Przeglądaj źródła

fix(coordinate): fix sentinel race condition, plugin upgrade payload parsing and update docs

jerry 2 miesięcy temu
rodzic
commit
ac10a9b9c8

+ 14 - 8
booker.py

@@ -328,10 +328,12 @@ class BuiltinBookerGCO(BaseBookerGCO):
             instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
             instance.set_log(self.m_logger)
             instance.set_config(plg_cfg)
+            instance.create_session()
+
             all_keys = [apt.routing_key for apt in self.m_cfg.appointment_types]
             task = Task(
                 instance=instance,
-                next_run=time.time() + 999999, 
+                next_run=time.time(), 
                 task_ref=None,
                 acceptable_routing_keys=all_keys,
                 source_queue="built-in",
@@ -341,8 +343,6 @@ class BuiltinBookerGCO(BaseBookerGCO):
             with self.m_lock:
                 self.m_tasks.append(task)
 
-            instance.create_session()
-            task.next_run = time.time()
             success = True
             self._log(f"+++ Built-in Booker spawned: {plg_cfg.account.username}")
         except Exception as e:
@@ -360,7 +360,10 @@ class BuiltinBookerGCO(BaseBookerGCO):
                 if task:
                     self._remove_task(task, "spawn failed")
                 elif instance:
-                    instance.cleanup()
+                    try:
+                        instance.cleanup()
+                    except Exception:
+                        pass
 
     def _execute_book_job(self, task: Task, query_result: VSQueryResult):
         queue_name = f"auto.{query_result.apt_type.routing_key}"
@@ -566,9 +569,11 @@ class OrderBookerGCO(BaseBookerGCO):
             instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
             instance.set_log(self.m_logger)
             instance.set_config(plg_cfg)
+            instance.create_session()
+
             task = Task(
                 instance=instance,
-                next_run=time.time() + 999999, 
+                next_run=time.time(), 
                 task_ref=task_id,
                 acceptable_routing_keys=acceptable_keys, 
                 source_queue=target_routing_key,
@@ -578,8 +583,6 @@ class OrderBookerGCO(BaseBookerGCO):
             with self.m_lock:
                 self.m_tasks.append(task)
 
-            instance.create_session() 
-            task.next_run = time.time()
             success = True             
             self._log(f"+++ Order Booker spawned: {plg_cfg.account.username} (Target: {acceptable_keys})")
         except Exception as e:
@@ -598,7 +601,10 @@ class OrderBookerGCO(BaseBookerGCO):
                 if task:
                     self._remove_task(task, "spawn failed")
                 elif instance:
-                    instance.cleanup()
+                    try:
+                        instance.cleanup()
+                    except Exception:
+                        pass
                 if task_id:
                     with self.m_lock:
                         self.m_task_data_cache.pop(str(task_id), None)

+ 3 - 0
config/config_standalone.json

@@ -2,6 +2,7 @@
   {
     "identifier": "tls",
     "debug": true,
+    "enable": false,
     "plugin_config": {
       "lib_path": "plugins",
       "plugin_name": "tls_plugin",
@@ -54,6 +55,7 @@
   {
     "identifier": "usa",
     "debug": true,
+    "enable": false,
     "plugin_config": {
       "lib_path": "plugins",
       "plugin_name": "usa_plugin",
@@ -113,6 +115,7 @@
   {
     "identifier": "vfs",
     "debug": true,
+    "enable": true,
     "plugin_config": {
       "lib_path": "plugins",
       "plugin_name": "vfs_plugin",

+ 374 - 0
docs/node_config_cloud_storage_and_api.md

@@ -0,0 +1,374 @@
+# Coordinate 节点配置云端管理系统与 HTTP API 设计文档
+
+本文档详细说明 Coordinate 系统的节点配置(`config_booker.json`、`config_sentinel.json`、`config_standalone.json`)收归云端数据库(MySQL 8.x)的集中管理方案、表结构设计、HTTP 管理与下发 API,以及与 Coordinate 节点端(`main.py`、`utils/cloud_config.py`)周期轮询与热重载机制的联动方案。
+
+---
+
+## 1. 架构总览
+
+整个节点配置管理与同步系统的时序与拓扑流如下:
+
+```mermaid
+sequenceDiagram
+    autonumber
+    actor Admin as 管理员/Web前端
+    participant API as 云端配置管理服务 (API Server)
+    participant DB as MySQL 数据库 (node_configurations)
+    participant Node as Coordinate 节点 (main.py)
+
+    Note over Admin,DB: 【阶段一:配置初始化与可视化编辑】
+    Admin->>API: POST /api/node_configurations/save (保存 node01 的 sentinel 配置)
+    API->>API: 校验 JSON 语法合法性并计算 MD5 Hash
+    API->>DB: 写入/更新 node_configurations 表 & 记录审计日志
+    API-->>Admin: 返回保存成功
+
+    Note over Node,DB: 【阶段二:节点定期轮询与平滑热重载】
+    loop 每 30 秒轮询一次 (可配)
+        Node->>API: GET /api/node_configurations/detail?node_id=node01&role=sentinel
+        API->>DB: 查询 (role='sentinel', node_id='node01') 的配置与 Hash
+        API-->>Node: 返回配置内容与 config_hash
+        alt config_hash 发生变更
+            Node->>Node: 写入本地磁盘缓存 config/config_sentinel.json
+            Node->>Node: 执行 sync_groups() 差异化启动/停止/更新 GCO 实例
+            Node->>Node: 热重载完成,更新当前 current_hash
+        else config_hash 一致
+            Node->>Node: 无需变动,跳过
+        end
+    end
+```
+
+---
+
+## 2. 数据库表结构设计 (MySQL 8.x / MariaDB)
+
+采用**轻量单表 + 审计日志**结构:
+- `node_configurations`:存储各角色与各节点的配置主体(完整 JSON 格式)及自动计算的 MD5 哈希;
+- `node_config_audit_logs`:记录配置的修改历史、变更人与变更前后 Hash。
+
+```sql
+-- ----------------------------
+-- 1. 节点配置主表
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS `node_configurations` (
+  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增主键',
+  `role` VARCHAR(32) NOT NULL COMMENT '角色类型: sentinel / booker / standalone',
+  `node_id` VARCHAR(64) NOT NULL COMMENT '节点唯一标识,如: node01, node02 等',
+  `config_content` JSON NOT NULL COMMENT '完整配置内容 (JSON 数组或 JSON 对象)',
+  `config_hash` CHAR(32) GENERATED ALWAYS AS (MD5(CAST(`config_content` AS CHAR))) STORED COMMENT '配置内容 MD5 哈希,用于节点秒级比对',
+  `is_enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用: 1-启用, 0-禁用',
+  `description` VARCHAR(255) DEFAULT '' COMMENT '配置用途/备注说明',
+  `created_by` VARCHAR(64) DEFAULT 'system' COMMENT '创建人',
+  `updated_by` VARCHAR(64) DEFAULT 'system' COMMENT '最后更新人',
+  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_role_node` (`role`, `node_id`),
+  KEY `idx_updated_at` (`updated_at`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='节点角色配置主表';
+
+-- ----------------------------
+-- 2. 配置修改审计日志表
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS `node_config_audit_logs` (
+  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '自增主键',
+  `role` VARCHAR(32) NOT NULL COMMENT '角色类型',
+  `node_id` VARCHAR(64) NOT NULL COMMENT '节点标识',
+  `action` VARCHAR(32) NOT NULL COMMENT '操作类型: CREATE / UPDATE / TOGGLE / DELETE',
+  `before_hash` CHAR(32) DEFAULT NULL COMMENT '修改前配置 Hash',
+  `after_hash` CHAR(32) DEFAULT NULL COMMENT '修改后配置 Hash',
+  `operator` VARCHAR(64) NOT NULL DEFAULT 'system' COMMENT '操作人',
+  `remark` VARCHAR(500) DEFAULT '' COMMENT '修改原因或备注说明',
+  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
+  PRIMARY KEY (`id`),
+  KEY `idx_role_node_time` (`role`, `node_id`, `created_at`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='配置修改审计日志表';
+```
+
+---
+
+## 3. HTTP RESTful API 设计
+
+### 3.1 统一规范
+
+- **鉴权方式**: `Authorization: Bearer <token>`
+- **Content-Type**: `application/json`
+- **统一响应报文**:
+  ```json
+  {
+    "code": 0,          // 0 表示成功,非 0 为具体错误码
+    "message": "success",
+    "data": {}
+  }
+  ```
+
+---
+
+### 3.2 接口详细定义
+
+#### 1. 节点拉取配置详情(Worker 轮询专用核心接口)
+
+- **接口地址**: `GET /api/node_configurations/detail`
+- **Query 参数**:
+  | 参数名 | 类型 | 必填 | 说明 |
+  | :--- | :--- | :--- | :--- |
+  | `node_id` | string | 是 | 节点标识,如 `node01` |
+  | `role` | string | 是 | 角色类型,可选值: `sentinel` / `booker` / `standalone` |
+
+- **请求示例**:
+  ```http
+  GET /api/node_configurations/detail?node_id=node01&role=sentinel HTTP/1.1
+  Host: api.text.skin
+  Authorization: Bearer tok_e946329a60ff45ba807f3f41b0e8b7fc
+  ```
+
+- **响应示例**:
+  ```json
+  {
+    "code": 0,
+    "message": "success",
+    "data": {
+      "id": 1,
+      "role": "sentinel",
+      "node_id": "node01",
+      "is_enabled": 1,
+      "config_hash": "e2fc714c4727ee9395f324cd2e7f331f",
+      "config_content": [
+        {
+          "identifier": "vfs.ie.nl",
+          "debug": false,
+          "enable": true,
+          "need_account": true,
+          "need_proxy": true,
+          "proxy_pool": ["proxy-cheap"],
+          "proxy_cd": 300,
+          "session_max_life": 1800,
+          "active_time_start": "00:00",
+          "active_time_end": "23:59",
+          "sentinel": {
+            "account_source": "built-in",
+            "account_pool_id": "ie.nl.sentinel",
+            "target_instances": 1,
+            "account_cd": 10800,
+            "signal_ttl": 30,
+            "query_wait": {
+              "mode": "Random",
+              "fixed_wait": 10,
+              "random_min": 60,
+              "random_max": 300
+            }
+          },
+          "plugin_config": {
+            "lib_path": "plugins",
+            "plugin_name": "vfs_plugin",
+            "plugin_bin": "vfs_plugin.py",
+            "plugin_proto": "IVSPlg"
+          },
+          "appointment_types": [
+            {
+              "weight": 10,
+              "routing_key": "slot.dub.nl.tourist",
+              "city": "Dublin",
+              "visa_type": "Tourist",
+              "country": "Netherlands"
+            }
+          ],
+          "website": "https://visa.vfsglobal.com/irl/en/nld/login",
+          "free_config": {
+            "mission_code": "nld",
+            "mission_name": "Netherlands",
+            "country_code": "irl",
+            "country_name": "Ireland",
+            "culture_code": "en-US",
+            "language": "en",
+            "apt_configs": {
+              "slot.dub.nl.tourist": {
+                "center_name": "Netherlands Visa Application Center - Dublin",
+                "address": "Cunningham House, 130 Francis Street, Dublin 8 D08 H48R",
+                "vac_code": "NTDB",
+                "category_name": "All Short stay Categories",
+                "category_code": "TA",
+                "subcategory_name": "Tourist",
+                "subcategory_code": "To"
+              }
+            }
+          }
+        }
+      ],
+      "updated_at": "2026-08-23 00:30:00"
+    }
+  }
+  ```
+
+---
+
+#### 2. 管理后台查询节点配置列表
+
+- **接口地址**: `GET /api/node_configurations/list`
+- **Query 参数**:
+  | 参数名 | 类型 | 必填 | 说明 |
+  | :--- | :--- | :--- | :--- |
+  | `role` | string | 否 | 过滤角色: `sentinel` / `booker` / `standalone` |
+  | `node_id` | string | 否 | 过滤节点标识 (支持模糊搜索) |
+  | `page` | int | 否 | 页码 (默认 1) |
+  | `page_size`| int | 否 | 每页条数 (默认 20) |
+
+- **响应示例**:
+  ```json
+  {
+    "code": 0,
+    "message": "success",
+    "data": {
+      "total": 3,
+      "items": [
+        {
+          "id": 1,
+          "role": "sentinel",
+          "node_id": "node01",
+          "is_enabled": 1,
+          "config_hash": "e2fc714c4727ee9395f324cd2e7f331f",
+          "description": "节点01 哨兵轮询配置",
+          "updated_by": "admin",
+          "updated_at": "2026-08-23 00:30:00"
+        }
+      ]
+    }
+  }
+  ```
+
+---
+
+#### 3. 管理后台新增/更新节点配置 (Save / Upsert)
+
+- **接口地址**: `POST /api/node_configurations/save`
+- **请求体 (Body)**:
+  ```json
+  {
+    "role": "sentinel",
+    "node_id": "node01",
+    "is_enabled": 1,
+    "config_content": [ ... ],
+    "description": "节点01 哨兵监控配置",
+    "operator": "admin",
+    "remark": "开启英国意大利预约通道"
+  }
+  ```
+- **响应示例**:
+  ```json
+  {
+    "code": 0,
+    "message": "Configuration saved successfully",
+    "data": {
+      "id": 1,
+      "role": "sentinel",
+      "node_id": "node01",
+      "config_hash": "e2fc714c4727ee9395f324cd2e7f331f"
+    }
+  }
+  ```
+
+---
+
+## 4. Coordinate 客户端集成改动
+
+### 4.1 `toolkit/vs_cloud_api.py` 新增方法
+
+```python
+def get_node_configuration(self, role: str, node_id: str) -> Optional[Dict[str, Any]]:
+    """
+    从云端获取指定节点与角色的配置详情
+    GET /api/node_configurations/detail?node_id={node_id}&role={role}
+    """
+    url = f"{self.base_url}/api/node_configurations/detail"
+    params = {
+        "node_id": node_id,
+        "role": role
+    }
+    headers = self._get_headers()
+    resp = self._perform_request('GET', url, params=params, headers=headers, timeout=10)
+    result = resp.json()
+    if result.get("code") == 0:
+        return result.get("data") or {}
+    else:
+        raise BizLogicError(message=f"Get node configuration error: {result.get('message')}")
+```
+
+### 4.2 `utils/cloud_config.py` 改造
+
+```python
+def fetch_cloud_config(role: str, node_id: str) -> Any:
+    """
+    拉取云端节点配置并返回 config_content
+    """
+    try:
+        data = VSCloudApi.Instance().get_node_configuration(role=role, node_id=node_id)
+        if data and "config_content" in data:
+            return data["config_content"]
+    except Exception as e:
+        pass
+    return None
+```
+
+---
+
+## 5. 数据初始化迁移脚本
+
+在实施迁移时,运行以下脚本将本地文件灌入数据库:
+
+```python
+import os
+import json
+import hashlib
+import pymysql
+
+DB_CONFIG = {
+    "host": "localhost",
+    "user": "root",
+    "password": "your_password",
+    "database": "coordinate_db",
+    "charset": "utf8mb4"
+}
+
+CONFIG_FILES = {
+    "booker": "config/config_booker.json",
+    "sentinel": "config/config_sentinel.json",
+    "standalone": "config/config_standalone.json"
+}
+
+TARGET_NODES = ["node01"]  # 初始化的目标节点 ID
+
+def migrate():
+    conn = pymysql.connect(**DB_CONFIG)
+    cursor = conn.cursor()
+
+    for role, file_path in CONFIG_FILES.items():
+        if not os.path.exists(file_path):
+            print(f"[SKIP] File not found: {file_path}")
+            continue
+
+        with open(file_path, "r", encoding="utf-8") as f:
+            content = json.load(f)
+
+        content_json_str = json.dumps(content, ensure_ascii=False)
+
+        for node_id in TARGET_NODES:
+            sql = """
+            INSERT INTO node_configurations 
+                (role, node_id, config_content, description, created_by, updated_by)
+            VALUES 
+                (%s, %s, %s, %s, 'migration_script', 'migration_script')
+            ON DUPLICATE KEY UPDATE 
+                config_content = VALUES(config_content),
+                updated_by = 'migration_script',
+                updated_at = NOW();
+            """
+            cursor.execute(sql, (role, node_id, content_json_str, f"Migrated from {file_path}"))
+            print(f"[OK] Migrated {role} for node '{node_id}'")
+
+    conn.commit()
+    cursor.close()
+    conn.close()
+    print("All configurations migrated successfully.")
+
+if __name__ == "__main__":
+    migrate()
+```

+ 304 - 0
docs/plugin_cloud_storage_and_api.md

@@ -0,0 +1,304 @@
+# 云端插件管理系统与 HTTP API 设计文档
+
+本文档详细说明 Coordinate 系统的云端插件存储架构、数据库表设计(MySQL 8.x)、HTTP 管理与分发 API,以及与 Coordinate 节点端(`main.py`、`plugin_updater.py`)热重载升级机制的联动方案。
+
+---
+
+## 1. 架构总览
+
+整个插件管理与发布系统的拓扑与时序流如下:
+
+```mermaid
+sequenceDiagram
+    autonumber
+    actor Admin as 管理员/网页前端
+    participant API as 云端管理服务 (API Server)
+    participant DB as MySQL 数据库
+    participant OSS as 对象存储 (OSS/S3)
+    participant Redis as Redis (PubSub 消息中继)
+    participant Node as Coordinate 节点 (main.py)
+
+    Note over Admin,OSS: 【阶段一:插件发布与版本管理】
+    Admin->>API: POST /plugins/publish (上传代码/URL、指定版本)
+    API->>OSS: 上传 Python 代码并计算 SHA256 校验和
+    API->>DB: 写入 plugin_versions 表并更新 plugins.latest_version
+    API-->>Admin: 返回发布成功
+
+    Note over Admin,Node: 【阶段二:命令下发与即时热重载】
+    Admin->>API: POST /plugins/upgrade/dispatch (点击下发升级)
+    API->>DB: 查询当前需要更新的插件及最新版本下载地址
+    API->>Redis: PUBLISH vs:channel:upgrade [payload]
+    Redis-->>Node: 广播推送升级消息给 Upgrade-Listener
+    Node->>OSS: 下载目标插件代码
+    Node->>Node: 语法预检 (py_compile) 与原子文件覆盖
+    Node->>Node: 热重载当前插件实例 (reload_wrappers_for_plugin)
+    Node-->>Admin: 定时心跳上报 RoleStatus 显示已安装最新版本
+```
+
+---
+
+## 2. 数据库表结构设计 (MySQL 8.x / MariaDB)
+
+采用清晰实用的**轻量双表结构**:
+- `plugins`:维护插件基础元数据与当前生效的最新版本(供网页列表展示和快速判断最新版本)。
+- `plugin_versions`:维护每个版本的发布记录、下载地址、SHA256 校验和与更新日志(用于留痕、版本追溯与一键回滚)。
+
+```sql
+-- ----------------------------
+-- 1. 插件基础信息表
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS `plugins` (
+  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID (plugin_id)',
+  `name` VARCHAR(64) NOT NULL COMMENT '插件唯一英文标识,如: tls_plugin',
+  `display_name` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '插件展示名称,如: TLSContact欧洲多国签证预约插件',
+  `filename` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '本地落盘文件名,如: tls_plugin.py',
+  `latest_version` VARCHAR(32) NOT NULL DEFAULT '1.0.0' COMMENT '当前推荐/最新生效版本号',
+  `description` VARCHAR(512) NOT NULL DEFAULT '' COMMENT '插件功能描述',
+  `status` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态: 1-启用, 0-停用',
+  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_name` (`name`),
+  KEY `idx_status` (`status`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件基础元数据表';
+
+-- ----------------------------
+-- 2. 插件版本发布历史表
+-- ----------------------------
+CREATE TABLE IF NOT EXISTS `plugin_versions` (
+  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID (version_id)',
+  `plugin_id` INT UNSIGNED NOT NULL DEFAULT 0 COMMENT '关联插件ID (对应 plugins.id)',
+  `plugin_name` VARCHAR(64) NOT NULL COMMENT '关联插件英文标识 (对应 plugins.name)',
+  `version` VARCHAR(32) NOT NULL COMMENT '版本号,如: 1.0.1',
+  `download_url` VARCHAR(512) NOT NULL COMMENT '代码文件下载URL (S3/OSS/对象存储/静态HTTP地址)',
+  `sha256` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '文件SHA256校验码 (用于节点下载后防篡改/完整性校验)',
+  `changelog` TEXT COMMENT '本次版本更新说明',
+  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '版本发布时间',
+  PRIMARY KEY (`id`),
+  UNIQUE KEY `uk_plugin_version` (`plugin_id`, `version`),
+  KEY `idx_plugin_name` (`plugin_name`),
+  KEY `idx_plugin_id` (`plugin_id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='插件版本发布历史表';
+```
+
+---
+
+## 3. HTTP RESTful API 设计
+
+### 3.1 统一规范
+
+- **Content-Type**: `application/json`(发布文件时支持 `multipart/form-data`)
+- **统一响应报文**:
+  ```json
+  {
+    "code": 0,          // 0 表示成功,非0为具体业务错误码
+    "msg": "success",   // 状态提示信息
+    "data": {}          // 业务数据(对象或数组)
+  }
+  ```
+
+---
+
+### 3.2 接口详细列表
+
+#### 1. 发布插件 / 上传新版本
+- **URL**: `POST /plugins/publish`
+- **Content-Type**: `multipart/form-data` 或 `application/json`
+- **请求字段**:
+
+| 字段 | 类型 | 必填 | 说明 |
+| :--- | :--- | :--- | :--- |
+| `name` | string | 是 | 插件唯一英文标识,如 `tls_plugin` |
+| `version` | string | 是 | 版本号,如 `1.0.1` |
+| `display_name` | string | 否 | 插件中文展示名,如 `TLSContact欧洲多国签证预约插件` |
+| `description` | string | 否 | 插件功能描述 |
+| `file` | file | 二选一 | 直接上传 `.py` 代码文件(后端自动上传OSS并计算SHA256) |
+| `download_url` | string | 二选一 | 已有文件下载地址 |
+| `sha256` | string | 否 | 文件 SHA256 校验和(若直接填 URL 时可选提供) |
+| `changelog` | string | 否 | 本次版本更新日志 |
+| `set_as_latest` | bool | 否 | 是否立即将该版本设为插件最新版本(默认 `true`) |
+
+- **响应示例**:
+```json
+{
+  "code": 0,
+  "msg": "Plugin published successfully",
+  "data": {
+    "plugin_id": 1,
+    "name": "tls_plugin",
+    "version": "1.0.1",
+    "download_url": "https://oss.example.com/plugins/tls_plugin-1.0.1.py",
+    "sha256": "5d41402abc4b2a76b9719d911017c592..."
+  }
+}
+```
+
+---
+
+#### 2. 获取插件列表 (网页管理)
+- **URL**: `GET /plugins/list_all`
+- **请求参数**:
+  - `page`: int, 页码 (默认 1)
+  - `page_size`: int, 每页数量 (默认 20)
+  - `status`: int, 状态过滤 (1-启用, 0-停用, 可选)
+- **响应示例**:
+```json
+{
+  "code": 0,
+  "msg": "success",
+  "data": {
+    "list": [
+      {
+        "id": 1,
+        "name": "tls_plugin",
+        "display_name": "TLSContact欧洲多国签证预约插件",
+        "filename": "tls_plugin.py",
+        "latest_version": "1.0.1",
+        "description": "DrissionPage拟人化与CF挑战破解",
+        "status": 1,
+        "created_at": "2026-08-20 10:00:00",
+        "updated_at": "2026-08-21 14:00:00"
+      }
+    ],
+    "total": 1
+  }
+}
+```
+
+---
+
+#### 3. 获取插件详情 (含历史所有版本)
+- **URL**: `GET /plugins/detail?plugin_id={id}`
+- **响应示例**:
+```json
+{
+  "code": 0,
+  "msg": "success",
+  "data": {
+    "id": 1,
+    "name": "tls_plugin",
+    "display_name": "TLSContact欧洲多国签证预约插件",
+    "filename": "tls_plugin.py",
+    "latest_version": "1.0.1",
+    "description": "DrissionPage拟人化与CF挑战破解",
+    "status": 1,
+    "versions": [
+      {
+        "id": 2,
+        "version": "1.0.1",
+        "download_url": "https://oss.example.com/plugins/tls_plugin-1.0.1.py",
+        "sha256": "5d41402abc4b2a76b9719d911017c592...",
+        "changelog": "修复CF验证码重试卡死问题",
+        "created_at": "2026-08-21 14:00:00"
+      },
+      {
+        "id": 1,
+        "version": "1.0.0",
+        "download_url": "https://oss.example.com/plugins/tls_plugin-1.0.0.py",
+        "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
+        "changelog": "初始版本上线",
+        "created_at": "2026-08-20 10:00:00"
+      }
+    ]
+  }
+}
+```
+
+---
+
+#### 4. 编辑插件基础信息
+- **URL**: `PUT /plugins/update?plugin_id={id}`
+- **请求体**:
+```json
+{
+  "display_name": "TLSContact欧洲签证插件(更新版)",
+  "description": "更新后的功能描述说明",
+  "status": 1
+}
+```
+
+---
+
+#### 5. 切换生效版本 / 一键回滚
+- **URL**: `POST /plugins/switch-version`
+- **请求体**:
+```json
+{
+  "plugin_id": 1,
+  "version": "1.0.0"
+}
+```
+> 服务端将 `plugins.latest_version` 改为指定历史版本号。
+
+---
+
+#### 6. 删除插件 / 删除指定历史版本
+- **删除整套插件**: `DELETE /plugins/delete?plugin_id={id}`
+  - 删除该插件及其所有关联版本记录。
+- **删除指定版本**: `DELETE /plugins/delete_version?plugin_id={id}&version={version}`
+  - 删除某个具体的历史版本记录。
+
+---
+
+#### 7. 下发插件升级命令 (控制面与节点联动)
+- **URL**: `POST /plugins/upgrade/dispatch`
+- **请求体**:
+```json
+{
+  "target_node": "all",          // "all" 表示全量广播,或指定特定节点 node_id 如 "node01"
+  "plugins": ["tls_plugin"]      // 指定升级的插件英文名列表;传空数组 [] 表示对所有启用的插件下发最新版
+}
+```
+- **服务端处理与广播**:
+  1. 服务端查询 DB 组装目标插件的最新版本元数据数组;
+  2. 根据 `target_node` 确定 Redis 频道(`vs:channel:upgrade` 或 `vs:channel:upgrade:{node_id}`);
+  3. 执行 `redis_client.publish(channel, json.dumps(payload))`。
+
+- **广播 Payload 结构示例**:
+```json
+[
+  {
+    "name": "tls_plugin",
+    "filename": "tls_plugin.py",
+    "version": "1.0.1",
+    "download_url": "https://oss.example.com/plugins/tls_plugin-1.0.1.py",
+    "sha256": "5d41402abc4b2a76b9719d911017c592..."
+  }
+]
+```
+
+---
+
+#### 8. 获取当前全量最新可用插件清单 (节点主动拉取)
+- **URL**: `GET /plugins/latest`
+- **响应示例**:
+```json
+{
+  "code": 0,
+  "msg": "success",
+  "data": [
+    {
+      "name": "tls_plugin",
+      "display_name": "TLSContact欧洲多国签证预约插件",
+      "filename": "tls_plugin.py",
+      "version": "1.0.1",
+      "description": "DrissionPage拟人化与CF挑战破解",
+      "download_url": "https://oss.example.com/plugins/tls_plugin-1.0.1.py",
+      "sha256": "5d41402abc4b2a76b9719d911017c592...",
+      "changelog": "修复CF验证码重试卡死问题"
+    }
+  ]
+}
+```
+
+---
+
+## 4. 与 Coordinate 节点本地代码对应关系
+
+| 业务动作 | 节点对应代码位置 |
+| :--- | :--- |
+| **升级消息监听** | [main.py: start_upgrade_listener()](file:///Users/hujiarui/workspace/coordinate/main.py#L153-L180) |
+| **版本比对规则** | [utils/plugin_updater.py: is_newer_version()](file:///Users/hujiarui/workspace/coordinate/utils/plugin_updater.py#L25-L27) |
+| **安全下载与编译安装** | [utils/plugin_updater.py: download_and_install_plugin()](file:///Users/hujiarui/workspace/coordinate/utils/plugin_updater.py#L117-L154) |
+| **热重载运行中实例** | [main.py: reload_wrappers_for_plugin()](file:///Users/hujiarui/workspace/coordinate/main.py#L104-L123) |
+| **节点版本心跳上报** | [vs_types.py: RoleStatus.installed_plugins](file:///Users/hujiarui/workspace/coordinate/vs_types.py#L290-L300) |

+ 12 - 4
main.py

@@ -122,7 +122,7 @@ def handle_plugin_upgrades(
     upgraded_any = False
 
     for item in upgrade_items:
-        plugin_name = item.get("plugin_name")
+        plugin_name = item.get("name")
         target_version = str(item.get("version", ""))
         if not plugin_name or not target_version:
             continue
@@ -139,6 +139,7 @@ def handle_plugin_upgrades(
                     download_url=item.get("download_url"),
                     code_content=item.get("code"),
                     filename=item.get("filename"),
+                    expected_sha256=item.get("sha256"),
                 )
                 logger.info(f"✅ Plugin '{plugin_name}' v{target_version} installed successfully.")
                 reload_wrappers_for_plugin(plugin_name, wrappers, gco_classes, logger)
@@ -305,9 +306,16 @@ def main():
             while not upgrade_queue.empty():
                 try:
                     payload = upgrade_queue.get_nowait()
-                    plugins_items = payload.get("plugins", [])
-                    if isinstance(plugins_items, dict):
-                        plugins_items = [plugins_items]
+                    plugins_items = []
+                    if isinstance(payload, list):
+                        plugins_items = payload
+                    elif isinstance(payload, dict):
+                        if "plugins" in payload:
+                            p = payload["plugins"]
+                            plugins_items = p if isinstance(p, list) else [p]
+                        else:
+                            plugins_items = [payload]
+
                     if plugins_items:
                         if handle_plugin_upgrades(plugins_items, wrappers, gco_classes, logger):
                             # 升级成功,立即刷新并上报最新 RoleStatus

+ 3 - 3
plugins/vfs_plugin.py

@@ -115,7 +115,7 @@ class BrowserResponse:
 
 class VfsPlugin(IVSPlg):
     name = "vfs_plugin"
-    version = "1.0.0"
+    version = "1.0.1"
     description = "VFS Global全球多国签证预约插件 (支持多中心、多签证类型与CF破解)"
 
     def __init__(self, group_id: str):
@@ -163,9 +163,9 @@ class VfsPlugin(IVSPlg):
     
     def _log(self, message):
         if self.logger:
-            self.logger(f'[TlsPlugin] [{self.group_id}] [{self.instance_id}] {message}')
+            self.logger(f'[VfsPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         else:
-            print(f'[TlsPlugin] [{self.group_id}] [{self.instance_id}] {message}')
+            print(f'[VfsPlugin] [{self.group_id}] [{self.instance_id}] {message}')
             
     def keep_alive(self):
         try:

+ 8 - 5
sentinel.py

@@ -264,12 +264,12 @@ class SentinelGCO:
             instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
             instance.set_log(self.m_logger)
             instance.set_config(plg_cfg)
-            task = Task(instance=instance, qw_cfg=self.m_cfg.sentinel.query_wait, next_run=time.time() + 999999, book_allowed=False)
+            
+            instance.create_session()
+            
+            task = Task(instance=instance, qw_cfg=self.m_cfg.sentinel.query_wait, next_run=time.time(), book_allowed=False)
             with self.m_lock:
                 self.m_tasks.append(task)
-
-            instance.create_session()
-            task.next_run = time.time()
             success = True
             self._log(f"+++ Sentinel spawned: {plg_cfg.account.username}")
         except Exception as e:
@@ -287,4 +287,7 @@ class SentinelGCO:
                 if task:
                     self._remove_task(task, "spawn failed")
                 elif instance is not None:
-                    instance.cleanup()
+                    try:
+                        instance.cleanup()
+                    except Exception:
+                        pass

+ 12 - 3
utils/plugin_updater.py

@@ -120,6 +120,7 @@ def download_and_install_plugin(
     download_url: Optional[str] = None,
     code_content: Optional[str] = None,
     filename: Optional[str] = None,
+    expected_sha256: Optional[str] = None,
     plugins_dir: str = PLUGINS_DIR,
 ) -> bool:
     """
@@ -142,13 +143,21 @@ def download_and_install_plugin(
         else:
             raise ValueError(f"Neither download_url nor code_content provided for '{plugin_name}'")
 
-        # 2. 语法预检(防止下载坏代码导致运行时崩溃)
+        # 2. SHA256 校验(若提供)
+        if expected_sha256:
+            import hashlib
+            with open(tmp_path, "rb") as f:
+                computed_sha256 = hashlib.sha256(f.read()).hexdigest()
+            if computed_sha256.lower() != expected_sha256.strip().lower():
+                raise ValueError(f"SHA256 checksum mismatch for '{plugin_name}': expected {expected_sha256}, got {computed_sha256}")
+
+        # 3. 语法预检(防止下载坏代码导致运行时崩溃)
         py_compile.compile(tmp_path, doraise=True)
 
-        # 3. 原子覆盖替换到 plugins/ 目录
+        # 4. 原子覆盖替换到 plugins/ 目录
         os.replace(tmp_path, target_path)
 
-        # 4. 重新触发内存动态扫描,更新内存中的版本数据(不落盘)
+        # 5. 重新触发内存动态扫描,更新内存中的版本数据(不落盘)
         scan_plugins(plugins_dir)
 
         return True

+ 0 - 1
vs_types.py

@@ -231,7 +231,6 @@ class Task(BaseModel):
     next_remote_ping: float = 0.0
     
     model_config = {
-        "underscore_attrs_are_private": True,
         "arbitrary_types_allowed": True
     }