standalone.py 20 KB

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