standalone.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import os
  2. import time
  3. import random
  4. import threading
  5. from datetime import datetime, timedelta, timezone
  6. from typing import Dict, Callable, Optional
  7. from core_types import (
  8. BookerStandaloneConfig,
  9. QueryWaitMode,
  10. PluginConfig,
  11. Account,
  12. QueryResult,
  13. BookResult,
  14. GroupStatus,
  15. PluginStatus,
  16. utc_now_str,
  17. BizException,
  18. RateLimiteddError,
  19. SessionExpiredOrInvalidError,
  20. PermissionDeniedError,
  21. NetworkTimeoutError,
  22. AccountStateError,
  23. AccountAuthError,
  24. AccountBannedError,
  25. AccountIncompleteError,
  26. AccountNotFoundError,
  27. normalize_error
  28. )
  29. from plugin_factory import PluginFactory
  30. from toolkit.cloud_api import CloudApi
  31. from utils.safe_redis_cli import SafeRedisClient
  32. from toolkit.proxy_manager import ProxyManager
  33. from toolkit.notifier import notify_date_changes, notify_book_result
  34. class StandaloneGCO:
  35. """
  36. Standalone GCO Instance Manager.
  37. Adheres to the unified lifecycle contract of SentinelGCO / BookerGCO (start / stop / update_config).
  38. """
  39. TAG = "STANDALONE"
  40. def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
  41. self.m_cfg = cfg
  42. self.m_logger = logger
  43. self.m_factory = PluginFactory()
  44. self.m_instance = None
  45. self.m_lock = threading.RLock()
  46. self.m_stop_event = threading.Event()
  47. self.m_last_login_time = 0
  48. self.m_next_query_time = 0
  49. self.m_next_keepalive_time = 0
  50. self.m_last_wait_log_time = 0.0
  51. self.m_current_dates = {}
  52. self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
  53. def _log(self, message: str):
  54. prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
  55. if self.m_logger:
  56. self.m_logger(f"{prefix} {message}")
  57. else:
  58. print(f"{prefix} {message}")
  59. def _get_wait_interval(self) -> float:
  60. """Calculate wait interval for next query based on configuration."""
  61. mode = self.m_cfg.query_wait.mode
  62. if mode == QueryWaitMode.Loop:
  63. return 1.0
  64. elif mode == QueryWaitMode.Fixed:
  65. return float(self.m_cfg.query_wait.fixed_wait)
  66. elif mode == QueryWaitMode.Random:
  67. return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
  68. return 30.0
  69. def _is_within_active_hours(self) -> bool:
  70. """Determine if current time is within active operating window for instances and queries."""
  71. start_str = self.m_cfg.active_time_start
  72. end_str = self.m_cfg.active_time_end
  73. current_bj_time = datetime.utcnow().time()
  74. start_time = datetime.strptime(start_str, "%H:%M").time()
  75. end_time = datetime.strptime(end_str, "%H:%M").time()
  76. return start_time <= current_bj_time <= end_time
  77. def update_config(self, new_cfg: BookerStandaloneConfig):
  78. """Dynamically update group configuration."""
  79. with self.m_lock:
  80. if self.m_cfg.enable and not new_cfg.enable:
  81. self._log("Config dynamically updated: Group DISABLED.")
  82. elif not self.m_cfg.enable and new_cfg.enable:
  83. self._log("Config dynamically updated: Group ENABLED.")
  84. else:
  85. self._log("Config dynamically updated: Parameters refreshed.")
  86. self.m_cfg = new_cfg
  87. def get_status(self) -> GroupStatus:
  88. with self.m_lock:
  89. instance = self.m_instance
  90. gid = self.m_cfg.identifier
  91. enable = self.m_cfg.enable
  92. plugin_name = self.m_cfg.plugin_config.plugin_name
  93. plugins_status = []
  94. healthy_count = 0
  95. if instance:
  96. st = instance.get_plugin_status()
  97. if st.is_healthy:
  98. healthy_count += 1
  99. plugins_status.append(st)
  100. return GroupStatus(
  101. group_id=gid,
  102. enable=enable,
  103. plugin_name=plugin_name,
  104. total_tasks=1 if instance else 0,
  105. healthy_tasks=healthy_count,
  106. plugins=plugins_status,
  107. updated_at=utc_now_str(),
  108. )
  109. def start(self):
  110. """Non-blocking start: registers plugin and starts background worker thread."""
  111. if not self.m_cfg.enable:
  112. return
  113. self._log("Starting Standalone GCO...")
  114. plugin_name = self.m_cfg.plugin_config.plugin_name
  115. class_name = "".join(part.title() for part in plugin_name.split('_'))
  116. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  117. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  118. worker_name = f"Standalone-{self.m_cfg.identifier}"
  119. threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
  120. def stop(self):
  121. """Gracefully stop background worker and clean up resources."""
  122. self._log("Stopping Standalone GCO...")
  123. self.m_stop_event.set()
  124. self._cleanup_instance("standalone stopped")
  125. def _cleanup_instance(self, reason: str = ""):
  126. with self.m_lock:
  127. if self.m_instance is not None:
  128. try:
  129. self._log(f"🧹 Cleaned up instance. Reason: {reason}")
  130. self.m_instance.cleanup()
  131. except Exception as e:
  132. self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
  133. finally:
  134. self.m_instance = None
  135. def _init_instance(self):
  136. """Initialize single instance and log in to create a session."""
  137. self._cleanup_instance("recreating new session")
  138. now = time.time()
  139. if now < self.m_last_login_time + self.m_cfg.login_interval:
  140. wait_time = self.m_last_login_time + self.m_cfg.login_interval - now
  141. self._log(f"Waiting {int(wait_time)}s for login interval cooldown...")
  142. if self.m_stop_event.wait(wait_time):
  143. return
  144. plugin_name = self.m_cfg.plugin_config.plugin_name
  145. plg_cfg = PluginConfig()
  146. plg_cfg.debug = self.m_cfg.debug
  147. plg_cfg.account = self.m_cfg.account
  148. proxy = ProxyManager.Instance().get_next_proxy(self.m_cfg.proxy_pool, proxy_cd=600)
  149. plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
  150. plg_cfg.free_config = self.m_cfg.free_config
  151. plg_cfg.session_max_life = self.m_cfg.session_max_life
  152. instance = self.m_factory.create(self.m_cfg.identifier, plugin_name)
  153. instance.set_log(self.m_logger)
  154. instance.set_config(plg_cfg)
  155. with self.m_lock:
  156. self.m_instance = instance
  157. self._log("Creating session...")
  158. instance.create_session()
  159. self.m_last_login_time = time.time()
  160. interval = self._get_wait_interval()
  161. self.m_next_query_time = time.time() + interval
  162. self.m_next_keepalive_time = time.time() + 10.0
  163. 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')}).")
  164. def _disable_account_safely(self, acc: Optional[Account], reason: str = "") -> None:
  165. """Safely disables account in cloud: sets status='disable', locks for 10 years, and records extra_data."""
  166. if not acc or acc.id <= 0 or acc.username in ("", "Guest"):
  167. return
  168. try:
  169. cloud = CloudApi.Instance()
  170. url = f"{cloud.base_url}/api/account/update"
  171. params = {"account_id": acc.id}
  172. far_future = (datetime.now(timezone.utc) + timedelta(days=3650)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
  173. payload = {
  174. "status": "disable",
  175. "next_use_time": far_future,
  176. "extra_data": {
  177. "disable_reason": reason,
  178. "disabled_at": int(time.time()),
  179. "module": "STANDALONE",
  180. "group": getattr(self.m_cfg, "identifier", "")
  181. }
  182. }
  183. cloud._perform_request('PUT', url, params=params, json_data=payload, headers=cloud._get_headers(), timeout=10)
  184. self._log(f"🚫 [Account Disabled] Account [{acc.username}] (ID={acc.id}) permanently marked as 'disable' in Cloud API. Reason: {reason}")
  185. except Exception as e:
  186. self._log(f"Failed to set account status to disable via cloud API: {e}. Falling back to 10-year lock...")
  187. try:
  188. CloudApi.Instance().lock_account(acc.id, 86400 * 3650)
  189. except Exception as lock_err:
  190. self._log(f"Fallback 10-year lock also failed: {lock_err}")
  191. def _dispatch_error_policy(self, action: str, err: Exception) -> None:
  192. """
  193. Standalone Error Recovery & Dispatch Policy Engine:
  194. Executes self-healing actions based on (Action, Exception Domain Type) matrix:
  195. - AccountStateError (invalid credentials, banned, incomplete): Permanently disables account, backs off.
  196. - 429 on create_session/login: Account-level rate limit. Lock account and back off.
  197. - 429 on query: Session alive, egress IP throttled. Do not lock account; rotate proxy.
  198. - session expired / 401: Destroy instance and reschedule re-login in 5s.
  199. - 403 Forbidden / WAF: IP blocked. Rotate proxy and back off.
  200. - Directly maintains logs and timers internally.
  201. """
  202. biz_err = normalize_error(err)
  203. acc = self.m_cfg.account if (self.m_cfg.account and self.m_cfg.account.username not in ("", "Guest")) else None
  204. # 0. Fatal Account State Error (credentials invalid, banned, incomplete, not found)
  205. if isinstance(biz_err, AccountStateError):
  206. self._log(f"🚨 [Account Fatal Error] {biz_err.__class__.__name__} during {action}: {biz_err.message} (code={biz_err.code})")
  207. if acc and acc.id > 0 and acc.username not in ("", "Guest"):
  208. self._disable_account_safely(acc, reason=f"{biz_err.__class__.__name__}: {biz_err.message}")
  209. self._cleanup_instance(f"{action} account fatal error: {biz_err.message}")
  210. self.m_last_login_time = time.time()
  211. self.m_next_query_time = time.time() + 3600.0
  212. # 1. Target site rate limit / 429
  213. elif isinstance(biz_err, RateLimiteddError):
  214. if action in ("create_session", "login", "spawn"):
  215. backoff = float(self.m_cfg.login_interval)
  216. self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
  217. if acc and acc.id > 0:
  218. try:
  219. CloudApi.Instance().lock_account(acc.id, int(backoff))
  220. self._log(f"🔒 Account [{acc.username}] locked for {int(backoff)}s via Cloud API.")
  221. except Exception as lock_err:
  222. self._log(f"Failed to lock account via cloud API: {lock_err}")
  223. self.m_last_login_time = time.time()
  224. self._cleanup_instance(f"{action} account rate limited")
  225. elif action == "query":
  226. # 429 during query: Egress IP rate-limited, do not lock account, rotate proxy
  227. self._log("🔄 [Proxy Rate Limited] Query hit 429 (IP throttled, Account preserved). Cleaning instance to rotate proxy...")
  228. self._cleanup_instance("query ip rate limited")
  229. self.m_next_query_time = time.time() + 10.0
  230. else:
  231. self._log(f"⚠️ [Rate Limited] 429 encountered during {action}.")
  232. self.m_next_query_time = time.time() + 10.0
  233. # 2. Session expired / 401
  234. elif isinstance(biz_err, SessionExpiredOrInvalidError):
  235. if action in ("create_session", "login", "spawn"):
  236. self._log(f"❌ [Auth Failed] Session creation failed (401 invalid credentials or challenge). Backing off for 10s...")
  237. self.m_last_login_time = time.time() - self.m_cfg.login_interval + 10.0
  238. self._cleanup_instance(f"{action} auth failed")
  239. else:
  240. self._log(f"🔄 [Session Expired] Session died during {action}. Cleaning up instance for re-login in 5s...")
  241. self._cleanup_instance(f"{action} session expired")
  242. self.m_next_query_time = time.time() + 5.0
  243. # 3. Permission denied / WAF blocked / 403
  244. elif isinstance(biz_err, PermissionDeniedError):
  245. self._log(f"🛡️ [WAF Blocked] 403 Forbidden detected during {action}. Cleaning instance to rotate proxy (60s cooldown)...")
  246. self._cleanup_instance(f"{action} waf blocked")
  247. self.m_next_query_time = time.time() + 60.0
  248. # 4. Network or browser timeout
  249. elif isinstance(biz_err, NetworkTimeoutError):
  250. self._log(f"⏱️ [Timeout] Network/browser timeout during {action}. Retrying in 5s...")
  251. self.m_next_query_time = time.time() + 5.0
  252. # 5. Fallback policy
  253. else:
  254. self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
  255. if action in ("create_session", "worker_loop"):
  256. self.m_last_login_time = time.time() - self.m_cfg.login_interval + 5.0
  257. else:
  258. self.m_next_query_time = time.time() + 10.0
  259. def _worker_loop(self):
  260. """
  261. Background worker daemon loop: keepalive -> schedule check -> query -> booking
  262. """
  263. self._log("Standalone worker loop started.")
  264. while not self.m_stop_event.is_set():
  265. try:
  266. if not self.m_cfg.enable:
  267. self.m_stop_event.wait(1.0)
  268. continue
  269. if not self._is_within_active_hours():
  270. self.m_stop_event.wait(5.0)
  271. continue
  272. # 1. Session initialization and self-healing
  273. if self.m_instance is None:
  274. try:
  275. self._init_instance()
  276. except Exception as e:
  277. self._dispatch_error_policy("create_session", e)
  278. continue
  279. # 2. Health check
  280. if self.m_instance and not self.m_instance.health_check():
  281. self._log("Health check failed. Session dead. Recreating session...")
  282. self._cleanup_instance("session health check failed")
  283. continue
  284. # 3. Query interval wait and periodic keepalive
  285. now = time.time()
  286. if now < self.m_next_query_time:
  287. remaining = self.m_next_query_time - now
  288. next_query_str = datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')
  289. keep_alive_sec = self.m_cfg.keep_alive
  290. # Periodic keepalive
  291. if self.m_instance and now >= self.m_next_keepalive_time:
  292. self.m_instance.keep_alive()
  293. self.m_next_keepalive_time = now + keep_alive_sec
  294. self._log(f"Session keepalive sent. Next query at {next_query_str} (remaining: {remaining:.0f}s)...")
  295. self.m_last_wait_log_time = now
  296. # Periodic wait countdown (logged every 15s)
  297. elif now - self.m_last_wait_log_time >= 15.0 and remaining > 3.0:
  298. self.m_last_wait_log_time = now
  299. self._log(f"Waiting for next query at {next_query_str} (remaining: {remaining:.0f}s)...")
  300. wait_sec = min(remaining, 1.0)
  301. self.m_stop_event.wait(wait_sec)
  302. continue
  303. # 4. Randomly pick a routing_key for query
  304. apt_types = self.m_cfg.appointment_types
  305. if not apt_types:
  306. self.m_stop_event.wait(2.0)
  307. continue
  308. weights = [max(0.0, float(t.weight)) for t in apt_types]
  309. if sum(weights) > 0:
  310. apt_type = random.choices(apt_types, weights=weights, k=1)[0]
  311. else:
  312. apt_type = random.choice(apt_types)
  313. self._log(f"Querying slots for {apt_type.routing_key}...")
  314. try:
  315. query_result = self.m_instance.query(apt_type)
  316. query_result.apt_type = apt_type
  317. notify_date_changes(query_result, cache=self.m_current_dates, logger=self._log)
  318. except Exception as e:
  319. self._dispatch_error_policy("query", e)
  320. continue
  321. # 5. Slot found: trigger auto-booking
  322. if query_result.success:
  323. self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
  324. try:
  325. book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
  326. notify_book_result(book_result, logger=self._log)
  327. if book_result.success:
  328. self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
  329. self.m_stop_event.wait(5.0)
  330. except Exception as e:
  331. self._dispatch_error_policy("book", e)
  332. # 6. Recompute and schedule next query and keepalive times
  333. interval = self._get_wait_interval()
  334. now = time.time()
  335. self.m_next_query_time = now + interval
  336. keep_alive_sec = self.m_cfg.keep_alive
  337. self.m_next_keepalive_time = now + keep_alive_sec
  338. self.m_last_wait_log_time = now
  339. self._log(f"Next query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')})...")
  340. except Exception as e:
  341. self._dispatch_error_policy("worker_loop", e)