|
@@ -1,61 +1,130 @@
|
|
|
import os
|
|
import os
|
|
|
import time
|
|
import time
|
|
|
import random
|
|
import random
|
|
|
|
|
+import threading
|
|
|
from datetime import datetime
|
|
from datetime import datetime
|
|
|
-from typing import List, Dict, Callable
|
|
|
|
|
|
|
+from typing import Dict, Callable, Optional
|
|
|
|
|
|
|
|
-from vs_types import BookerStandaloneConfig, QueryWaitMode, VSPlgConfig, VSQueryResult, VSBookResult
|
|
|
|
|
|
|
+from vs_types import BookerStandaloneConfig, QueryWaitMode, VSPlgConfig, VSQueryResult, VSBookResult, GroupStatus, PluginStatus, utc_now_str
|
|
|
from vs_plg_factory import VSPlgFactory
|
|
from vs_plg_factory import VSPlgFactory
|
|
|
from utils.safe_redis_cli import SafeRedisClient
|
|
from utils.safe_redis_cli import SafeRedisClient
|
|
|
from toolkit.vs_cloud_api import VSCloudApi
|
|
from toolkit.vs_cloud_api import VSCloudApi
|
|
|
from toolkit.thread_pool import ThreadPool
|
|
from toolkit.thread_pool import ThreadPool
|
|
|
|
|
|
|
|
|
|
|
|
|
-class BookerStandalone:
|
|
|
|
|
- def __init__(self, config: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
|
|
|
|
|
|
|
+class StandaloneGCO:
|
|
|
|
|
+ """
|
|
|
|
|
+ Standalone GCO 实例管理器。
|
|
|
|
|
+ 遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。
|
|
|
|
|
+ """
|
|
|
|
|
+ TAG = "STANDALONE"
|
|
|
|
|
+
|
|
|
|
|
+ def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
|
|
|
|
|
+ self.m_cfg = cfg
|
|
|
self.m_logger = logger
|
|
self.m_logger = logger
|
|
|
self.m_factory = VSPlgFactory()
|
|
self.m_factory = VSPlgFactory()
|
|
|
- self.m_cfg = config
|
|
|
|
|
- self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
|
|
|
|
|
self.m_instance = None
|
|
self.m_instance = None
|
|
|
- self.m_running = False
|
|
|
|
|
- self.m_next_query_time = 0.0
|
|
|
|
|
- self.m_last_login_time = 0.0
|
|
|
|
|
|
|
+ self.m_lock = threading.RLock()
|
|
|
|
|
+ self.m_stop_event = threading.Event()
|
|
|
|
|
+ self.m_last_login_time = 0
|
|
|
|
|
+ self.m_next_query_time = 0
|
|
|
self.m_current_dates = {}
|
|
self.m_current_dates = {}
|
|
|
|
|
+ self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
|
|
|
|
|
|
|
|
- def _log(self, message):
|
|
|
|
|
|
|
+ def _log(self, message: str):
|
|
|
|
|
+ prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
|
|
|
if self.m_logger:
|
|
if self.m_logger:
|
|
|
- self.m_logger(f'[BOOKER] {message}')
|
|
|
|
|
|
|
+ self.m_logger(f"{prefix} {message}")
|
|
|
else:
|
|
else:
|
|
|
- print(f'[BOOKER] {message}')
|
|
|
|
|
|
|
+ print(f"{prefix} {message}")
|
|
|
|
|
|
|
|
def _get_wait_interval(self) -> float:
|
|
def _get_wait_interval(self) -> float:
|
|
|
"""根据配置计算下一次查询的等待时间"""
|
|
"""根据配置计算下一次查询的等待时间"""
|
|
|
- if self.m_cfg.query_wait.mode == QueryWaitMode.Loop:
|
|
|
|
|
|
|
+ mode = self.m_cfg.query_wait.mode
|
|
|
|
|
+ if mode == QueryWaitMode.Loop:
|
|
|
return 1.0
|
|
return 1.0
|
|
|
- elif self.m_cfg.query_wait.mode == QueryWaitMode.Fixed:
|
|
|
|
|
|
|
+ elif mode == QueryWaitMode.Fixed:
|
|
|
return float(self.m_cfg.query_wait.fixed_wait)
|
|
return float(self.m_cfg.query_wait.fixed_wait)
|
|
|
- elif self.m_cfg.query_wait.mode == QueryWaitMode.Random:
|
|
|
|
|
|
|
+ elif mode == QueryWaitMode.Random:
|
|
|
return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
|
|
return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
|
|
|
return 30.0
|
|
return 30.0
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
def _is_within_active_hours(self) -> bool:
|
|
def _is_within_active_hours(self) -> bool:
|
|
|
- """
|
|
|
|
|
- 判断当前是否在允许创建实例的时间段内
|
|
|
|
|
- """
|
|
|
|
|
|
|
+ """判断当前是否在允许创建实例和查询的时间段内"""
|
|
|
start_str = self.m_cfg.active_time_start
|
|
start_str = self.m_cfg.active_time_start
|
|
|
end_str = self.m_cfg.active_time_end
|
|
end_str = self.m_cfg.active_time_end
|
|
|
current_bj_time = datetime.utcnow().time()
|
|
current_bj_time = datetime.utcnow().time()
|
|
|
start_time = datetime.strptime(start_str, "%H:%M").time()
|
|
start_time = datetime.strptime(start_str, "%H:%M").time()
|
|
|
end_time = datetime.strptime(end_str, "%H:%M").time()
|
|
end_time = datetime.strptime(end_str, "%H:%M").time()
|
|
|
return start_time <= current_bj_time <= end_time
|
|
return start_time <= current_bj_time <= end_time
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
def update_config(self, new_cfg: BookerStandaloneConfig):
|
|
def update_config(self, new_cfg: BookerStandaloneConfig):
|
|
|
- """
|
|
|
|
|
- 动态更新配置
|
|
|
|
|
- """
|
|
|
|
|
- pass
|
|
|
|
|
-
|
|
|
|
|
|
|
+ """动态更新配置"""
|
|
|
|
|
+ with self.m_lock:
|
|
|
|
|
+ if self.m_cfg.enable and not new_cfg.enable:
|
|
|
|
|
+ self._log("Config dynamically updated: Group DISABLED.")
|
|
|
|
|
+ elif not self.m_cfg.enable and new_cfg.enable:
|
|
|
|
|
+ self._log("Config dynamically updated: Group ENABLED.")
|
|
|
|
|
+ else:
|
|
|
|
|
+ self._log("Config dynamically updated: Parameters refreshed.")
|
|
|
|
|
+ self.m_cfg = new_cfg
|
|
|
|
|
+
|
|
|
|
|
+ def get_status(self) -> GroupStatus:
|
|
|
|
|
+ with self.m_lock:
|
|
|
|
|
+ instance = self.m_instance
|
|
|
|
|
+ gid = self.m_cfg.identifier
|
|
|
|
|
+ enable = self.m_cfg.enable
|
|
|
|
|
+ plugin_name = self.m_cfg.plugin_config.plugin_name
|
|
|
|
|
+
|
|
|
|
|
+ plugins_status = []
|
|
|
|
|
+ healthy_count = 0
|
|
|
|
|
+ if instance:
|
|
|
|
|
+ st = instance.get_plugin_status()
|
|
|
|
|
+ if st.is_healthy:
|
|
|
|
|
+ healthy_count += 1
|
|
|
|
|
+ plugins_status.append(st)
|
|
|
|
|
+
|
|
|
|
|
+ return GroupStatus(
|
|
|
|
|
+ group_id=gid,
|
|
|
|
|
+ enable=enable,
|
|
|
|
|
+ plugin_name=plugin_name,
|
|
|
|
|
+ total_tasks=1 if instance else 0,
|
|
|
|
|
+ healthy_tasks=healthy_count,
|
|
|
|
|
+ plugins=plugins_status,
|
|
|
|
|
+ updated_at=utc_now_str(),
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+ def start(self):
|
|
|
|
|
+ """非阻塞启动,注册插件并开启后台工作线程"""
|
|
|
|
|
+ if not self.m_cfg.enable:
|
|
|
|
|
+ return
|
|
|
|
|
+
|
|
|
|
|
+ self._log("Starting Standalone GCO...")
|
|
|
|
|
+ plugin_name = self.m_cfg.plugin_config.plugin_name
|
|
|
|
|
+ class_name = "".join(part.title() for part in plugin_name.split('_'))
|
|
|
|
|
+ plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
|
|
|
|
|
+ self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
|
|
|
|
|
+
|
|
|
|
|
+ worker_name = f"Standalone-{self.m_cfg.identifier}"
|
|
|
|
|
+ threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
|
|
|
|
|
+
|
|
|
|
|
+ def stop(self):
|
|
|
|
|
+ """优雅停止"""
|
|
|
|
|
+ self._log("Stopping Standalone GCO...")
|
|
|
|
|
+ self.m_stop_event.set()
|
|
|
|
|
+ self._cleanup_instance("standalone stopped")
|
|
|
|
|
+
|
|
|
|
|
+ def _cleanup_instance(self, reason: str = ""):
|
|
|
|
|
+ with self.m_lock:
|
|
|
|
|
+ if self.m_instance is not None:
|
|
|
|
|
+ try:
|
|
|
|
|
+ self._log(f"🧹 Cleaned up instance. Reason: {reason}")
|
|
|
|
|
+ self.m_instance.cleanup()
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
|
|
|
|
|
+ finally:
|
|
|
|
|
+ self.m_instance = None
|
|
|
|
|
+
|
|
|
def _notify_date_changes(self, query_result: VSQueryResult):
|
|
def _notify_date_changes(self, query_result: VSQueryResult):
|
|
|
current_earliest_date = query_result.earliest_date
|
|
current_earliest_date = query_result.earliest_date
|
|
|
apt_type = query_result.apt_type
|
|
apt_type = query_result.apt_type
|
|
@@ -77,7 +146,7 @@ class BookerStandalone:
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
self._log(f"Failed to notify to cloud: {e}")
|
|
self._log(f"Failed to notify to cloud: {e}")
|
|
|
ThreadPool.getInstance().enqueue(_push_to_wx)
|
|
ThreadPool.getInstance().enqueue(_push_to_wx)
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
def _notify_book_result(self, book_result: VSBookResult):
|
|
def _notify_book_result(self, book_result: VSBookResult):
|
|
|
if book_result.success:
|
|
if book_result.success:
|
|
|
def _update_cloud_success():
|
|
def _update_cloud_success():
|
|
@@ -96,35 +165,19 @@ class BookerStandalone:
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
self._log(f"Failed to update success state to cloud: {e}")
|
|
self._log(f"Failed to update success state to cloud: {e}")
|
|
|
ThreadPool.getInstance().enqueue(_update_cloud_success)
|
|
ThreadPool.getInstance().enqueue(_update_cloud_success)
|
|
|
-
|
|
|
|
|
- def _countdown_wait(self, seconds: float, wait_for='') -> bool:
|
|
|
|
|
- """倒计时等待,动态刷新同一行,返回 False 表示被 stop 中断"""
|
|
|
|
|
- end = time.time() + seconds
|
|
|
|
|
- last_remaining = None
|
|
|
|
|
- while self.m_running and time.time() < end:
|
|
|
|
|
- remaining = int(end - time.time())
|
|
|
|
|
- if remaining != last_remaining:
|
|
|
|
|
- print(f"[BOOKER] Next {wait_for} in {remaining} seconds... (stop to exit)", end='\r', flush=True)
|
|
|
|
|
- last_remaining = remaining
|
|
|
|
|
- time.sleep(1)
|
|
|
|
|
- print()
|
|
|
|
|
- return self.m_running
|
|
|
|
|
|
|
|
|
|
def _init_instance(self):
|
|
def _init_instance(self):
|
|
|
"""初始化单实例并进行登录创建会话"""
|
|
"""初始化单实例并进行登录创建会话"""
|
|
|
- if self.m_instance is not None:
|
|
|
|
|
- self.m_instance.cleanup()
|
|
|
|
|
-
|
|
|
|
|
|
|
+ self._cleanup_instance("recreating new session")
|
|
|
|
|
+
|
|
|
now = time.time()
|
|
now = time.time()
|
|
|
if now < self.m_last_login_time + self.m_cfg.login_interval:
|
|
if now < self.m_last_login_time + self.m_cfg.login_interval:
|
|
|
- wait = self.m_last_login_time + self.m_cfg.login_interval - now
|
|
|
|
|
- self._countdown_wait(wait, wait_for='init instance')
|
|
|
|
|
-
|
|
|
|
|
|
|
+ wait_time = self.m_last_login_time + self.m_cfg.login_interval - now
|
|
|
|
|
+ self._log(f"Waiting {int(wait_time)}s for login interval cooldown...")
|
|
|
|
|
+ if self.m_stop_event.wait(wait_time):
|
|
|
|
|
+ return
|
|
|
|
|
+
|
|
|
plugin_name = self.m_cfg.plugin_config.plugin_name
|
|
plugin_name = self.m_cfg.plugin_config.plugin_name
|
|
|
- class_name = "".join(part.title() for part in plugin_name.split('_'))
|
|
|
|
|
- plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
|
|
|
|
|
- self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
|
|
|
|
|
-
|
|
|
|
|
plg_cfg = VSPlgConfig()
|
|
plg_cfg = VSPlgConfig()
|
|
|
plg_cfg.debug = self.m_cfg.debug
|
|
plg_cfg.debug = self.m_cfg.debug
|
|
|
plg_cfg.account = self.m_cfg.account
|
|
plg_cfg.account = self.m_cfg.account
|
|
@@ -132,49 +185,67 @@ class BookerStandalone:
|
|
|
plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
|
|
plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
|
|
|
plg_cfg.free_config = self.m_cfg.free_config
|
|
plg_cfg.free_config = self.m_cfg.free_config
|
|
|
plg_cfg.session_max_life = self.m_cfg.session_max_life
|
|
plg_cfg.session_max_life = self.m_cfg.session_max_life
|
|
|
-
|
|
|
|
|
- self.m_instance = self.m_factory.create("single_task", plugin_name)
|
|
|
|
|
- self.m_instance.set_log(self.m_logger)
|
|
|
|
|
- self.m_instance.set_config(plg_cfg)
|
|
|
|
|
-
|
|
|
|
|
- self.m_next_query_time = time.time() + self._get_wait_interval()
|
|
|
|
|
- self.m_last_login_time = time.time()
|
|
|
|
|
- self.m_instance.create_session()
|
|
|
|
|
- self._log("Session created successfully.")
|
|
|
|
|
|
|
|
|
|
- def start(self):
|
|
|
|
|
|
|
+ instance = self.m_factory.create(self.m_cfg.identifier, plugin_name)
|
|
|
|
|
+ instance.set_log(self.m_logger)
|
|
|
|
|
+ instance.set_config(plg_cfg)
|
|
|
|
|
+ with self.m_lock:
|
|
|
|
|
+ self.m_instance = instance
|
|
|
|
|
+
|
|
|
|
|
+ self._log("Creating session...")
|
|
|
|
|
+ try:
|
|
|
|
|
+ instance.create_session()
|
|
|
|
|
+ self.m_last_login_time = time.time()
|
|
|
|
|
+ self.m_next_query_time = time.time() + self._get_wait_interval()
|
|
|
|
|
+ self._log("Session created successfully.")
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ self._cleanup_instance("session creation failed")
|
|
|
|
|
+ raise
|
|
|
|
|
+
|
|
|
|
|
+ def _worker_loop(self):
|
|
|
"""
|
|
"""
|
|
|
- 单线程无限循环:心跳保活 -> 时间判定 -> 查询 -> 预定
|
|
|
|
|
|
|
+ 后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定
|
|
|
"""
|
|
"""
|
|
|
- self.m_running = True
|
|
|
|
|
- self._log("Auto Booker Started.")
|
|
|
|
|
-
|
|
|
|
|
- while self.m_running:
|
|
|
|
|
- if not self._is_within_active_hours():
|
|
|
|
|
- continue
|
|
|
|
|
- try:
|
|
|
|
|
- self._init_instance()
|
|
|
|
|
- break
|
|
|
|
|
- except Exception as e:
|
|
|
|
|
- self._log(f"Failed to create session: {e}. Retrying in 10s...")
|
|
|
|
|
- time.sleep(10)
|
|
|
|
|
|
|
+ self._log("Standalone worker loop started.")
|
|
|
|
|
|
|
|
- while self.m_running:
|
|
|
|
|
|
|
+ while not self.m_stop_event.is_set():
|
|
|
try:
|
|
try:
|
|
|
- now = time.time()
|
|
|
|
|
|
|
+ if not self.m_cfg.enable:
|
|
|
|
|
+ self.m_stop_event.wait(1.0)
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
if not self._is_within_active_hours():
|
|
if not self._is_within_active_hours():
|
|
|
|
|
+ self.m_stop_event.wait(5.0)
|
|
|
continue
|
|
continue
|
|
|
-
|
|
|
|
|
- if not self.m_instance.health_check():
|
|
|
|
|
|
|
+
|
|
|
|
|
+ # 1. 会话初始化
|
|
|
|
|
+ if self.m_instance is None:
|
|
|
|
|
+ try:
|
|
|
|
|
+ self._init_instance()
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ self._log(f"Failed to create session: {e}. Retrying in 10s...")
|
|
|
|
|
+ self.m_stop_event.wait(10.0)
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ # 2. 健康检查
|
|
|
|
|
+ if self.m_instance and not self.m_instance.health_check():
|
|
|
self._log("Health check failed. Session dead. Recreating session...")
|
|
self._log("Health check failed. Session dead. Recreating session...")
|
|
|
- self._init_instance()
|
|
|
|
|
|
|
+ self._cleanup_instance("session health check failed")
|
|
|
continue
|
|
continue
|
|
|
-
|
|
|
|
|
|
|
+
|
|
|
|
|
+ # 3. 查询等待
|
|
|
|
|
+ now = time.time()
|
|
|
if now < self.m_next_query_time:
|
|
if now < self.m_next_query_time:
|
|
|
- wait = self.m_next_query_time - now
|
|
|
|
|
- self._countdown_wait(wait, wait_for="query slot")
|
|
|
|
|
|
|
+ wait_sec = min(self.m_next_query_time - now, 1.0)
|
|
|
|
|
+ self.m_stop_event.wait(wait_sec)
|
|
|
|
|
+ continue
|
|
|
|
|
|
|
|
|
|
+ # 4. 随机选取 routing_key 进行查询
|
|
|
apt_types = self.m_cfg.appointment_types
|
|
apt_types = self.m_cfg.appointment_types
|
|
|
|
|
+ if not apt_types:
|
|
|
|
|
+ self.m_stop_event.wait(2.0)
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
weights = [float(t.weight) for t in apt_types]
|
|
weights = [float(t.weight) for t in apt_types]
|
|
|
apt_type = random.choices(apt_types, weights=weights, k=1)[0]
|
|
apt_type = random.choices(apt_types, weights=weights, k=1)[0]
|
|
|
|
|
|
|
@@ -183,17 +254,17 @@ class BookerStandalone:
|
|
|
query_result.apt_type = apt_type
|
|
query_result.apt_type = apt_type
|
|
|
self.m_next_query_time = time.time() + self._get_wait_interval()
|
|
self.m_next_query_time = time.time() + self._get_wait_interval()
|
|
|
self._notify_date_changes(query_result)
|
|
self._notify_date_changes(query_result)
|
|
|
|
|
+
|
|
|
|
|
+ # 5. 发现档期,执行自动预定
|
|
|
if query_result.success:
|
|
if query_result.success:
|
|
|
self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
|
|
self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
|
|
|
- # 5. 执行预定
|
|
|
|
|
book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
|
|
book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
|
|
|
self._notify_book_result(book_result)
|
|
self._notify_book_result(book_result)
|
|
|
if book_result.success:
|
|
if book_result.success:
|
|
|
self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
|
|
self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
|
|
|
- break
|
|
|
|
|
|
|
+ # 预定成功后可继续或等待后续任务
|
|
|
|
|
+ self.m_stop_event.wait(5.0)
|
|
|
|
|
+
|
|
|
except Exception as e:
|
|
except Exception as e:
|
|
|
- self._log(f"Loop Exception: {e}")
|
|
|
|
|
-
|
|
|
|
|
- def stop(self):
|
|
|
|
|
- """外部中断时调用"""
|
|
|
|
|
- self.m_running = False
|
|
|
|
|
|
|
+ self._log(f"Standalone loop exception: {e}")
|
|
|
|
|
+ self.m_stop_event.wait(2.0)
|