fix: 选主看门狗 —— 抢不到后台租约不再永久残废(邮件不发/不自动还车)
线上症状:提醒邮件到点不发、19 分钟也不自动还车;用户打开网页(前端自己调 还车接口)才还车。 根因 - bootstrap() 靠 SQLite 租约选主;容器重启时上一个进程的租约最长还有 120 秒 有效期,新进程一上来必然抢不到 - 旧实现:非 leader 直接 return True,且 _bootstrap_started 保持 True, 后续所有 bootstrap() 调用(含 before_request 的兜底)都直接返回 False → 这个进程**永远**不跑恢复计时器/巡检/自动还车/订阅/告警 - 唯一能把车还掉的只剩前端页面 —— 于是表现为「必须打开网页才还车」 改法 - 把「启动后台线程」拆成幂等的 _start_background_once() - 新增 _ensure_background_running():已启动→每轮续租(续不上大声报错); 没启动→尝试抢租约,抢到立刻启动(含 restore_active_timers + _sweep_on_boot, 落后期间错过的超期单会在接管那一刻补还) - 新增 _start_leader_watchdog():**所有进程都挂**,每 30 秒续租/重试接管, 不再只在 leader 进程里跑 - bootstrap():非 leader 也置 _bootstrap_done(避免每请求重入),并挂看门狗 - 连续抢不到租约时每 10 轮(约 5 分钟)打一条 [启动][警告] 日志,避免再次静默 测试 - 新增 tests/test_leader_watchdog.py 4 例:租约被占→不启动;租约释放→接管且 只启动一次;续租失败→返回 False;非 leader 也挂看门狗;bootstrap 幂等 - 全量 238 passed(234 + 4) - 真进程验证:残留旧租约(旧 PID 已死)→ 新进程 bootstrap 为非 leader → 32 秒后看门狗接管(leases.owner 变为新 PID),此后每 30 秒续期
This commit is contained in:
@@ -830,61 +830,30 @@ LEADER_LEASE = "xbcr-schedulers"
|
|||||||
LEADER_TTL = 120 # 秒;持有者每 30 秒续期
|
LEADER_TTL = 120 # 秒;持有者每 30 秒续期
|
||||||
|
|
||||||
|
|
||||||
def _start_leader_renewer():
|
_background_started = False
|
||||||
"""leader 每 30 秒续一次租约;续不上就记日志(不自杀,避免抖动时全线停摆)。"""
|
_background_lock = threading.Lock()
|
||||||
def loop():
|
_leader_watchdog_started = False
|
||||||
while True:
|
_leader_watchdog_lock = threading.Lock()
|
||||||
time.sleep(30)
|
_leadership_misses = 0 # 连续抢不到租约的轮数(只用于告警日志)
|
||||||
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():
|
def _try_acquire_leadership() -> bool:
|
||||||
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
|
"""尝试成为后台线程的唯一持有者。异常时按 leader 处理(单进程部署)。"""
|
||||||
global _bootstrap_done, _bootstrap_started
|
|
||||||
with _bootstrap_lock:
|
|
||||||
if _bootstrap_done or _bootstrap_started:
|
|
||||||
return False
|
|
||||||
_bootstrap_started = True # 防重入;done 要等工作真正完成再置位
|
|
||||||
|
|
||||||
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
|
|
||||||
try:
|
|
||||||
init_db()
|
|
||||||
except Exception as exc:
|
|
||||||
print(f"[启动] init_db 失败: {exc}")
|
|
||||||
|
|
||||||
# 多 worker 部署时后台线程只能有一份:靠 SQLite 租约选主。
|
|
||||||
# 抢不到就只当 web worker(不跑采集/巡检/定时器),否则会重复发信、
|
|
||||||
# 重复自动还车,月卡还会被扣两次。
|
|
||||||
try:
|
try:
|
||||||
from db import acquire_lease
|
from db import acquire_lease
|
||||||
# None = 租约表不可用(老库/单进程):按 leader 处理
|
return acquire_lease(LEADER_LEASE, LEADER_TTL) is not False
|
||||||
is_leader = acquire_lease(LEADER_LEASE, LEADER_TTL) is not False
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"[启动] 选主失败,按 leader 处理(单进程部署可忽略): {exc}")
|
print(f"[启动] 选主失败,按 leader 处理(单进程部署可忽略): {exc}")
|
||||||
is_leader = True
|
|
||||||
# 测试/工具场景:只要数据库和路由,不启动任何后台线程(避免采集线程写库
|
|
||||||
# 干扰用例的统计断言)
|
|
||||||
if os.environ.get("XBCR_DISABLE_BACKGROUND") == "1":
|
|
||||||
print("[启动] XBCR_DISABLE_BACKGROUND=1:只初始化数据库,不启动后台线程")
|
|
||||||
with _bootstrap_lock:
|
|
||||||
_bootstrap_done = True
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
if not is_leader:
|
|
||||||
print("[启动] 本进程不是 leader:跳过采集/巡检/定时器/调度线程")
|
def _start_background_once() -> bool:
|
||||||
print("[启动] bootstrap 完成(web worker)")
|
"""启动采集/巡检/定时器/订阅/告警,**只启动一次**。返回本次是否真的启动了。"""
|
||||||
return True
|
global _background_started
|
||||||
_start_leader_renewer()
|
with _background_lock:
|
||||||
|
if _background_started:
|
||||||
|
return False
|
||||||
|
_background_started = True
|
||||||
|
|
||||||
steps = [
|
steps = [
|
||||||
("恢复计时器", restore_active_timers),
|
("恢复计时器", restore_active_timers),
|
||||||
@@ -909,6 +878,106 @@ def bootstrap():
|
|||||||
start_alert_scheduler()
|
start_alert_scheduler()
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
print(f"[启动] 告警调度失败: {exc}")
|
print(f"[启动] 告警调度失败: {exc}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_background_running() -> bool:
|
||||||
|
"""后台线程的守护逻辑(看门狗每 30 秒调一次)。
|
||||||
|
|
||||||
|
- 已经在跑:续租约;续不上就大声记日志(线程无法优雅停止,只能告警)。
|
||||||
|
- 还没跑:尝试抢租约,抢到就启动后台线程。
|
||||||
|
|
||||||
|
这里之所以要"每 30 秒重试一次",是因为容器重启时上一个进程的租约还活着
|
||||||
|
(TTL 120 秒):新进程一上来必然是"非 leader",若只试一次就放弃,这个
|
||||||
|
进程会**永远**不发提醒邮件、永远不自动还车 —— 用户看到的现象就是
|
||||||
|
"到点了既不提醒也不还车,只有打开网页(前端自己调还车接口)才还"。
|
||||||
|
"""
|
||||||
|
from db import acquire_lease, lease_held_by_me
|
||||||
|
if _background_started:
|
||||||
|
try:
|
||||||
|
if acquire_lease(LEADER_LEASE, LEADER_TTL) is False:
|
||||||
|
print("[启动] 后台线程租约已被其它进程接管(本进程不再续期)")
|
||||||
|
return False
|
||||||
|
if not lease_held_by_me(LEADER_LEASE):
|
||||||
|
print("[启动] 租约校验失败(可能已过期被接管)")
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 租约续期异常: {exc}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
if not _try_acquire_leadership():
|
||||||
|
global _leadership_misses
|
||||||
|
_leadership_misses += 1
|
||||||
|
# 每 10 轮(约 5 分钟)提醒一次:长时间抢不到租约等于"这个进程不发提醒、
|
||||||
|
# 不自动还车",必须在日志里能看见,不能又变成静默残废。
|
||||||
|
if _leadership_misses % 10 == 0:
|
||||||
|
print(f"[启动][警告] 已连续 {_leadership_misses} 轮抢不到后台线程租约"
|
||||||
|
f"(约 {_leadership_misses * 30 // 60} 分钟):本进程不跑提醒/自动还车,"
|
||||||
|
f"请检查是否有残留 leases 行或另一个进程在位")
|
||||||
|
return False
|
||||||
|
_leadership_misses = 0
|
||||||
|
print("[启动] 拿到后台线程租约,开始启动采集/巡检/定时器/订阅/告警")
|
||||||
|
_start_background_once()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _start_leader_watchdog():
|
||||||
|
"""常驻看门狗:每 30 秒续租/重试接管。**所有进程都启动**,不只是 leader。"""
|
||||||
|
global _leader_watchdog_started
|
||||||
|
with _leader_watchdog_lock:
|
||||||
|
if _leader_watchdog_started:
|
||||||
|
return
|
||||||
|
_leader_watchdog_started = True
|
||||||
|
|
||||||
|
def loop():
|
||||||
|
while True:
|
||||||
|
time.sleep(30)
|
||||||
|
try:
|
||||||
|
_ensure_background_running()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] 选主/续租异常: {exc}")
|
||||||
|
|
||||||
|
threading.Thread(target=loop, daemon=True, name="leader-watchdog").start()
|
||||||
|
|
||||||
|
|
||||||
|
def bootstrap():
|
||||||
|
"""初始化数据库并启动所有后台线程。幂等:重复调用只会执行一次。"""
|
||||||
|
global _bootstrap_done, _bootstrap_started
|
||||||
|
with _bootstrap_lock:
|
||||||
|
if _bootstrap_done or _bootstrap_started:
|
||||||
|
return False
|
||||||
|
_bootstrap_started = True # 防重入;done 要等工作真正完成再置位
|
||||||
|
|
||||||
|
print("[启动] bootstrap: 初始化数据库 + 启动后台线程")
|
||||||
|
try:
|
||||||
|
init_db()
|
||||||
|
except Exception as exc:
|
||||||
|
print(f"[启动] init_db 失败: {exc}")
|
||||||
|
|
||||||
|
# 多 worker 部署时后台线程只能有一份:靠 SQLite 租约选主。
|
||||||
|
# 抢不到就先当 web worker(不跑采集/巡检/定时器),否则会重复发信、
|
||||||
|
# 重复自动还车,月卡还会被扣两次。
|
||||||
|
#
|
||||||
|
# 注意:**抢不到只是"暂时"**。容器重启时上一个进程的租约最长还有 120 秒,
|
||||||
|
# 新进程一上来必然抢不到;所以后面一定要挂看门狗每 30 秒重试接管,
|
||||||
|
# 否则这个进程会永远不发提醒、永远不自动还车(只有前端打开页面才还)。
|
||||||
|
is_leader = _try_acquire_leadership()
|
||||||
|
if not is_leader:
|
||||||
|
print("[启动] 本进程暂时不是 leader(可能有残留租约):"
|
||||||
|
"由看门狗每 30 秒重试接管")
|
||||||
|
# 测试/工具场景:只要数据库和路由,不启动任何后台线程(避免采集线程写库
|
||||||
|
# 干扰用例的统计断言)
|
||||||
|
if os.environ.get("XBCR_DISABLE_BACKGROUND") == "1":
|
||||||
|
print("[启动] XBCR_DISABLE_BACKGROUND=1:只初始化数据库,不启动后台线程")
|
||||||
|
with _bootstrap_lock:
|
||||||
|
_bootstrap_done = True
|
||||||
|
return True
|
||||||
|
|
||||||
|
if is_leader:
|
||||||
|
_start_background_once()
|
||||||
|
# 不管本进程是不是 leader,都要挂看门狗:租约到期/被释放后由它接管。
|
||||||
|
_start_leader_watchdog()
|
||||||
|
|
||||||
with _bootstrap_lock:
|
with _bootstrap_lock:
|
||||||
_bootstrap_done = True
|
_bootstrap_done = True
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""选主看门狗:抢不到后台线程租约时必须持续重试,不能一次放弃。
|
||||||
|
|
||||||
|
线上真实故障(BUG):容器重启时上一个进程的租约还有效(TTL 120 秒),新进程
|
||||||
|
一上来必然抢不到 → 旧实现直接 `return True` 且不再重试 → 这个进程**永远**
|
||||||
|
不发提醒邮件、永远不自动还车;用户看到的是「到点没邮件、也不还车,只有自己
|
||||||
|
打开网页(前端调还车接口)才还」。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import db
|
||||||
|
import app as app_mod
|
||||||
|
|
||||||
|
|
||||||
|
class LeaderWatchdogTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
# 其它用例会在进程内设 XBCR_DISABLE_BACKGROUND=1(只建库不起线程),
|
||||||
|
# 那会让 bootstrap() 在选主之前就返回,测不到看门狗。
|
||||||
|
self._env_backup = os.environ.pop("XBCR_DISABLE_BACKGROUND", None)
|
||||||
|
app_mod._leadership_misses = 0
|
||||||
|
app_mod._background_started = False
|
||||||
|
app_mod._bootstrap_started = False
|
||||||
|
app_mod._bootstrap_done = False
|
||||||
|
app_mod._leader_watchdog_started = False
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
if self._env_backup is not None:
|
||||||
|
os.environ["XBCR_DISABLE_BACKGROUND"] = self._env_backup
|
||||||
|
app_mod._leadership_misses = 0
|
||||||
|
app_mod._background_started = False
|
||||||
|
app_mod._bootstrap_started = False
|
||||||
|
app_mod._bootstrap_done = False
|
||||||
|
app_mod._leader_watchdog_started = False
|
||||||
|
|
||||||
|
def test_retries_until_lease_is_free(self):
|
||||||
|
"""租约被别人占着 → 不启动;租约释放后 → 立刻接管并只启动一次。"""
|
||||||
|
started = []
|
||||||
|
|
||||||
|
def fake_start():
|
||||||
|
# 真实实现会在内部置 _background_started,这里照做(否则测不到「只启动一次」)
|
||||||
|
started.append(1)
|
||||||
|
app_mod._background_started = True
|
||||||
|
return True
|
||||||
|
|
||||||
|
with patch.object(app_mod, "_start_background_once", side_effect=fake_start), \
|
||||||
|
patch.object(app_mod, "_try_acquire_leadership", return_value=False):
|
||||||
|
self.assertFalse(app_mod._ensure_background_running())
|
||||||
|
self.assertEqual([], started, "抢不到租约时不应启动后台线程")
|
||||||
|
|
||||||
|
# 租约到期/被释放:下一轮看门狗应该接管
|
||||||
|
with patch.object(app_mod, "_start_background_once", side_effect=fake_start), \
|
||||||
|
patch.object(app_mod, "_try_acquire_leadership", return_value=True), \
|
||||||
|
patch.object(db, "acquire_lease", return_value=True), \
|
||||||
|
patch.object(db, "lease_held_by_me", return_value=True):
|
||||||
|
self.assertTrue(app_mod._ensure_background_running())
|
||||||
|
self.assertEqual(1, len(started), "拿到租约后应启动一次后台线程")
|
||||||
|
# 再走一轮:已经启动过,不应重复启动
|
||||||
|
app_mod._ensure_background_running()
|
||||||
|
self.assertEqual(1, len(started), "后台线程不能重复启动")
|
||||||
|
|
||||||
|
def test_renew_failure_is_reported(self):
|
||||||
|
"""已经在跑但续租失败 → 返回 False(调用方据此记日志/告警)。"""
|
||||||
|
app_mod._background_started = True
|
||||||
|
with patch.object(db, "acquire_lease", return_value=False):
|
||||||
|
self.assertFalse(app_mod._ensure_background_running())
|
||||||
|
|
||||||
|
def test_bootstrap_arms_watchdog_even_when_not_leader(self):
|
||||||
|
"""非 leader 也要把看门狗挂上,否则永远没有接管机会。"""
|
||||||
|
watchdog = []
|
||||||
|
with patch.object(app_mod, "init_db"), \
|
||||||
|
patch.object(app_mod, "_try_acquire_leadership", return_value=False), \
|
||||||
|
patch.object(app_mod, "_start_background_once") as bg, \
|
||||||
|
patch.object(app_mod, "_start_leader_watchdog",
|
||||||
|
side_effect=lambda: watchdog.append(1)):
|
||||||
|
self.assertTrue(app_mod.bootstrap())
|
||||||
|
|
||||||
|
self.assertEqual([], bg.call_args_list, "非 leader 不应启动后台线程")
|
||||||
|
self.assertEqual(1, len(watchdog), "非 leader 也必须挂看门狗")
|
||||||
|
self.assertTrue(app_mod._bootstrap_done, "非 leader 也要置 done,避免每个请求重入")
|
||||||
|
|
||||||
|
def test_bootstrap_starts_background_as_leader_and_is_idempotent(self):
|
||||||
|
with patch.object(app_mod, "init_db"), \
|
||||||
|
patch.object(app_mod, "_try_acquire_leadership", return_value=True), \
|
||||||
|
patch.object(app_mod, "_start_background_once") as bg, \
|
||||||
|
patch.object(app_mod, "_start_leader_watchdog"):
|
||||||
|
self.assertTrue(app_mod.bootstrap())
|
||||||
|
self.assertTrue(app_mod._bootstrap_done)
|
||||||
|
bg.assert_called_once()
|
||||||
|
# 第二次调用(before_request 每秒都在调)不应重复启动
|
||||||
|
self.assertFalse(app_mod.bootstrap())
|
||||||
|
bg.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user