# -*- 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 import uuid 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 = {} def submit_run(account: str, plugin, fields: dict) -> str: """启动一次插件运行(手动 POST /api/runs 与定时任务共用入口)。 - 登记运行记录 + 广播 run_start + 上报 start; - 后台线程执行:命名空间并发闸(同平台串行)→ 设备级单活(排队等待当前插件结束) → 拉起执行子进程;启动失败回滚单活槽位并广播 run_done(error)。 返回 run_id。 """ run_id = uuid.uuid4().hex with _st.RUN_LOCK: if len(_st.RUNS) >= _st.MAX_RUNS: _st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录 _st.RUNS[run_id] = {"status": "running", "account": account, "version": getattr(plugin, "version", "0"), "started": time.time(), "result": None, "error": None} HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id, "at": datetime.now().strftime("%H:%M:%S")}) licensing.report(account=account, device_id="", plugin_id=plugin.id, version=getattr(plugin, "version", "0"), status="start") def _queued(): # 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢 gate = _st._ns_gate(plugin.platform) if gate.locked(): HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id, "level": "INFO", "msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"}) with gate: # 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前 if _scheduler._is_busy(): HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id, "level": "INFO", "msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"}) def _start(): if _is_user_stopped(run_id): # 排队期间用户已点停止:不真正拉起插件,抛异常让 request_start 回滚单活槽位, # 由下方 !ok 分支把 run 落为"用户手动强制停止",避免"看似取消实际还在跑"。 raise RuntimeError("用户已取消该排队任务") threading.Thread(target=_run_target, args=(plugin, fields, run_id), daemon=True, name=f"exec-{plugin.id}").start() return run_id r = _scheduler.request_start(account, plugin.id, getattr(plugin, "version", "0"), _start) if not r.get("ok"): # 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待 err = r.get("error") or "启动失败" if _is_user_stopped(run_id): err = "用户手动强制停止" with _STOP_LOCK: _USER_STOPPED.discard(run_id) _st._set_run(run_id, status="error", result=None, error=err) HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": err}) threading.Thread(target=_queued, daemon=True, name=f"run-{plugin.id}").start() return run_id # ==================== 手动强制停止 ==================== # 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)