sentinel.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. import os
  2. import time
  3. import json
  4. import random
  5. import threading
  6. from typing import List, Dict, Callable
  7. from vs_types import GroupConfig, VSPlgConfig, Task, QueryWaitMode
  8. from vs_plg_factory import VSPlgFactory
  9. from toolkit.thread_pool import ThreadPool
  10. from toolkit.vs_cloud_api import VSCloudApi
  11. from toolkit.backoff import ExponentialBackoff
  12. from utils.safe_redis_cli import SafeRedisClient
  13. class SentinelGCO:
  14. def __init__(self, cfg: GroupConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
  15. self.m_cfg = cfg
  16. self.m_factory = VSPlgFactory()
  17. self.m_logger = logger
  18. self.m_tasks: List[Task] = []
  19. self.m_lock = threading.RLock()
  20. self.m_stop_event = threading.Event()
  21. self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
  22. self.m_pending_builtin = 0
  23. self.group_backoff = ExponentialBackoff(base_delay=60.0, max_delay=3600.0, factor=2.0)
  24. self.m_last_spawn_time = 0.0
  25. self.m_spawn_interval = 120
  26. self.m_last_group_query_time = 0.0
  27. def _log(self, message):
  28. if self.m_logger:
  29. self.m_logger(f'[SENTINEL] [{self.m_cfg.identifier}] {message}')
  30. else:
  31. print(f'[SENTINEL] [{self.m_cfg.identifier}] {message}')
  32. def _get_average_interval(self) -> float:
  33. """计算当前组平均的查询间隔(秒)"""
  34. mode = self.m_cfg.query_wait.mode
  35. if mode == QueryWaitMode.Loop:
  36. return 1.0
  37. elif mode == QueryWaitMode.Fixed:
  38. return float(self.m_cfg.query_wait.fixed_wait)
  39. elif mode == QueryWaitMode.Random:
  40. return (self.m_cfg.query_wait.random_min + self.m_cfg.query_wait.random_max) / 2.0
  41. return 30.0
  42. def update_config(self, new_cfg: GroupConfig):
  43. """
  44. 动态更新配置
  45. """
  46. with self.m_lock:
  47. if self.m_cfg.enable and not new_cfg.enable:
  48. self._log("Config dynamically updated: Group DISABLED. Will stop creating new tasks.")
  49. elif not self.m_cfg.enable and new_cfg.enable:
  50. self._log("Config dynamically updated: Group ENABLED.")
  51. else:
  52. self._log("Config dynamically updated: Parameters refreshed.")
  53. self.m_cfg = new_cfg
  54. def start(self):
  55. if not self.m_cfg.enable:
  56. return
  57. self._log("Starting Sentinel...")
  58. plugin_name = self.m_cfg.plugin_config.plugin_name
  59. class_name = "".join(part.title() for part in plugin_name.split('_'))
  60. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  61. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  62. threading.Thread(target=self._monitor_loop, daemon=True, name="Sentinel-Monitor").start()
  63. threading.Thread(target=self._creator_loop, daemon=True, name="Sentinel-Creator").start()
  64. def stop(self):
  65. self._log("Stopping Sentinel...")
  66. self.m_stop_event.set()
  67. with self.m_lock:
  68. tasks_to_cleanup = list(self.m_tasks)
  69. self.m_tasks.clear()
  70. for task in tasks_to_cleanup:
  71. self._cleanup_task(task, "sentinel stopped")
  72. def _cleanup_task(self, task: Task, reason: str):
  73. try:
  74. if task and task.instance:
  75. self._log(f"Cleaning up sentinel instance. reason={reason}")
  76. task.instance.cleanup()
  77. except Exception as e:
  78. self._log(f"Cleanup failed. reason={reason}, error={e}")
  79. def _remove_task(self, task: Task, reason: str):
  80. removed = False
  81. with self.m_lock:
  82. if task in self.m_tasks:
  83. self.m_tasks.remove(task)
  84. removed = True
  85. if removed:
  86. self._cleanup_task(task, reason)
  87. def _get_redis_key(self, routing_key: str) -> str:
  88. return f"vs:signal:{routing_key}"
  89. def _monitor_loop(self):
  90. self._log("Monitor loop started.")
  91. self.m_last_group_query_time = 0.0
  92. while not self.m_stop_event.is_set():
  93. try:
  94. time.sleep(1)
  95. now = time.time()
  96. with self.m_lock:
  97. tasks_to_check = list(self.m_tasks)
  98. active_tasks = []
  99. dead_tasks = []
  100. for t in tasks_to_check:
  101. if t.is_querying:
  102. active_tasks.append(t)
  103. continue
  104. if t.instance.health_check():
  105. active_tasks.append(t)
  106. else:
  107. dead_tasks.append(t)
  108. if dead_tasks:
  109. with self.m_lock:
  110. current_tasks = list(self.m_tasks)
  111. self.m_tasks = [t for t in self.m_tasks if t in active_tasks]
  112. for t in dead_tasks:
  113. if t in current_tasks:
  114. self._cleanup_task(t, "health check failed")
  115. else:
  116. with self.m_lock:
  117. self.m_tasks = [t for t in self.m_tasks if t in active_tasks]
  118. if not active_tasks:
  119. continue
  120. avg_interval = self._get_average_interval()
  121. global_gap = max(1.0, avg_interval / len(active_tasks))
  122. active_tasks.sort(key=lambda x: x.next_run)
  123. for task in active_tasks:
  124. if now < task.next_run:
  125. continue
  126. if task.is_querying:
  127. continue
  128. if now - self.m_last_group_query_time < global_gap:
  129. break
  130. apt_types = self.m_cfg.appointment_types
  131. if not apt_types:
  132. continue
  133. weights = [float(item.weight) for item in apt_types]
  134. apt_type = random.choices(apt_types, weights=weights, k=1)[0]
  135. interval = 30
  136. mode = task.qw_cfg.mode
  137. if mode == QueryWaitMode.Loop:
  138. interval = 1
  139. elif mode == QueryWaitMode.Fixed:
  140. interval = task.qw_cfg.fixed_wait
  141. elif mode == QueryWaitMode.Random:
  142. interval = random.randint(task.qw_cfg.random_min, task.qw_cfg.random_max)
  143. task.is_querying = True
  144. self.m_last_group_query_time = now
  145. def _query_job(current_task=task, a_type=apt_type, wait_gap=interval):
  146. try:
  147. VSCloudApi.Instance().slot_refresh_start(a_type.routing_key, country=a_type.country, city=a_type.city, visa_type=a_type.visa_type)
  148. result = current_task.instance.query(a_type)
  149. result.apt_type = a_type
  150. if result.success:
  151. ttl = self.m_cfg.sentinel.signal_ttl
  152. self._log(f"🔥 SLOT FOUND! Writing signal to Redis (TTL: {ttl}s)")
  153. payload = {
  154. "group_id": self.m_cfg.identifier,
  155. "apt_type": a_type.model_dump(),
  156. "query_result": result.to_snapshot_payload(),
  157. "timestamp": time.time()
  158. }
  159. redis_key = self._get_redis_key(a_type.routing_key)
  160. self.redis_client.setex(redis_key, ttl, json.dumps(payload))
  161. payload["query_result"]["website"] = self.m_cfg.website
  162. VSCloudApi.Instance().slot_snapshot_report(payload["query_result"])
  163. VSCloudApi.Instance().slot_refresh_success(a_type.routing_key)
  164. except Exception as e:
  165. self._log(f"Query exception: {e}")
  166. VSCloudApi.Instance().slot_refresh_fail(a_type.routing_key, error=str(e))
  167. finally:
  168. current_task.next_run = time.time() + wait_gap
  169. current_task.is_querying = False
  170. ThreadPool.getInstance().enqueue(_query_job)
  171. break
  172. except Exception as e:
  173. self._log(f"Monitor loop error: {e}")
  174. def _creator_loop(self):
  175. self._log("Creator loop started.")
  176. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  177. while not self.m_stop_event.is_set():
  178. try:
  179. time.sleep(1)
  180. if self.redis_client.exists(group_cd_key):
  181. continue
  182. with self.m_lock:
  183. current = len(self.m_tasks)
  184. pending = self.m_pending_builtin
  185. target = self.m_cfg.sentinel.target_instances
  186. if (current + pending) < target:
  187. now = time.time()
  188. if now - self.m_last_spawn_time >= self.m_spawn_interval:
  189. with self.m_lock:
  190. self.m_last_spawn_time = now
  191. self._log(f"Staggered spawn triggered. Next spawn in {self.m_spawn_interval:.1f}s")
  192. self._spawn_sentinel_worker()
  193. except Exception as e:
  194. self._log(f'Creator loop exception:{e}')
  195. def _spawn_sentinel_worker(self):
  196. with self.m_lock:
  197. self.m_pending_builtin += 1
  198. def _job():
  199. instance = None
  200. success = False
  201. try:
  202. plg_cfg = VSPlgConfig()
  203. plg_cfg.debug = self.m_cfg.debug
  204. plg_cfg.free_config = self.m_cfg.free_config
  205. plg_cfg.session_max_life = self.m_cfg.session_max_life
  206. if not self.m_cfg.need_account:
  207. plg_cfg.account.id = 0
  208. plg_cfg.account.username = "Guest"
  209. else:
  210. acc = VSCloudApi.Instance().get_next_account(self.m_cfg.sentinel.account_pool_id, self.m_cfg.sentinel.account_cd)
  211. plg_cfg.account = type(plg_cfg.account)(**acc)
  212. if self.m_cfg.need_proxy:
  213. proxy = VSCloudApi.Instance().get_next_proxy(self.m_cfg.proxy_pool, self.m_cfg.proxy_cd)
  214. plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
  215. instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
  216. instance.set_log(self.m_logger)
  217. instance.set_config(plg_cfg)
  218. instance.create_session()
  219. with self.m_lock:
  220. self.m_tasks.append(
  221. Task(instance=instance,qw_cfg=self.m_cfg.query_wait,next_run=time.time(), book_allowed=False))
  222. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  223. self.redis_client.delete(group_fail_key)
  224. success = True
  225. self._log(f"+++ Sentinel spawned: {plg_cfg.account.username}")
  226. except Exception as e:
  227. err_str = str(e)
  228. resource_not_found_indicators = [
  229. "40401" in err_str,
  230. "Account not found" in err_str,
  231. "Proxy not found" in err_str,
  232. ]
  233. if any(resource_not_found_indicators):
  234. return
  235. self._log(f"Spawn failed: {e}")
  236. rate_limited_indicators = [
  237. "42901" in err_str,
  238. "Rate limited" in err_str
  239. ]
  240. if any(rate_limited_indicators):
  241. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  242. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  243. g_fails = self.redis_client.incr(group_fail_key)
  244. g_cd = self.group_backoff.calculate(g_fails)
  245. self.redis_client.set(group_cd_key, "1", ex=int(g_cd))
  246. self._log(f"📉 [Rate Limited] Sentinel Spawn failed {g_fails} times. Global Backoff: {g_cd:.1f}s.")
  247. finally:
  248. if not success and instance is not None:
  249. instance.cleanup()
  250. with self.m_lock:
  251. self.m_pending_builtin = max(0, self.m_pending_builtin - 1)
  252. ThreadPool.getInstance().enqueue(_job)