Files
37duAutomation/webhost/backend/plugin_runner.py
T
puddy 7722939d9a feat: 搭建控制面管理前端并剥离底座管理功能
1. 新增controlplane/frontend Vue3管理前端,实现登录、账号CRUD、插件上传/管理、权限授权
2. 为controlplane/app.py添加CORS中间件并挂载前端静态产物
3. 重构环境变量加载,统一使用app/common/env.load_app_env()
4. 剥离webhost/的管理UI与代理接口,仅保留基础登录能力
5. 新增环境隔离规范文档与架构蓝图说明
2026-09-09 17:10:12 +08:00

99 lines
3.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 -*-
"""插件执行子进程入口(进程级隔离)。
由底座 main 以 `python -m webhost.backend.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。"""
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
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 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
# 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()
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())