Files
37duAutomation/desktop/webhost/backend/core/job_guard.py
T

129 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""环境包版插件执行守护:Job Object 托管 + 内存上限 + 超时强杀。
Node 壳(electron-shell runner.js)在**便携环境包**模式下不再直接 spawn
plugin_runner,而是经由本守护拉起,以获得旧 Python 底座同等的进程托管能力:
python job_guard.py [--mem <MB>] [--timeout <秒>] -- <python> -u <plugin_runner.py> [args...]
- Job Object(KILL_ON_JOB_CLOSE + PROCESS_MEMORY_LIMIT,复用 winjob.py)
→ 插件及其拉起的浏览器孙进程整体托管,内存超限/超时/宿主退出即整树终止;
- stdin/stdout/stderr 三通道逐字节透传(plugin_runner 协议不经过本进程改写,
与 Node 直接 spawn 时逐字节一致:fields 单行 JSON → 事件行/诊断行);
- 退出码 = 子进程退出码(透传),Node 侧结论判定逻辑不变;
- 非 Windows 平台安全降级为直接 spawn 子进程(winjob 内部 no-op)。
本文件同时进入环境包运行时子集(webhost/backend/core/job_guard.py),
不依赖任何第三方包(ctypes 标准库实现)。
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import threading
import time
try:
from webhost.backend.core import winjob # 环境包/仓库内相对解析
except Exception: # noqa: BLE001 兜底:直接同目录导入
import winjob
def _forward(src, dst, name: str) -> None:
"""把 src 的字节流逐块转发到 dst;EOF 后 flush 并结束。"""
try:
while True:
chunk = src.read(65536)
if not chunk:
break
dst.write(chunk)
dst.flush()
except Exception: # noqa: BLE001 通道关闭即结束
pass
finally:
try:
dst.flush()
except Exception: # noqa: BLE001
pass
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="37du 插件执行守护(Job Object 托管)")
parser.add_argument("--mem", type=int, default=0, help="作业级内存上限(MB),0=不限")
parser.add_argument("--timeout", type=int, default=0, help="超时秒数,0=不限(Node 侧仍有兜底强杀)")
parser.add_argument("child", nargs=argparse.REMAINDER, help="-- 之后为真实子进程命令")
args = parser.parse_args(argv)
if not args.child or args.child[0] != "--":
print("用法:python job_guard.py [--mem MB] [--timeout 秒] -- <cmd...>", file=sys.stderr)
return 2
child_cmd = args.child[1:]
if not child_cmd:
print("缺少子进程命令", file=sys.stderr)
return 2
# 透传环境(宿主注入的 PLUGINS_ROOT / PLATFORM_ACCOUNT 等原样继承)
env = dict(os.environ)
# 1) 子进程:stdin/stdout/stderr 直接对接父进程(Node 侧),协议零改写
try:
child = subprocess.Popen(
child_cmd,
stdin=sys.stdin.buffer,
stdout=sys.stdout.buffer,
stderr=sys.stderr.buffer,
cwd=os.getcwd(),
env=env,
bufsize=0,
)
except OSError as e:
print(f"拉起子进程失败: {e}", file=sys.stderr)
return 127
# 2) Job Object 托管(Windows):整树终止 + 内存上限
job = winjob.Job(max_mem_mb=int(args.mem or 0))
try:
job.assign(child)
except Exception: # noqa: BLE001
pass
# 3) 超时守护(兜底;Node 侧 taskkill 仍作为第二道防线)
timed_out = {"v": False}
def _kill_on_timeout() -> None:
time.sleep(max(1, int(args.timeout or 0)))
timed_out["v"] = True
try:
job.terminate(1)
except Exception: # noqa: BLE001
try:
child.kill()
except Exception: # noqa: BLE001
pass
timer = None
if int(args.timeout or 0) > 0:
timer = threading.Thread(target=_kill_on_timeout, daemon=True)
timer.start()
# 4) 等子进程结束(进程退出/超时终止均在此返回);子进程自身已接管三通道
try:
code = child.wait()
except KeyboardInterrupt:
job.terminate(1)
try:
code = child.wait(timeout=5)
except Exception: # noqa: BLE001
code = 1
job.close()
if timed_out["v"]:
print(f"[job_guard] 插件执行超时({args.timeout}s)已强制终止", file=sys.stderr)
return int(code) if code is not None else 1
if __name__ == "__main__":
raise SystemExit(main())