instance_guard.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. # This Python file uses the following encoding: utf-8
  2. # @author handman123
  3. # github https://github.com/runhey
  4. """跨进程实例看守器。
  5. 通过共享 JSON 状态文件协调多个进程的实例执行顺序,确保同一时间
  6. 只有一个实例操作模拟器。持有执行权(token)的实例可执行任务,
  7. 其他实例排队等待。
  8. """
  9. import json
  10. import threading
  11. from pathlib import Path
  12. from datetime import datetime
  13. from filelock import FileLock
  14. from module.logger import logger
  15. class _QueueState:
  16. """共享状态文件的持久化层。
  17. 负责 JSON 文件的原子读写和持有者心跳过期判断。
  18. 文件锁(FileLock)保证跨进程写入安全。
  19. 文件格式:
  20. {
  21. "current": "oas1", # 当前持有执行权的实例名
  22. "timestamp": "2026-07-08 ...", # 持有者心跳时间戳
  23. "queue": ["oas2", "oas3"] # 等待队列
  24. }
  25. """
  26. STATE_FILE = Path.cwd() / "log" / ".queue_state.json"
  27. STALE_TIMEOUT = 300 # 心跳超时 5 分钟,超过视为持有者崩溃
  28. def __init__(self, config_name: str):
  29. """Args:
  30. config_name: 配置文件名称,如 'oas1'。
  31. """
  32. self.config_name = config_name
  33. self._lock = FileLock(str(self.STATE_FILE) + ".lock", timeout=5)
  34. def read(self) -> dict:
  35. """读取状态文件。
  36. 调用方需持有 _lock。文件不存在或损坏时返回空状态。
  37. Returns:
  38. dict: 包含 current、timestamp、queue 的状态字典。
  39. """
  40. if not self.STATE_FILE.exists():
  41. return {"current": None, "timestamp": None, "queue": []}
  42. try:
  43. with open(self.STATE_FILE, "r", encoding="utf-8") as f:
  44. return json.load(f)
  45. except (json.JSONDecodeError, IOError):
  46. logger.warning("[InstanceGuard] State file corrupted, resetting")
  47. return {"current": None, "timestamp": None, "queue": []}
  48. def write(self, state: dict) -> None:
  49. """写入状态文件。调用方需持有 _lock。"""
  50. self.STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
  51. with open(self.STATE_FILE, "w", encoding="utf-8") as f:
  52. json.dump(state, f, indent=2, ensure_ascii=False)
  53. def is_stale(self, state: dict) -> bool:
  54. """判断持有者心跳是否过期。
  55. 如果 timestamp 距现在超过 STALE_TIMEOUT 秒,认为持有者崩溃。
  56. Args:
  57. state: 从 read() 获取的状态字典。
  58. Returns:
  59. bool: True 表示心跳过期,可安全接管。
  60. """
  61. ts_str = state.get("timestamp")
  62. if not ts_str:
  63. return False
  64. try:
  65. ts = datetime.fromisoformat(ts_str)
  66. elapsed = (datetime.now() - ts).total_seconds()
  67. return elapsed > self.STALE_TIMEOUT
  68. except (ValueError, TypeError):
  69. return True
  70. def __enter__(self):
  71. self._lock.acquire()
  72. return self.read()
  73. def __exit__(self, *args):
  74. self._lock.release()
  75. class _Heartbeat:
  76. """心跳保活线程。
  77. 持有 token 期间定期更新 timestamp,防止被误判崩溃。
  78. 同时监控 token 是否被其他实例抢占(例如被管理员从状态文件强制接管),
  79. 检测到丢失时设置 token_lost 标志通知主线程。
  80. """
  81. INTERVAL = 180 # 心跳间隔 3 分钟,小于 STALE_TIMEOUT(5min) 留出缓冲
  82. def __init__(self, config_name: str, state: _QueueState):
  83. self._config_name = config_name
  84. self._state = state
  85. self._thread: threading.Thread = None
  86. self._stop_event: threading.Event = None
  87. self._token_lost = threading.Event()
  88. @property
  89. def token_lost(self) -> bool:
  90. """token 是否被其他实例抢占。"""
  91. return self._token_lost.is_set()
  92. def start(self) -> None:
  93. """启动心跳 daemon 线程。已运行则跳过。"""
  94. if self._thread and self._thread.is_alive():
  95. return
  96. self._token_lost.clear()
  97. self._stop_event = threading.Event()
  98. self._thread = threading.Thread(target=self._loop, daemon=True)
  99. self._thread.start()
  100. logger.info(
  101. f"[InstanceGuard] Heartbeat started for '{self._config_name}'")
  102. def stop(self) -> None:
  103. """停止心跳线程。"""
  104. if self._stop_event:
  105. self._stop_event.set()
  106. self._thread = None
  107. self._stop_event = None
  108. def _loop(self) -> None:
  109. """心跳循环。每 INTERVAL 秒刷新 timestamp。"""
  110. while not self._stop_event.wait(timeout=self.INTERVAL):
  111. try:
  112. with self._state._lock:
  113. state = self._state.read()
  114. if state["current"] == self._config_name:
  115. state["timestamp"] = datetime.now().isoformat()
  116. self._state.write(state)
  117. elif self._config_name not in state.get("queue", []):
  118. # 不在 current 也不在 queue,说明被强制移除了
  119. logger.warning(
  120. f"[InstanceGuard] '{self._config_name}' lost token, "
  121. f"current holder: {state['current']}")
  122. self._token_lost.set()
  123. return
  124. except Exception as e:
  125. logger.error(f"[InstanceGuard] Heartbeat error: {e}")
  126. class InstanceGuard:
  127. """跨进程实例看守器。
  128. 通过共享状态文件协调多个实例的执行顺序,确保同一时间只有一个实例
  129. 操作模拟器。集成心跳保活和崩溃检测。
  130. 用法:
  131. guard = InstanceGuard(config_name)
  132. if guard.try_acquire():
  133. # 执行业务逻辑
  134. guard.release()
  135. """
  136. def __init__(self, config_name: str):
  137. """Args:
  138. config_name: 配置文件名称。
  139. """
  140. self.config_name = config_name
  141. self._state = _QueueState(config_name)
  142. self._heartbeat = _Heartbeat(config_name, self._state)
  143. @property
  144. def token_lost(self) -> bool:
  145. """token 是否被其他实例抢占。"""
  146. return self._heartbeat.token_lost
  147. # ==================== 执行权操作 ====================
  148. def try_acquire(self) -> bool:
  149. """尝试获取执行权。
  150. 四种情况:
  151. 1. 自己已是持有者 — 刷新 heartbeat,返回 True
  152. 2. 持有者心跳过期 — 强制接管,返回 True
  153. 3. 无人持有 — 自己成为持有者,启动心跳,返回 True
  154. 4. 他人持有 — 加入等待队列,返回 False
  155. Returns:
  156. True: 已获得执行权。
  157. False: 执行权被他人持有,已加入队列。
  158. """
  159. with self._state._lock:
  160. state = self._state.read()
  161. # 自己已是持有者,刷新心跳
  162. if state["current"] == self.config_name:
  163. state["timestamp"] = datetime.now().isoformat()
  164. self._state.write(state)
  165. return True
  166. # 持有者崩溃,强制接管
  167. if state["current"] and self._state.is_stale(state):
  168. logger.warning(
  169. f"[InstanceGuard] Holder '{state['current']}' "
  170. f"heartbeat stale, taking over")
  171. state["current"] = None
  172. state["timestamp"] = None
  173. # 无人持有,自己成为持有者
  174. if state["current"] is None:
  175. state["current"] = self.config_name
  176. state["timestamp"] = datetime.now().isoformat()
  177. if self.config_name in state["queue"]:
  178. state["queue"].remove(self.config_name)
  179. self._state.write(state)
  180. logger.info(
  181. f"[InstanceGuard] '{self.config_name}' acquired token")
  182. self._heartbeat.start()
  183. return True
  184. # 他人持有,加入等待队列
  185. if self.config_name not in state["queue"]:
  186. state["queue"].append(self.config_name)
  187. self._state.write(state)
  188. logger.info(
  189. f"[InstanceGuard] '{self.config_name}' waiting, "
  190. f"holder: '{state['current']}', "
  191. f"queue: {state['queue']}")
  192. return False
  193. def release(self) -> None:
  194. """释放执行权。
  195. 停止心跳线程。如果等待队列非空,自动移交给下一个实例。
  196. 如果自己不是持有者,静默返回。
  197. """
  198. with self._state._lock:
  199. state = self._state.read()
  200. if state["current"] != self.config_name:
  201. return
  202. self._heartbeat.stop()
  203. if state["queue"]:
  204. next_holder = state["queue"].pop(0)
  205. state["current"] = next_holder
  206. state["timestamp"] = datetime.now().isoformat()
  207. logger.info(
  208. f"[InstanceGuard] '{self.config_name}' released token "
  209. f"→ '{next_holder}'")
  210. else:
  211. state["current"] = None
  212. state["timestamp"] = None
  213. logger.info(
  214. f"[InstanceGuard] '{self.config_name}' released token, "
  215. f"queue empty")
  216. self._state.write(state)
  217. def should_release(self, pending_task: list, waiting_task: list,
  218. idle_threshold_minutes: int = 10) -> bool:
  219. """判断是否应该在进入空闲前释放执行权。
  220. 条件:
  221. 1. pending_task 为空(当前无待执行任务)
  222. 2. waiting_task 为空,或最早的任务距现在超过 idle_threshold_minutes 分钟
  223. Args:
  224. pending_task: 当前到期的任务列表。
  225. waiting_task: 未来任务列表,按 next_run 升序。
  226. idle_threshold_minutes: 空闲阈值(分钟)。
  227. Returns:
  228. True: 空闲时间足够长,应释放执行权。
  229. False: 即将有任务,应继续持有。
  230. """
  231. if pending_task:
  232. return False
  233. if not waiting_task:
  234. return True
  235. next_task_time = waiting_task[0].next_run
  236. idle_seconds = (next_task_time - datetime.now()).total_seconds()
  237. return idle_seconds > idle_threshold_minutes * 60
  238. def remove_from_queue(self) -> None:
  239. """从排队系统中完全移除自己。
  240. 进程停止时调用,防止残留状态导致死锁。
  241. 如果自己是持有者,将执行权移交给下一个等待者。
  242. """
  243. with self._state._lock:
  244. state = self._state.read()
  245. if self.config_name in state["queue"]:
  246. state["queue"].remove(self.config_name)
  247. logger.info(
  248. f"[InstanceGuard] '{self.config_name}' removed from queue")
  249. if state["current"] == self.config_name:
  250. self._heartbeat.stop()
  251. if state["queue"]:
  252. next_holder = state["queue"].pop(0)
  253. state["current"] = next_holder
  254. state["timestamp"] = datetime.now().isoformat()
  255. logger.info(
  256. f"[InstanceGuard] '{self.config_name}' removed, "
  257. f"token → '{next_holder}'")
  258. else:
  259. state["current"] = None
  260. state["timestamp"] = None
  261. self._state.write(state)
  262. return
  263. self._state.write(state)