sentinel.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. def _log(self, message):
  26. if self.m_logger:
  27. self.m_logger(f'[SENTINEL] [{self.m_cfg.identifier}] {message}')
  28. def start(self):
  29. if not self.m_cfg.enable:
  30. return
  31. self._log("Starting Sentinel...")
  32. plugin_name = self.m_cfg.plugin_config.plugin_name
  33. class_name = "".join(part.title() for part in plugin_name.split('_'))
  34. plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
  35. self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
  36. threading.Thread(target=self._monitor_loop, daemon=True, name="Sentinel-Monitor").start()
  37. threading.Thread(target=self._creator_loop, daemon=True, name="Sentinel-Creator").start()
  38. def stop(self):
  39. self._log("Stopping Sentinel...")
  40. self.m_stop_event.set()
  41. def _get_redis_key(self, routing_key: str) -> str:
  42. return f"vs:signal:{routing_key}"
  43. def _monitor_loop(self):
  44. self._log("Monitor loop started.")
  45. rng = random.Random()
  46. while not self.m_stop_event.is_set():
  47. try:
  48. time.sleep(0.5)
  49. now = time.time()
  50. with self.m_lock:
  51. active_tasks = [t for t in self.m_tasks if t.instance.health_check()]
  52. self.m_tasks = active_tasks
  53. for task in active_tasks:
  54. if now < task.next_run:
  55. continue
  56. apt_types = self.m_cfg.appointment_types
  57. if not apt_types:
  58. continue
  59. weights = [float(item.weight) for item in apt_types]
  60. apt_type = random.choices(apt_types, weights=weights, k=1)[0]
  61. interval = 30
  62. mode = task.qw_cfg.mode
  63. if mode == QueryWaitMode.Loop:
  64. interval = 1
  65. elif mode == QueryWaitMode.Fixed:
  66. interval = task.qw_cfg.fixed_wait
  67. elif mode == QueryWaitMode.Random:
  68. interval = rng.randint(task.qw_cfg.random_min, task.qw_cfg.random_max)
  69. task.next_run = time.time() + interval
  70. try:
  71. VSCloudApi.Instance().slot_refresh_start(apt_type.routing_key, country=apt_type.country, city=apt_type.city, visa_type=apt_type.visa_type)
  72. result = task.instance.query(apt_type)
  73. result.apt_type = apt_type
  74. VSCloudApi.Instance().slot_refresh_success(apt_type.routing_key)
  75. if result.success:
  76. ttl = self.m_cfg.sentinel.signal_ttl
  77. self._log(f"🔥 SLOT FOUND! Writing signal to Redis (TTL: {ttl}s)")
  78. payload = {
  79. "group_id": self.m_cfg.identifier,
  80. "apt_type": apt_type.model_dump(),
  81. "query_result": result.to_snapshot_payload(),
  82. "timestamp": now
  83. }
  84. redis_key = self._get_redis_key(apt_type.routing_key)
  85. self.redis_client.setex(redis_key, ttl, json.dumps(payload))
  86. payload["query_result"]["website"] = self.m_cfg.website
  87. VSCloudApi.Instance().slot_snapshot_report(payload["query_result"])
  88. except Exception as e:
  89. self._log(f"Query exception: {e}")
  90. VSCloudApi.Instance().slot_refresh_fail(apt_type.routing_key, error=str(e))
  91. except Exception as e:
  92. self._log(f"Monitor loop error: {e}")
  93. time.sleep(2)
  94. def _creator_loop(self):
  95. self._log("Creator loop started.")
  96. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  97. while not self.m_stop_event.is_set():
  98. time.sleep(2)
  99. with self.m_lock:
  100. if self.redis_client.exists(group_cd_key):
  101. continue
  102. current = len(self.m_tasks)
  103. pending = self.m_pending_builtin
  104. if (current + pending) < self.m_cfg.sentinel.target_instances:
  105. self._spawn_sentinel_worker()
  106. def _spawn_sentinel_worker(self):
  107. with self.m_lock:
  108. self.m_pending_builtin += 1
  109. def _job():
  110. try:
  111. plg_cfg = VSPlgConfig()
  112. plg_cfg.debug = self.m_cfg.debug
  113. plg_cfg.free_config = self.m_cfg.free_config
  114. plg_cfg.session_max_life = self.m_cfg.session_max_life
  115. if not self.m_cfg.need_account:
  116. plg_cfg.account.id = 0
  117. plg_cfg.account.username = "Guest"
  118. else:
  119. acc = VSCloudApi.Instance().get_next_account(self.m_cfg.sentinel.account_pool_id, self.m_cfg.sentinel.account_cd)
  120. plg_cfg.account.id = acc['id']
  121. plg_cfg.account.username = acc['username']
  122. plg_cfg.account.password = acc['password']
  123. if self.m_cfg.need_proxy:
  124. proxy = VSCloudApi.Instance().get_next_proxy(self.m_cfg.proxy_pool, self.m_cfg.proxy_cd)
  125. plg_cfg.proxy.id = proxy['id']
  126. plg_cfg.proxy.ip = proxy['ip']
  127. plg_cfg.proxy.port = proxy['port']
  128. plg_cfg.proxy.scheme = proxy['scheme']
  129. plg_cfg.proxy.username = proxy['username']
  130. plg_cfg.proxy.password = proxy['password']
  131. instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
  132. instance.set_log(self.m_logger)
  133. instance.set_config(plg_cfg)
  134. instance.create_session()
  135. with self.m_lock:
  136. self.m_tasks.append(
  137. Task(instance=instance,qw_cfg=self.m_cfg.query_wait,next_run=time.time(), book_allowed=False))
  138. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  139. self.redis_client.delete(group_fail_key)
  140. self._log(f"+++ Sentinel spawned: {plg_cfg.account.username}")
  141. except Exception as e:
  142. err_str = str(e)
  143. resource_not_found_indicators = [
  144. "40401" in err_str,
  145. "Account not found" in err_str,
  146. "Proxy not found" in err_str,
  147. ]
  148. if any(resource_not_found_indicators):
  149. return
  150. self._log(f"Spawn failed: {e}")
  151. rate_limited_indicators = [
  152. "42901" in err_str,
  153. "Rate limited" in err_str
  154. ]
  155. if any(rate_limited_indicators):
  156. group_fail_key = f"vs:group:failures:{self.m_cfg.identifier}"
  157. group_cd_key = f"vs:group:cooldown:{self.m_cfg.identifier}"
  158. g_fails = self.redis_client.incr(group_fail_key)
  159. g_cd = self.group_backoff.calculate(g_fails)
  160. self.redis_client.set(group_cd_key, "1", ex=int(g_cd))
  161. self._log(f"📉 [Rate Limited] Sentinel Spawn failed {g_fails} times. Global Backoff: {g_cd:.1f}s.")
  162. finally:
  163. with self.m_lock:
  164. self.m_pending_builtin = max(0, self.m_pending_builtin - 1)
  165. ThreadPool.getInstance().enqueue(_job)