# -*- 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 = {} 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) try: proc = subprocess.Popen( cmd, cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace", ) job.assign(proc) 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 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: _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)