fix(批次C): 多进程选主 + 计时器锁 + bootstrap 完成后再置位

- db.py 新增 leases 表与 acquire_lease/release_lease/lease_held_by_me:
  BEGIN IMMEDIATE 保证「读-判断-写」原子,多进程同时抢只有一个成功;
  租约表不可用时返回 None(老库/临时库),调用方按单进程处理,不会误拦
- app.bootstrap:抢 LEADER_LEASE(120s TTL,30s 续期)才启动采集/巡检/定时器/
  订阅/告警;非 leader 直接当 web worker。解决多 worker 下重复发信、
  重复自动还车、月卡重复扣费
- bootstrap 标志:新增 _bootstrap_started 防重入,_bootstrap_done 改为
  工作真正完成后再置位(原来先置 True,并发请求会以为已完成)
- timer._run_recovery:按 rental 抢 300 秒租约,跨进程只有一个进程去还这一单
- timer._active_timers:加 _timers_lock,取消时用 pop 一次取出(原来 in→del
  之间被删会 KeyError;del 会连带抹掉别的线程刚 append 的 timer,导致脱管)

测试:164 pytest(新增租约 3 条)+ 32 node 全绿
This commit is contained in:
zzy
2026-11-15 23:33:08 +08:00
parent 6847482447
commit d34b5bc375
4 changed files with 200 additions and 10 deletions
+44 -3
View File
@@ -660,15 +660,38 @@ def api_history_heatmap():
# WSGI 与 __main__ 都会调用,再由 before_request 兜住「首次请求」。
_bootstrap_lock = threading.Lock()
_bootstrap_done = False
_bootstrap_started = False
LEADER_LEASE = "xbcr-schedulers"
LEADER_TTL = 120 # 秒;持有者每 30 秒续期
def _start_leader_renewer():
"""leader 每 30 秒续一次租约;续不上就记日志(不自杀,避免抖动时全线停摆)。"""
def loop():
while True:
time.sleep(30)
try:
from db import acquire_lease, lease_held_by_me
if not acquire_lease(LEADER_LEASE, LEADER_TTL):
print("[启动] 后台线程租约已被其它进程接管(本进程不再续期)")
return
if not lease_held_by_me(LEADER_LEASE):
print("[启动] 租约校验失败,停止续期")
return
except Exception as exc:
print(f"[启动] 租约续期异常: {exc}")
threading.Thread(target=loop, daemon=True, name="leader-lease").start()
def bootstrap():
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
global _bootstrap_done
global _bootstrap_done, _bootstrap_started
with _bootstrap_lock:
if _bootstrap_done:
if _bootstrap_done or _bootstrap_started:
return False
_bootstrap_done = True
_bootstrap_started = True # 防重入;done 要等工作真正完成再置位
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
try:
@@ -676,6 +699,22 @@ def bootstrap():
except Exception as exc:
print(f"[启动] init_db 失败: {exc}")
# 多 worker 部署时后台线程只能有一份:靠 SQLite 租约选主。
# 抢不到就只当 web worker(不跑采集/巡检/定时器),否则会重复发信、
# 重复自动还车,月卡还会被扣两次。
try:
from db import acquire_lease
# None = 租约表不可用(老库/单进程):按 leader 处理
is_leader = acquire_lease(LEADER_LEASE, LEADER_TTL) is not False
except Exception as exc:
print(f"[启动] 选主失败,按 leader 处理(单进程部署可忽略): {exc}")
is_leader = True
if not is_leader:
print("[启动] 本进程不是 leader:跳过采集/巡检/定时器/调度线程")
print("[启动] bootstrap 完成(web worker)")
return True
_start_leader_renewer()
steps = [
("恢复计时器", restore_active_timers),
("补还超期订单", _sweep_on_boot),
@@ -700,6 +739,8 @@ def bootstrap():
except Exception as exc:
print(f"[启动] 告警调度失败: {exc}")
with _bootstrap_lock:
_bootstrap_done = True
print("[启动] bootstrap 完成")
return True