standalone.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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 core_types import (
  8. BookerStandaloneConfig,
  9. QueryWaitMode,
  10. PluginConfig,
  11. QueryResult,
  12. BookResult,
  13. GroupStatus,
  14. PluginStatus,
  15. utc_now_str,
  16. BizException,
  17. RateLimiteddError,
  18. SessionExpiredOrInvalidError,
  19. PermissionDeniedError,
  20. NetworkTimeoutError
  21. )
  22. from plugin_factory import PluginFactory
  23. from utils.safe_redis_cli import SafeRedisClient
  24. from toolkit.proxy_manager import ProxyManager
  25. from toolkit.cloud_api import CloudApi
  26. from toolkit.notifier import notify_date_changes, notify_book_result
  27. class StandaloneGCO:
  28. """
  29. Standalone GCO 实例管理器。
  30. 遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。
  31. """
  32. TAG = "STANDALONE"
  33. def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
  34. self.m_cfg = cfg
  35. self.m_logger = logger
  36. self.m_factory = PluginFactory()
  37. self.m_instance = None
  38. self.m_lock = threading.RLock()
  39. self.m_stop_event = threading.Event()
  40. self.m_last_login_time = 0
  41. self.m_next_query_time = 0
  42. self.m_next_keepalive_time = 0
  43. self.m_last_wait_log_time = 0.0
  44. self.m_current_dates = {}
  45. self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
  46. def _log(self, message: str):
  47. prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
  48. if self.m_logger:
  49. self.m_logger(f"{prefix} {message}")
  50. else:
  51. print(f"{prefix} {message}")
  52. def _get_wait_interval(self) -> float:
  53. """根据配置计算下一次查询的等待时间"""
  54. mode = self.m_cfg.query_wait.mode
  55. if mode == QueryWaitMode.Loop:
  56. return 1.0
  57. elif mode == QueryWaitMode.Fixed:
  58. return float(self.m_cfg.query_wait.fixed_wait)
  59. elif mode == QueryWaitMode.Random:
  60. return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
  61. return 30.0
  62. def _is_within_active_hours(self) -> bool:
  63. """判断当前是否在允许创建实例和查询的时间段内"""
  64. start_str = self.m_cfg.active_time_start
  65. end_str = self.m_cfg.active_time_end
  66. current_bj_time = datetime.utcnow().time()
  67. start_time = datetime.strptime(start_str, "%H:%M").time()
  68. end_time = datetime.strptime(end_str, "%H:%M").time()
  69. return start_time <= current_bj_time <= end_time
  70. def update_config(self, new_cfg: BookerStandaloneConfig):
  71. """动态更新配置"""
  72. with self.m_lock:
  73. if self.m_cfg.enable and not new_cfg.enable:
  74. self._log("Config dynamically updated: Group DISABLED.")
  75. elif not self.m_cfg.enable and new_cfg.enable:
  76. self._log("Config dynamically updated: Group ENABLED.")
  77. else:
  78. self._log("Config dynamically updated: Parameters refreshed.")
  79. self.m_cfg = new_cfg
  80. def get_status(self) -> GroupStatus:
  81. with self.m_lock:
  82. instance = self.m_instance
  83. gid = self.m_cfg.identifier
  84. enable = self.m_cfg.enable
  85. plugin_name = self.m_cfg.plugin_config.plugin_name
  86. plugins_status = []
  87. healthy_count = 0
  88. if instance:
  89. st = instance.get_plugin_status()
  90. if st.is_healthy:
  91. healthy_count += 1
  92. plugins_status.append(st)
  93. return GroupStatus(
  94. group_id=gid,
  95. enable=enable,
  96. plugin_name=plugin_name,
  97. total_tasks=1 if instance else 0,
  98. healthy_tasks=healthy_count,
  99. plugins=plugins_status,
  100. updated_at=utc_now_str(),
  101. )
  102. def start(self):
  103. """非阻塞启动,注册插件并开启后台工作线程"""
  104. if not self.m_cfg.enable:
  105. return
  106. self._log("Starting Standalone GCO...")
  107. plugin_name = self.m_cfg.plugin_config.plugin_name
  108. class_name = "".join(part.title() for part in plugin_name.split('_'))
  109. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  110. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  111. worker_name = f"Standalone-{self.m_cfg.identifier}"
  112. threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
  113. def stop(self):
  114. """优雅停止"""
  115. self._log("Stopping Standalone GCO...")
  116. self.m_stop_event.set()
  117. self._cleanup_instance("standalone stopped")
  118. def _cleanup_instance(self, reason: str = ""):
  119. with self.m_lock:
  120. if self.m_instance is not None:
  121. try:
  122. self._log(f"🧹 Cleaned up instance. Reason: {reason}")
  123. self.m_instance.cleanup()
  124. except Exception as e:
  125. self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
  126. finally:
  127. self.m_instance = None
  128. def _init_instance(self):
  129. """初始化单实例并进行登录创建会话"""
  130. self._cleanup_instance("recreating new session")
  131. now = time.time()
  132. if now < self.m_last_login_time + self.m_cfg.login_interval:
  133. wait_time = self.m_last_login_time + self.m_cfg.login_interval - now
  134. self._log(f"Waiting {int(wait_time)}s for login interval cooldown...")
  135. if self.m_stop_event.wait(wait_time):
  136. return
  137. plugin_name = self.m_cfg.plugin_config.plugin_name
  138. plg_cfg = PluginConfig()
  139. plg_cfg.debug = self.m_cfg.debug
  140. plg_cfg.account = self.m_cfg.account
  141. proxy = ProxyManager.Instance().get_next_proxy(self.m_cfg.proxy_pool, proxy_cd=600)
  142. plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
  143. plg_cfg.free_config = self.m_cfg.free_config
  144. plg_cfg.session_max_life = self.m_cfg.session_max_life
  145. instance = self.m_factory.create(self.m_cfg.identifier, plugin_name)
  146. instance.set_log(self.m_logger)
  147. instance.set_config(plg_cfg)
  148. with self.m_lock:
  149. self.m_instance = instance
  150. self._log("Creating session...")
  151. instance.create_session()
  152. self.m_last_login_time = time.time()
  153. interval = self._get_wait_interval()
  154. self.m_next_query_time = time.time() + interval
  155. self.m_next_keepalive_time = time.time() + 10.0
  156. 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')}).")
  157. def _normalize_error(self, err: Exception) -> BizException:
  158. """
  159. 将任意异常规整化为领域异常 BizException。
  160. 保留对未结构化历史异常字符串特征的兜底兼容识别。
  161. """
  162. if isinstance(err, BizException):
  163. return err
  164. err_str = str(err)
  165. if "42901" in err_str or "Rate limited" in err_str:
  166. return RateLimiteddError(message=err_str)
  167. if "40101" in err_str or "Session expired" in err_str or "session invalid" in err_str.lower():
  168. return SessionExpiredOrInvalidError(message=err_str)
  169. if "40301" in err_str or "403" in err_str or "Cloudflare Access Denied" in err_str:
  170. return PermissionDeniedError(message=err_str)
  171. return BizException(
  172. code=50000,
  173. message=f"Unhandled ({type(err).__name__}): {err_str}",
  174. )
  175. def _dispatch_error_policy(self, action: str, err: Exception) -> None:
  176. """
  177. Standalone 错误调度与自愈策略引擎 (Policy Engine):
  178. 基于 (Action, 异常事实类型) 矩阵 + Standalone 单机模式 + 本组配置闭环执行自愈动作:
  179. - create_session/login 时 429:判定为账号级限流,锁定账号,执行 login_interval 退避等待;
  180. - query 时 429:会话已建立,判定为出口 IP 频率超限,不锁定账号,销毁实例触发下轮代理轮换;
  181. - session expired / 401:销毁当前实例,重置下一次查询时间为 5s 后以触发重新登录;
  182. - 403 Forbidden / WAF:判定为 IP 被封,清理实例换 IP 并退避;
  183. - 内部直接完成日志输出与定时器维护,调用方无需感知具体冷却数值。
  184. """
  185. biz_err = self._normalize_error(err)
  186. acc = self.m_cfg.account if (self.m_cfg.account and self.m_cfg.account.username not in ("", "Guest")) else None
  187. # 1. 目标站限流 / 429
  188. if isinstance(biz_err, RateLimiteddError):
  189. if action in ("create_session", "login", "spawn"):
  190. backoff = float(self.m_cfg.login_interval)
  191. self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
  192. if acc and getattr(acc, "id", 0):
  193. try:
  194. CloudApi.Instance().lock_account(acc.id, int(backoff))
  195. self._log(f"🔒 Account [{acc.username}] locked for {int(backoff)}s via Cloud API.")
  196. except Exception as lock_err:
  197. self._log(f"Failed to lock account via cloud API: {lock_err}")
  198. self.m_last_login_time = time.time()
  199. self._cleanup_instance(f"{action} account rate limited")
  200. elif action == "query":
  201. # 查询时 429:出口 IP 限流,绝不锁账号,换 IP 即可!
  202. self._log("🔄 [Proxy Rate Limited] Query hit 429 (IP throttled, Account preserved). Cleaning instance to rotate proxy...")
  203. self._cleanup_instance("query ip rate limited")
  204. self.m_next_query_time = time.time() + 10.0
  205. else:
  206. self._log(f"⚠️ [Rate Limited] 429 encountered during {action}.")
  207. self.m_next_query_time = time.time() + 10.0
  208. # 2. 会话过期 / 401
  209. elif isinstance(biz_err, SessionExpiredOrInvalidError):
  210. if action in ("create_session", "login", "spawn"):
  211. self._log(f"❌ [Auth Failed] Session creation failed (401 invalid credentials or challenge). Backing off for 10s...")
  212. self.m_last_login_time = time.time() - self.m_cfg.login_interval + 10.0
  213. self._cleanup_instance(f"{action} auth failed")
  214. else:
  215. self._log(f"🔄 [Session Expired] Session died during {action}. Cleaning up instance for re-login in 5s...")
  216. self._cleanup_instance(f"{action} session expired")
  217. self.m_next_query_time = time.time() + 5.0
  218. # 3. 权限被拒 / WAF 拦截 / 403
  219. elif isinstance(biz_err, PermissionDeniedError):
  220. self._log(f"🛡️ [WAF Blocked] 403 Forbidden detected during {action}. Cleaning instance to rotate proxy (60s cooldown)...")
  221. self._cleanup_instance(f"{action} waf blocked")
  222. self.m_next_query_time = time.time() + 60.0
  223. # 4. 网络或浏览器超时
  224. elif isinstance(biz_err, NetworkTimeoutError):
  225. self._log(f"⏱️ [Timeout] Network/browser timeout during {action}. Retrying in 5s...")
  226. self.m_next_query_time = time.time() + 5.0
  227. # 5. 兜底策略
  228. else:
  229. self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
  230. if action in ("create_session", "worker_loop"):
  231. self.m_last_login_time = time.time() - self.m_cfg.login_interval + 5.0
  232. else:
  233. self.m_next_query_time = time.time() + 10.0
  234. def _worker_loop(self):
  235. """
  236. 后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定
  237. """
  238. self._log("Standalone worker loop started.")
  239. while not self.m_stop_event.is_set():
  240. try:
  241. if not self.m_cfg.enable:
  242. self.m_stop_event.wait(1.0)
  243. continue
  244. if not self._is_within_active_hours():
  245. self.m_stop_event.wait(5.0)
  246. continue
  247. # 1. 会话初始化与自愈
  248. if self.m_instance is None:
  249. try:
  250. self._init_instance()
  251. except Exception as e:
  252. self._dispatch_error_policy("create_session", e)
  253. continue
  254. # 2. 健康检查
  255. if self.m_instance and not self.m_instance.health_check():
  256. self._log("Health check failed. Session dead. Recreating session...")
  257. self._cleanup_instance("session health check failed")
  258. continue
  259. # 3. 查询等待与周期性保活
  260. now = time.time()
  261. if now < self.m_next_query_time:
  262. remaining = self.m_next_query_time - now
  263. next_query_str = datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')
  264. keep_alive_sec = self.m_cfg.keep_alive
  265. # 周期性保活
  266. if self.m_instance and now >= self.m_next_keepalive_time:
  267. self.m_instance.keep_alive()
  268. self.m_next_keepalive_time = now + keep_alive_sec
  269. self._log(f"Session keepalive sent. Next query at {next_query_str} (remaining: {remaining:.0f}s)...")
  270. self.m_last_wait_log_time = now
  271. # 周期性显示等待倒计时(每隔 15 秒提示一次)
  272. elif now - self.m_last_wait_log_time >= 15.0 and remaining > 3.0:
  273. self.m_last_wait_log_time = now
  274. self._log(f"Waiting for next query at {next_query_str} (remaining: {remaining:.0f}s)...")
  275. wait_sec = min(remaining, 1.0)
  276. self.m_stop_event.wait(wait_sec)
  277. continue
  278. # 4. 随机选取 routing_key 进行查询
  279. apt_types = self.m_cfg.appointment_types
  280. if not apt_types:
  281. self.m_stop_event.wait(2.0)
  282. continue
  283. weights = [max(0.0, float(t.weight)) for t in apt_types]
  284. if sum(weights) > 0:
  285. apt_type = random.choices(apt_types, weights=weights, k=1)[0]
  286. else:
  287. apt_type = random.choice(apt_types)
  288. self._log(f"Querying slots for {apt_type.routing_key}...")
  289. try:
  290. query_result = self.m_instance.query(apt_type)
  291. query_result.apt_type = apt_type
  292. notify_date_changes(query_result, cache=self.m_current_dates, logger=self._log)
  293. except Exception as e:
  294. self._dispatch_error_policy("query", e)
  295. continue
  296. # 5. 发现档期,执行自动预定
  297. if query_result.success:
  298. self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
  299. try:
  300. book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
  301. notify_book_result(book_result, logger=self._log)
  302. if book_result.success:
  303. self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
  304. self.m_stop_event.wait(5.0)
  305. except Exception as e:
  306. self._dispatch_error_policy("book", e)
  307. # 6. 在所有操作(包括抢单流程)执行完毕后,再统一计算并调度下一次查询时间与保活时间
  308. interval = self._get_wait_interval()
  309. now = time.time()
  310. self.m_next_query_time = now + interval
  311. keep_alive_sec = self.m_cfg.keep_alive
  312. self.m_next_keepalive_time = now + keep_alive_sec
  313. self.m_last_wait_log_time = now
  314. self._log(f"Next query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')})...")
  315. except Exception as e:
  316. self._dispatch_error_policy("worker_loop", e)