release: bump version to 1.1.7, update xq0031_xq0032 plugin to 1.0.8
主要变更: 1. 整体版本升级至1.1.7,更新安装包与shell版本号 2. 新增API与后端能力: - 新增停止运行接口,支持强制终止插件进程与浏览器子进程 - 云端会话令牌与下载票据落库,适配多worker部署 - 优化Chrome版本读取逻辑,避免弹窗与编码问题 3. xq0031_xq0032插件升级至1.0.8: - 新增仓库中文名自动筛选功能,简化用户操作 - 优化ERP登录与报表导出流程,修复标签页残留问题 - 新增前端强制停止按钮,支持实时终止运行 - 修复中文编码与乱码问题,兼容Windows非UTF-8环境 4. 修复授权校验逻辑,确保账号与授权匹配 5. 更新文档与部署脚本,修正发版流程说明
This commit is contained in:
@@ -132,7 +132,7 @@ def admin_password(p: schemas.PwdIn,
|
||||
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
|
||||
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 只验证不建号
|
||||
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在
|
||||
# core.auth._cloud_tokens(_issue_cloud_token 签发、_cloud_account 解析),此处不再重复声明。
|
||||
# core.auth(_issue_cloud_token 签发落库 cloud_tokens 表、_cloud_account 解析),此处不再重复声明。
|
||||
|
||||
|
||||
@router.post("/auth/exchange")
|
||||
|
||||
@@ -146,8 +146,9 @@ def me_control_list(x_api_token: str = Header(default="", alias="X-API-Token"))
|
||||
return {"ticket": crypto._sign_blob(payload), "control": payload}
|
||||
|
||||
|
||||
# 一次性下载票据(内存态,兑换后失效)
|
||||
_DL_TICKETS: dict = {}
|
||||
# 一次性下载票据落库(download_tickets 表):gunicorn 多 worker 下签发与兑换必须共享同一份状态,
|
||||
# 否则 A worker 签发的票据落到 B/C/D worker 兑换会 404「票据无效」,3/4 概率下载失败(同云令牌坑)。
|
||||
_DL_TICKET_TTL = 3600 # 票据有效期(秒):签发后 1 小时未兑换即清理
|
||||
|
||||
|
||||
@router.get("/api/plugins/{plugin_id}/versions/{version}/download-ticket")
|
||||
@@ -172,10 +173,16 @@ def download_ticket(plugin_id: str, version: str,
|
||||
path = config.PKG_DIR / ver["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{ver['filename']}")
|
||||
# 票据内含可下载文件名与校验值;用一次性 nonce 存内存,兑换后失效
|
||||
# 票据内含可下载文件名与校验值;落库共享,兑换时原子置 used=1 作废
|
||||
nonce = secrets.token_hex(16)
|
||||
_DL_TICKETS[nonce] = {"filename": ver["filename"], "sha256": ver["sha256"] or "",
|
||||
"used": False}
|
||||
with _db() as conn:
|
||||
# 顺手清理过期票据,防表无限增长
|
||||
conn.execute(
|
||||
"DELETE FROM download_tickets WHERE created_at < DATE_SUB(NOW(), INTERVAL %d SECOND)"
|
||||
% int(_DL_TICKET_TTL))
|
||||
conn.execute(
|
||||
"INSERT INTO download_tickets(nonce, filename, sha256, used) VALUES (%s, %s, %s, 0)",
|
||||
(nonce, ver["filename"], ver["sha256"] or ""))
|
||||
url = f"/api/download/{nonce}"
|
||||
return {"ticket": nonce, "url": url, "filename": ver["filename"],
|
||||
"sha256": ver["sha256"] or "", "expiresAt": _now()}
|
||||
@@ -185,15 +192,19 @@ def download_ticket(plugin_id: str, version: str,
|
||||
def download(ticket: str, x_api_token: str = Header(default="", alias="X-API-Token")):
|
||||
"""兑换下载票据:一次性有效,兑换即作废并写审计。"""
|
||||
_check_token(x_api_token)
|
||||
item = _DL_TICKETS.get(ticket)
|
||||
if not item or item["used"]:
|
||||
with _db() as conn:
|
||||
# 原子占位:仅 used=0 才能改成 1,命中行数=0 说明票据不存在或已被兑换
|
||||
cur = conn.execute(
|
||||
"UPDATE download_tickets SET used = 1 WHERE nonce = %s AND used = 0", (ticket,))
|
||||
row = conn.execute(
|
||||
"SELECT filename FROM download_tickets WHERE nonce = %s", (ticket,)).fetchone()
|
||||
if not cur.rowcount or not row:
|
||||
raise HTTPException(404, "下载票据无效或已使用")
|
||||
item["used"] = True
|
||||
path = config.PKG_DIR / item["filename"]
|
||||
path = config.PKG_DIR / row["filename"]
|
||||
if not path.exists():
|
||||
raise HTTPException(404, f"包文件缺失:{item['filename']}")
|
||||
_audit("", "download-ticket", item["filename"])
|
||||
return FileResponse(path, filename=item["filename"], media_type="application/octet-stream")
|
||||
raise HTTPException(404, f"包文件缺失:{row['filename']}")
|
||||
_audit("", "download-ticket", row["filename"])
|
||||
return FileResponse(path, filename=row["filename"], media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.post("/api/runtime/report")
|
||||
|
||||
@@ -14,8 +14,8 @@ import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from fastapi import HTTPException
|
||||
|
||||
@@ -116,8 +116,8 @@ def _auth_fail(account: str) -> None:
|
||||
|
||||
# ==================== 云端会话 token(员工端扫码登录,§2.2) ====================
|
||||
_CLOUD_TOKEN_TTL = 7 * 24 * 3600 # 云端会话 token 有效期(秒,7 天)
|
||||
_cloud_tokens: dict = {} # token -> {exp, account, nickname};壳持此调云端 API
|
||||
_cloud_lock = threading.Lock()
|
||||
# 云令牌落库(cloud_tokens 表)而非进程内存:gunicorn 多 worker 下登录签发的令牌
|
||||
# 必须能被任意 worker 解出,否则 Bearer 身份解析只有 1/N 概率命中。
|
||||
|
||||
|
||||
def _auth_account_lookup(account: str) -> dict:
|
||||
@@ -134,32 +134,38 @@ def _auth_account_lookup(account: str) -> dict:
|
||||
|
||||
|
||||
def _cloud_account(bearer: str) -> str:
|
||||
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。"""
|
||||
"""从 Bearer 云端会话 token 解出工号(§2.2);无效/过期/缺失返回空串。
|
||||
|
||||
查 cloud_tokens 表(落库共享):签发与解析不再受 worker 进程限制。
|
||||
库不可用时返回空串(身份解析失败不抛异常,交由各路由的兜底逻辑处理)。
|
||||
"""
|
||||
token = (bearer or "").strip()
|
||||
if token.lower().startswith("bearer "):
|
||||
token = token[7:].strip()
|
||||
if not token:
|
||||
return ""
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
rec = _cloud_tokens.get(token)
|
||||
if rec and rec["exp"] >= now:
|
||||
return rec["account"]
|
||||
if rec: # 过期顺手清理,防内存无限增长
|
||||
_cloud_tokens.pop(token, None)
|
||||
return ""
|
||||
try:
|
||||
with _db() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT account FROM cloud_tokens WHERE token = %s AND expires_at > NOW()",
|
||||
(token,)).fetchone()
|
||||
except Exception: # noqa: BLE001 库异常按“无身份”处理,不阻断请求
|
||||
return ""
|
||||
return str(row["account"]) if row else ""
|
||||
|
||||
|
||||
def _issue_cloud_token(account: str, nickname: str) -> str:
|
||||
"""签发云端会话 token 并写入共享存储(与 _cloud_account 同源,供 apis/auth /auth/exchange 调用)。
|
||||
"""签发云端会话 token 并落库(与 _cloud_account 同源,供 apis/auth /auth/exchange 调用)。
|
||||
|
||||
之前 apis/auth 里另建了一份同名 dict,写读不通导致 Bearer 永远解不出账号;这里统一出口。
|
||||
之前用进程内存 dict,gunicorn 多 worker 下写读不通导致 Bearer 随机解不出账号;改为落库。
|
||||
"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = time.time()
|
||||
with _cloud_lock:
|
||||
for k in [k for k, v in _cloud_tokens.items() if v["exp"] < now]:
|
||||
_cloud_tokens.pop(k, None)
|
||||
_cloud_tokens[token] = {"exp": now + _CLOUD_TOKEN_TTL, "account": account,
|
||||
"nickname": nickname}
|
||||
expires = datetime.now() + timedelta(seconds=_CLOUD_TOKEN_TTL)
|
||||
with _db() as conn:
|
||||
# 顺手清理已过期令牌,防表无限增长
|
||||
conn.execute("DELETE FROM cloud_tokens WHERE expires_at < NOW()")
|
||||
conn.execute(
|
||||
"INSERT INTO cloud_tokens(token, account, nickname, expires_at) VALUES (%s, %s, %s, %s)",
|
||||
(token, account, nickname, expires.strftime("%Y-%m-%d %H:%M:%S")))
|
||||
conn.commit()
|
||||
return token
|
||||
@@ -21,7 +21,7 @@ from controlplane.core.crypto import _hash_password
|
||||
# 初始迁移版本:全量 DDL 建齐后登记;后续增量 DDL 在此追加新版本并配套迁移逻辑
|
||||
_SCHEMA_VERSION = "20260917_001"
|
||||
|
||||
# 全量 DDL(11 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
# 全量 DDL(13 张表,MySQL 5.7 兼容;与 tools/schema_mysql.sql 逐条一致)
|
||||
_DDL_TABLES = (
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
@@ -204,6 +204,28 @@ _DDL_TABLES = (
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (token),
|
||||
KEY idx_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)'
|
||||
""",
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (nonce),
|
||||
KEY idx_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)'
|
||||
""",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -215,3 +215,29 @@ CREATE TABLE IF NOT EXISTS file_sources (
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_category (category)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='大文件源(内网直链,走内网文件服务器)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 云端会话令牌:落库共享(gunicorn 多 worker 下 Bearer 身份解析通用)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS cloud_tokens (
|
||||
token VARCHAR(64) NOT NULL COMMENT '云端会话令牌(secrets.token_urlsafe(32))',
|
||||
account VARCHAR(64) NOT NULL COMMENT '所属账号(工号)',
|
||||
nickname VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称快照(登录时冗余,省一次查库)',
|
||||
expires_at DATETIME NOT NULL COMMENT '过期时间(签发时间 + 7 天)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (token),
|
||||
KEY idx_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='云端会话令牌(落库共享,多 worker 通用)';
|
||||
|
||||
-- ------------------------------------------------------------
|
||||
-- 一次性插件下载票据:落库共享,多 worker 通用(进程内存版在 4 worker 下 3/4 概率查不到票据)
|
||||
-- ------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS download_tickets (
|
||||
nonce VARCHAR(32) NOT NULL COMMENT '一次性下载票据(secrets.token_hex(16))',
|
||||
filename VARCHAR(255) NOT NULL COMMENT '插件包文件名(packages/ 下)',
|
||||
sha256 CHAR(64) NOT NULL DEFAULT '' COMMENT '安装包 sha256 校验值',
|
||||
used TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否已兑换:1=是 0=否(兑换即作废)',
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '签发时间',
|
||||
PRIMARY KEY (nonce),
|
||||
KEY idx_created (created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='一次性插件下载票据(落库共享,多 worker 通用)';
|
||||
|
||||
@@ -13,7 +13,7 @@ from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target
|
||||
from webhost.backend.core.runner import RunReq, _run_target, terminate_run
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
@@ -94,6 +94,21 @@ def get_run(run_id: str, request: Request) -> dict:
|
||||
return run
|
||||
|
||||
|
||||
@router.post("/api/runs/{run_id}/stop")
|
||||
def stop_run(run_id: str, request: Request) -> dict:
|
||||
"""手动强制停止指定运行:仅运行属主可操作,整树强杀执行子进程(含浏览器)。"""
|
||||
account = _require_login(request)
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id)
|
||||
if not run or run.get("account") != account:
|
||||
raise HTTPException(404, "运行不存在")
|
||||
if run.get("status") != "running":
|
||||
raise HTTPException(409, "运行已结束,无需停止")
|
||||
if not terminate_run(run_id):
|
||||
raise HTTPException(409, "任务尚未真正启动(排队中或刚结束),请稍候再试")
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
|
||||
@@ -116,9 +116,10 @@ def _read_version(exe: Path) -> str:
|
||||
import subprocess as _sp
|
||||
try:
|
||||
out2 = _sp.run(
|
||||
["powershell", "-NoProfile", "-Command",
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command",
|
||||
"(Get-Item -LiteralPath '%s').VersionInfo.ProductVersion" % exe],
|
||||
capture_output=True, text=True, timeout=5)
|
||||
capture_output=True, text=True, timeout=5,
|
||||
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0)) # 不弹 PowerShell 窗口
|
||||
v = (out2.stdout or "").strip()
|
||||
return v if _VERSION_RE.match(v) else ""
|
||||
except Exception: # noqa: BLE001
|
||||
|
||||
@@ -145,13 +145,16 @@ def license_status() -> tuple[str, dict | None]:
|
||||
|
||||
|
||||
def ensure_license(account: str) -> tuple[bool, dict | None]:
|
||||
"""确保本地授权票据可用:ok → (True, payload);否则联网刷新一次后复查。
|
||||
"""确保本地授权票据可用且属于当前账号:ok → (True, payload);否则联网刷新一次后复查。
|
||||
|
||||
票据必须与登录账号一致:票据只按 expiresAt 判过期,换账号登录后旧票仍在有效期内,
|
||||
沿用旧票会让「个人中心可见插件」与「运行门禁」停留在上一账号的授权快照
|
||||
(表现为换账号后显示"暂无可用插件"),故账号不匹配一律视为不可用并强制刷新。
|
||||
刷新失败(离线/控制面不可达)→ (False, None)。这是「可见性/运行/平台登录」的统一授权门禁,
|
||||
过期且实际在线时会自动刷新恢复(用户无感),离线则拒绝并提示联网刷新。
|
||||
"""
|
||||
status, payload = license_status()
|
||||
if status == "ok":
|
||||
if status == "ok" and (payload or {}).get("userId") == account:
|
||||
return True, payload
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _sync_licensing # 延迟导入,避免模块环
|
||||
@@ -159,7 +162,7 @@ def ensure_license(account: str) -> tuple[bool, dict | None]:
|
||||
except Exception as _exc: # noqa: BLE001 联网刷新失败(离线/控制面不可达)
|
||||
_LOGGER.warning("授权票据联网刷新失败(离线或控制面不可达):%s", _exc)
|
||||
status, payload = license_status()
|
||||
return (status == "ok"), payload
|
||||
return (status == "ok" and (payload or {}).get("userId") == account), payload
|
||||
|
||||
|
||||
# ==================== 缓存写读 ====================
|
||||
@@ -285,11 +288,17 @@ def _push_report(rec: dict) -> bool:
|
||||
|
||||
|
||||
def _push_via_tempfile(rec: dict) -> None:
|
||||
"""向 /api/runtime/report 的同步 POST(requests)。"""
|
||||
"""向 /api/runtime/report 的同步 POST(requests)。
|
||||
必须带 X-API-Token 内部凭证:中心机 CONTROLPLANE_TOKEN 非空时该接口强制校验,
|
||||
无头 POST 一律 401(此前运行上报全部静默失败落离线暂存、补报同样无头永远补不上),
|
||||
与 cpapi.py 各接口的头注入保持一致。"""
|
||||
import requests
|
||||
|
||||
from webhost.backend.core import config
|
||||
|
||||
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
|
||||
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
|
||||
json=rec, timeout=5)
|
||||
json=rec, headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
|
||||
|
||||
|
||||
@@ -32,7 +32,9 @@ def _plugin_schema(p) -> dict:
|
||||
fields = p.fields
|
||||
caps = (manifest or {}).get("capabilities") or p.capabilities
|
||||
perms = (manifest or {}).get("permissions") or p.permissions
|
||||
return {"id": p.id, "name": name, "version": p.version,
|
||||
return {"id": p.id, "name": name,
|
||||
# 版本优先取 plugin.json 的 version(与发布包一致),缺 manifest 时回退类的默认值
|
||||
"version": (manifest or {}).get("version") or p.version,
|
||||
"description": description, "uses_month": getattr(p, "uses_month", False),
|
||||
"ui": bool((manifest or {}).get("ui")),
|
||||
"capabilities": caps, "permissions": perms, "fields": fields}
|
||||
|
||||
@@ -35,10 +35,12 @@ except OSError:
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
"""写一行 JSON 到协议通道(原始 stdout)。插件 print 已改道 stderr,不污染协议。"""
|
||||
"""写一行 JSON 到协议通道(原始 stdout.buffer,显式 UTF-8 字节)。
|
||||
插件 print 已改道 stderr,不污染协议;不走文本层是避免 Windows GBK 环境下
|
||||
stdout 按 locale 编码导致中文变 mojibake(父进程按 UTF-8 解码会对不上)。"""
|
||||
try:
|
||||
_PROTO.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
_PROTO.flush()
|
||||
_PROTO.buffer.write((json.dumps(obj, ensure_ascii=False) + "\n").encode("utf-8"))
|
||||
_PROTO.buffer.flush()
|
||||
except Exception: # noqa: BLE001 通道已关则静默
|
||||
pass
|
||||
|
||||
@@ -65,12 +67,14 @@ def _run() -> int:
|
||||
if "--allowed" in sys.argv else "")
|
||||
allowed = {s for s in allowed_arg.split(",") if s} if allowed_arg else None
|
||||
|
||||
# fields 经 stdin 传入(单行 JSON)
|
||||
# fields 经 stdin 传入(单行 JSON,UTF-8 字节):显式走 buffer 按 UTF-8 解,
|
||||
# 不依赖 sys.stdin 的 locale 解码(Windows GBK 环境下中文会被解出乱码/孤立代理字符,
|
||||
# 导致 fields 值与插件内字符串常量比对失败,如「未知执行模式」)
|
||||
fields: dict = {}
|
||||
try:
|
||||
_line = sys.stdin.readline().strip()
|
||||
if _line:
|
||||
fields = json.loads(_line) or {}
|
||||
_raw = sys.stdin.buffer.readline().strip()
|
||||
if _raw:
|
||||
fields = json.loads(_raw) or {}
|
||||
except Exception as _e: # noqa: BLE001
|
||||
fields = {}
|
||||
|
||||
|
||||
@@ -32,6 +32,34 @@ class RunReq(BaseModel):
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
# ==================== 手动强制停止 ====================
|
||||
# run_id → 执行中 Job 句柄(供 POST /api/runs/{id}/stop 整树强杀,含浏览器孙进程)
|
||||
_ACTIVE: dict = {}
|
||||
_ACTIVE_LOCK = threading.Lock()
|
||||
_USER_STOPPED: set = set()
|
||||
_STOP_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def terminate_run(run_id: str) -> bool:
|
||||
"""手动终止运行:登记停止标记并整树强杀 Job。返回是否已找到并触发终止。"""
|
||||
with _ACTIVE_LOCK:
|
||||
job = _ACTIVE.get(run_id)
|
||||
with _STOP_LOCK:
|
||||
_USER_STOPPED.add(run_id)
|
||||
if job is None:
|
||||
return False # 尚未真正拉起执行子进程(排队中)或已结束
|
||||
try:
|
||||
job.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _is_user_stopped(run_id: str) -> bool:
|
||||
with _STOP_LOCK:
|
||||
return run_id in _USER_STOPPED
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
|
||||
|
||||
@@ -55,14 +83,24 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
|
||||
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
|
||||
job = _winjob.Job(max_mem_mb=max_mem_mb)
|
||||
# 子进程 stdio 编码统一 UTF-8:默认跟随 Windows locale(GBK) 会导致
|
||||
# stderr 中文 traceback 变 mojibake、stdin JSON 中文解出孤立代理字符
|
||||
_child_env = dict(os.environ)
|
||||
_child_env["PYTHONIOENCODING"] = "utf-8"
|
||||
_child_env["PYTHONUTF8"] = "1"
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
cmd,
|
||||
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, text=True, encoding="utf-8",
|
||||
errors="replace",
|
||||
errors="replace", env=_child_env,
|
||||
# 抑制宿主进程的控制台窗口(runner.exe 为 console 子系统),
|
||||
# 同时 stdout/stderr 走 PIPE 捕获不受影响
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
)
|
||||
job.assign(proc)
|
||||
with _ACTIVE_LOCK:
|
||||
_ACTIVE[run_id] = job # 登记句柄,供手动强制停止整树强杀
|
||||
except Exception as e: # noqa: BLE001 子进程拉起失败
|
||||
job.close()
|
||||
_st._set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
|
||||
@@ -134,6 +172,10 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
result=ev.get("result"), error=ev.get("error"))
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
|
||||
"error": ev.get("error")})
|
||||
elif _is_user_stopped(run_id):
|
||||
msg = "用户手动强制停止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
elif timed_out:
|
||||
msg = f"插件执行超时({timeout}s)已强制终止"
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
@@ -143,6 +185,8 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
_st._set_run(run_id, status="error", result=None, error=msg)
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||||
finally:
|
||||
with _ACTIVE_LOCK:
|
||||
_ACTIVE.pop(run_id, None)
|
||||
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
|
||||
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
|
||||
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
|
||||
|
||||
@@ -383,9 +383,18 @@ async function onShellDownload() {
|
||||
if (downloading.value) return
|
||||
downloading.value = true
|
||||
shellDismissed.value = false
|
||||
// 点击即进入"下载中"反馈(不等轮询):内网直连下载很快,若靠 15s 轮询拉状态,
|
||||
// 进度条可能还没显示就已经下载完,用户会以为点了没反应
|
||||
const v = shellUpdate.value.latest || ''
|
||||
shellUpdate.value = { ...shellUpdate.value,
|
||||
dl: { status: 'downloading', version: v, received: 0, total: 0, pct: 0, error: '' } }
|
||||
lastDlStatus = 'downloading' // 兜底:即使立即下载完成,也能触发"已就绪"一次性提示
|
||||
try {
|
||||
await downloadShellUpdate() // 后端后台流式下载,进度经轮询展示
|
||||
try { shellUpdate.value = await getShellStatus() } catch (_) {} // 抢拉真实进度,避免卡在 0%
|
||||
} catch (e) {
|
||||
shellUpdate.value = { ...shellUpdate.value,
|
||||
dl: { status: 'failed', version: v, received: 0, total: 0, pct: 0, error: (e.message || e) } }
|
||||
ElMessage.error('开始下载失败:' + (e.message || e))
|
||||
}
|
||||
downloading.value = false
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 37du 自动化工作台 - Inno Setup 安装脚本 (Inno Setup 7)
|
||||
; 编译: "C:\Program Files\Inno Setup 7\ISCC.exe" webhost\tools\install.iss
|
||||
; 打包内容: 主程序 37du-host.exe + 插件执行壳 37du-host-runner.exe + .env 默认配置
|
||||
; .env 与 webhost/.env 同源(控制面/平台共享配置):仅首次安装写入(onlyifdoesntexist),
|
||||
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
|
||||
|
||||
#define MyAppName "37du 自动化工作台"
|
||||
#define MyAppVersion "1.1.3"
|
||||
#define MyAppVersion "1.1.7"
|
||||
#define MyAppExeName "37du-host.exe"
|
||||
|
||||
[Setup]
|
||||
|
||||
@@ -1 +1 @@
|
||||
1.1.3
|
||||
1.1.7
|
||||
Reference in New Issue
Block a user