standalone.py 21 KB

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