standalone.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import os
  2. import time
  3. import random
  4. import threading
  5. from datetime import datetime
  6. from typing import Dict, Callable, Optional
  7. from vs_types import BookerStandaloneConfig, QueryWaitMode, VSPlgConfig, VSQueryResult, VSBookResult, GroupStatus, PluginStatus, utc_now_str
  8. from vs_plg_factory import VSPlgFactory
  9. from utils.safe_redis_cli import SafeRedisClient
  10. from toolkit.proxy_manager import ProxyManager
  11. from toolkit.notifier import notify_date_changes, notify_book_result
  12. class StandaloneGCO:
  13. """
  14. Standalone GCO 实例管理器。
  15. 遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。
  16. """
  17. TAG = "STANDALONE"
  18. def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
  19. self.m_cfg = cfg
  20. self.m_logger = logger
  21. self.m_factory = VSPlgFactory()
  22. self.m_instance = None
  23. self.m_lock = threading.RLock()
  24. self.m_stop_event = threading.Event()
  25. self.m_last_login_time = 0
  26. self.m_next_query_time = 0
  27. self.m_next_keepalive_time = 0
  28. self.m_last_wait_log_time = 0.0
  29. self.m_current_dates = {}
  30. self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
  31. def _log(self, message: str):
  32. prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
  33. if self.m_logger:
  34. self.m_logger(f"{prefix} {message}")
  35. else:
  36. print(f"{prefix} {message}")
  37. def _get_wait_interval(self) -> float:
  38. """根据配置计算下一次查询的等待时间"""
  39. mode = self.m_cfg.query_wait.mode
  40. if mode == QueryWaitMode.Loop:
  41. return 1.0
  42. elif mode == QueryWaitMode.Fixed:
  43. return float(self.m_cfg.query_wait.fixed_wait)
  44. elif mode == QueryWaitMode.Random:
  45. return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
  46. return 30.0
  47. def _is_within_active_hours(self) -> bool:
  48. """判断当前是否在允许创建实例和查询的时间段内"""
  49. start_str = self.m_cfg.active_time_start
  50. end_str = self.m_cfg.active_time_end
  51. current_bj_time = datetime.utcnow().time()
  52. start_time = datetime.strptime(start_str, "%H:%M").time()
  53. end_time = datetime.strptime(end_str, "%H:%M").time()
  54. return start_time <= current_bj_time <= end_time
  55. def update_config(self, new_cfg: BookerStandaloneConfig):
  56. """动态更新配置"""
  57. with self.m_lock:
  58. if self.m_cfg.enable and not new_cfg.enable:
  59. self._log("Config dynamically updated: Group DISABLED.")
  60. elif not self.m_cfg.enable and new_cfg.enable:
  61. self._log("Config dynamically updated: Group ENABLED.")
  62. else:
  63. self._log("Config dynamically updated: Parameters refreshed.")
  64. self.m_cfg = new_cfg
  65. def get_status(self) -> GroupStatus:
  66. with self.m_lock:
  67. instance = self.m_instance
  68. gid = self.m_cfg.identifier
  69. enable = self.m_cfg.enable
  70. plugin_name = self.m_cfg.plugin_config.plugin_name
  71. plugins_status = []
  72. healthy_count = 0
  73. if instance:
  74. st = instance.get_plugin_status()
  75. if st.is_healthy:
  76. healthy_count += 1
  77. plugins_status.append(st)
  78. return GroupStatus(
  79. group_id=gid,
  80. enable=enable,
  81. plugin_name=plugin_name,
  82. total_tasks=1 if instance else 0,
  83. healthy_tasks=healthy_count,
  84. plugins=plugins_status,
  85. updated_at=utc_now_str(),
  86. )
  87. def start(self):
  88. """非阻塞启动,注册插件并开启后台工作线程"""
  89. if not self.m_cfg.enable:
  90. return
  91. self._log("Starting Standalone GCO...")
  92. plugin_name = self.m_cfg.plugin_config.plugin_name
  93. class_name = "".join(part.title() for part in plugin_name.split('_'))
  94. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  95. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  96. worker_name = f"Standalone-{self.m_cfg.identifier}"
  97. threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
  98. def stop(self):
  99. """优雅停止"""
  100. self._log("Stopping Standalone GCO...")
  101. self.m_stop_event.set()
  102. self._cleanup_instance("standalone stopped")
  103. def _cleanup_instance(self, reason: str = ""):
  104. with self.m_lock:
  105. if self.m_instance is not None:
  106. try:
  107. self._log(f"🧹 Cleaned up instance. Reason: {reason}")
  108. self.m_instance.cleanup()
  109. except Exception as e:
  110. self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
  111. finally:
  112. self.m_instance = None
  113. def _init_instance(self):
  114. """初始化单实例并进行登录创建会话"""
  115. self._cleanup_instance("recreating new session")
  116. now = time.time()
  117. if now < self.m_last_login_time + self.m_cfg.login_interval:
  118. wait_time = self.m_last_login_time + self.m_cfg.login_interval - now
  119. self._log(f"Waiting {int(wait_time)}s for login interval cooldown...")
  120. if self.m_stop_event.wait(wait_time):
  121. return
  122. plugin_name = self.m_cfg.plugin_config.plugin_name
  123. plg_cfg = VSPlgConfig()
  124. plg_cfg.debug = self.m_cfg.debug
  125. plg_cfg.account = self.m_cfg.account
  126. proxy = ProxyManager.Instance().get_next_proxy(self.m_cfg.proxy_pool, proxy_cd=600)
  127. plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
  128. plg_cfg.free_config = self.m_cfg.free_config
  129. plg_cfg.session_max_life = self.m_cfg.session_max_life
  130. instance = self.m_factory.create(self.m_cfg.identifier, plugin_name)
  131. instance.set_log(self.m_logger)
  132. instance.set_config(plg_cfg)
  133. with self.m_lock:
  134. self.m_instance = instance
  135. self._log("Creating session...")
  136. self.m_last_login_time = time.time()
  137. instance.create_session()
  138. interval = self._get_wait_interval()
  139. self.m_next_query_time = time.time() + interval
  140. self.m_next_keepalive_time = time.time() + 10.0
  141. self._log(f"Session created successfully. Initial query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')}).")
  142. def _worker_loop(self):
  143. """
  144. 后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定
  145. """
  146. self._log("Standalone worker loop started.")
  147. while not self.m_stop_event.is_set():
  148. try:
  149. if not self.m_cfg.enable:
  150. self.m_stop_event.wait(1.0)
  151. continue
  152. if not self._is_within_active_hours():
  153. self.m_stop_event.wait(5.0)
  154. continue
  155. # 1. 会话初始化
  156. if self.m_instance is None:
  157. try:
  158. self._init_instance()
  159. except Exception as e:
  160. self._cleanup_instance("session creation failed")
  161. cooldown = self.m_cfg.login_interval
  162. self._log(f"Failed to create session: {e}. Retrying in {int(cooldown)}s (login interval cooldown)...")
  163. self.m_stop_event.wait(cooldown)
  164. continue
  165. # 2. 健康检查
  166. if self.m_instance and not self.m_instance.health_check():
  167. self._log("Health check failed. Session dead. Recreating session...")
  168. self._cleanup_instance("session health check failed")
  169. continue
  170. # 3. 查询等待与周期性保活
  171. now = time.time()
  172. if now < self.m_next_query_time:
  173. remaining = self.m_next_query_time - now
  174. next_query_str = datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')
  175. keep_alive_sec = self.m_cfg.keep_alive
  176. # 周期性保活
  177. if self.m_instance and now >= self.m_next_keepalive_time:
  178. self.m_instance.keep_alive()
  179. self.m_next_keepalive_time = now + keep_alive_sec
  180. self._log(f"Session keepalive sent. Next query at {next_query_str} (remaining: {remaining:.0f}s)...")
  181. self.m_last_wait_log_time = now
  182. # 周期性显示等待倒计时(每隔 15 秒提示一次)
  183. elif now - self.m_last_wait_log_time >= 15.0 and remaining > 3.0:
  184. self.m_last_wait_log_time = now
  185. self._log(f"Waiting for next query at {next_query_str} (remaining: {remaining:.0f}s)...")
  186. wait_sec = min(remaining, 1.0)
  187. self.m_stop_event.wait(wait_sec)
  188. continue
  189. # 4. 随机选取 routing_key 进行查询
  190. apt_types = self.m_cfg.appointment_types
  191. if not apt_types:
  192. self.m_stop_event.wait(2.0)
  193. continue
  194. weights = [max(0.0, float(t.weight)) for t in apt_types]
  195. if sum(weights) > 0:
  196. apt_type = random.choices(apt_types, weights=weights, k=1)[0]
  197. else:
  198. apt_type = random.choice(apt_types)
  199. self._log(f"Querying slots for {apt_type.routing_key}...")
  200. query_result = self.m_instance.query(apt_type)
  201. query_result.apt_type = apt_type
  202. notify_date_changes(query_result, cache=self.m_current_dates, logger=self._log)
  203. # 5. 发现档期,执行自动预定
  204. if query_result.success:
  205. self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
  206. book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
  207. notify_book_result(book_result, logger=self._log)
  208. if book_result.success:
  209. self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
  210. # 预定成功后可继续或等待后续任务
  211. self.m_stop_event.wait(5.0)
  212. # 6. 在所有操作(包括抢单流程)执行完毕后,再统一计算并调度下一次查询时间与保活时间
  213. interval = self._get_wait_interval()
  214. now = time.time()
  215. self.m_next_query_time = now + interval
  216. keep_alive_sec = self.m_cfg.keep_alive
  217. self.m_next_keepalive_time = now + keep_alive_sec
  218. self.m_last_wait_log_time = now
  219. self._log(f"Next query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')})...")
  220. except Exception as e:
  221. self._log(f"Standalone loop exception: {e}")
  222. self.m_stop_event.wait(2.0)