sentinel.py 14 KB

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