Files
37duAutomation/desktop/webhost/backend/core/plugin_runner.py
T
puddy 1e533dd1b3 refactor: 完成项目目录重构与代码迁移
本次提交完成了整体项目的目录梳理与代码迁移:
1.  将根级controlplane、webhost等目录的代码迁移至desktop/对应子目录,统一桌面端架构
2.  移动并整理了插件目录结构,将插件统一放入根级plugins/
3.  调整了前端项目的路径与配置,统一前后端开发构建流程
4.  清理了废弃的旧版app/目录与冗余的构建中间文件
5.  更新了.gitignore与README.md,适配新的项目结构
2026-09-14 17:46:09 +08:00

108 lines
4.0 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 -*-
"""插件执行子进程入口(进程级隔离)。
由底座 main 以 `python -m webhost.backend.core.plugin_runner --plugin <id>` 拉起,
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
- get_session / get_user_id 在本进程内直接读取共享 cookie 文件重建,不依赖主进程
"""
from __future__ import annotations
import json
import os
import sys
def _bootstrap_paths() -> str:
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
if getattr(sys, "frozen", False):
root = os.path.dirname(os.path.abspath(sys.executable)) # 打包运行:exe 同级目录
os.chdir(root)
return root
root = os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__))))) # core/plugin_runner.py → 项目根
if root not in sys.path:
sys.path.insert(0, root)
return root
_ROOT = _bootstrap_paths()
try:
os.chdir(_ROOT)
except OSError:
pass
def _emit(obj: dict) -> None:
"""写一行 JSON 到协议通道(原始 stdout)。插件 print 已改道 stderr,不污染协议。"""
try:
_PROTO.write(json.dumps(obj, ensure_ascii=False) + "\n")
_PROTO.flush()
except Exception: # noqa: BLE001 通道已关则静默
pass
def _run() -> int:
# 协议通道 = 原始 sys.stdout(fd1);把插件的 print 改道到 stderr,防止污染协议行
global _PROTO
_PROTO = sys.stdout
sys.stdout = sys.stderr
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
from webhost.backend.plugins.base import RunContext
from webhost.backend.core import auth as platform_auth
# 解析参数
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
plugin_id = args.get("--plugin") or (sys.argv[sys.argv.index("--plugin") + 1]
if "--plugin" in sys.argv else "")
if not plugin_id:
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
return 2
# 宿主透传的插件白名单:与宿主进程加载集保持一致(未传 = 全量)
allowed_arg = (sys.argv[sys.argv.index("--allowed") + 1]
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: dict = {}
try:
_line = sys.stdin.readline().strip()
if _line:
fields = json.loads(_line) or {}
except Exception as _e: # noqa: BLE001
fields = {}
class _ChildContext(RunContext):
"""子进程版上下文:log/progress 经 stdout 回传;登录态在本进程重建。"""
def __init__(self, run_id: str, plugin_id: str, auth):
super().__init__(hub=None, run_id=run_id, plugin_id=plugin_id, auth=auth)
def log(self, msg: str, level: str = "INFO"):
_emit({"ev": "log", "level": level, "msg": str(msg)})
def progress(self, pct: int):
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
try:
load_plugins(allowed)
plugin = PLUGINS.find(plugin_id)
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
auth=platform_auth)
result = plugin.run(fields, ctx)
_emit({"ev": "result", "ok": True, "result": result})
return 0
except KeyError:
_emit({"ev": "result", "ok": False, "error": f"插件未找到: {plugin_id}"})
return 3
except Exception as _e: # noqa: BLE001 插件顶层兜底
import traceback
traceback.print_exc()
_emit({"ev": "result", "ok": False, "error": str(_e)})
return 1
if __name__ == "__main__":
raise SystemExit(_run())