主要变更: 1. 整体版本升级至1.1.7,更新安装包与shell版本号 2. 新增API与后端能力: - 新增停止运行接口,支持强制终止插件进程与浏览器子进程 - 云端会话令牌与下载票据落库,适配多worker部署 - 优化Chrome版本读取逻辑,避免弹窗与编码问题 3. xq0031_xq0032插件升级至1.0.8: - 新增仓库中文名自动筛选功能,简化用户操作 - 优化ERP登录与报表导出流程,修复标签页残留问题 - 新增前端强制停止按钮,支持实时终止运行 - 修复中文编码与乱码问题,兼容Windows非UTF-8环境 4. 修复授权校验逻辑,确保账号与授权匹配 5. 更新文档与部署脚本,修正发版流程说明
209 lines
8.5 KiB
Python
209 lines
8.5 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""webhost 宿主 run 执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
|
||
|
||
进程级隔离:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀;
|
||
由 Windows Job Object 整树托管(含浏览器孙进程)。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import logging
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
from datetime import datetime
|
||
from pathlib import Path
|
||
|
||
from pydantic import BaseModel
|
||
|
||
from webhost.backend.core import scheduler as _scheduler
|
||
from webhost.backend.core import winjob as _winjob
|
||
from webhost.backend.core import licensing
|
||
from webhost.backend.core import state as _st
|
||
from webhost.backend.core.hub import HUB
|
||
|
||
_LOGGER = logging.getLogger(__name__)
|
||
|
||
|
||
class RunReq(BaseModel):
|
||
plugin_id: str
|
||
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,超时强杀。
|
||
|
||
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
|
||
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
|
||
"""
|
||
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
|
||
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
|
||
|
||
# 打包运行(frozen):拉起同级 37du-host-runner.exe(console 壳,内置同一套执行代码)
|
||
if getattr(sys, "frozen", False):
|
||
runner_exe = Path(sys.executable).with_name("37du-host-runner.exe")
|
||
cmd = [str(runner_exe), "--plugin", plugin.id, "--run", run_id]
|
||
root = Path(sys.executable).resolve().parent
|
||
else:
|
||
runner = Path(__file__).with_name("plugin_runner.py")
|
||
root = Path(__file__).resolve().parents[3] # core/runner.py → 项目根
|
||
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
|
||
if _st.ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||
cmd += ["--allowed", ",".join(sorted(_st.ALLOWED))]
|
||
|
||
# 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", 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}")
|
||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||
"error": f"拉起执行子进程失败: {e}"})
|
||
return
|
||
|
||
def _publish_event(ev: dict):
|
||
t = ev.get("ev")
|
||
if t == "log":
|
||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
|
||
elif t == "progress":
|
||
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
|
||
"pct": int(ev.get("pct", 0))})
|
||
|
||
_result: dict = {}
|
||
_rlock = threading.Lock()
|
||
|
||
def _drain_out():
|
||
for line in proc.stdout:
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
ev = json.loads(line)
|
||
except ValueError:
|
||
continue
|
||
if ev.get("ev") in ("log", "progress"):
|
||
_publish_event(ev)
|
||
elif ev.get("ev") == "result":
|
||
with _rlock:
|
||
_result.update(ev)
|
||
|
||
def _drain_err():
|
||
for line in proc.stderr:
|
||
line = line.strip()
|
||
if line:
|
||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||
"level": "ERROR", "msg": line})
|
||
|
||
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
|
||
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
|
||
t_out.start(); t_err.start()
|
||
|
||
try:
|
||
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
|
||
proc.stdin.close()
|
||
except OSError:
|
||
pass
|
||
|
||
timed_out = False
|
||
try:
|
||
proc.wait(timeout=timeout)
|
||
except subprocess.TimeoutExpired:
|
||
timed_out = True
|
||
try:
|
||
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
|
||
proc.wait(timeout=5)
|
||
except (subprocess.TimeoutExpired, OSError):
|
||
pass
|
||
|
||
try:
|
||
with _rlock:
|
||
ev = dict(_result)
|
||
if ev:
|
||
ok = bool(ev.get("ok"))
|
||
_st._set_run(run_id, status="done" if ok else "error",
|
||
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)
|
||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
|
||
else:
|
||
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
|
||
_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 兜底清理残留子进程
|
||
|
||
|
||
def _report_run(plugin_id: str, run_id: str) -> None:
|
||
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
|
||
try:
|
||
with _st.RUN_LOCK:
|
||
run = _st.RUNS.get(run_id) or {}
|
||
account = run.get("account", "")
|
||
status = "done" if run.get("status") == "done" else \
|
||
("running" if run.get("status") == "running" else "error")
|
||
msg = run.get("error") or ""
|
||
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
|
||
licensing.report(account=account, device_id="",
|
||
plugin_id=plugin_id, version=run.get("version", ""),
|
||
status=status, msg=msg, duration_sec=duration)
|
||
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
|
||
_LOGGER.warning("运行上报失败:%s", _exc) |