sentinel.py 10 KB

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