Files
37duAutomation/desktop/webhost/backend/core/plugin_runner.py
T
puddy a649a938e6 release: bump version to 1.1.7, update xq0031_xq0032 plugin to 1.0.8
主要变更:
1. 整体版本升级至1.1.7,更新安装包与shell版本号
2. 新增API与后端能力:
   - 新增停止运行接口,支持强制终止插件进程与浏览器子进程
   - 云端会话令牌与下载票据落库,适配多worker部署
   - 优化Chrome版本读取逻辑,避免弹窗与编码问题
3. xq0031_xq0032插件升级至1.0.8:
   - 新增仓库中文名自动筛选功能,简化用户操作
   - 优化ERP登录与报表导出流程,修复标签页残留问题
   - 新增前端强制停止按钮,支持实时终止运行
   - 修复中文编码与乱码问题,兼容Windows非UTF-8环境
4. 修复授权校验逻辑,确保账号与授权匹配
5. 更新文档与部署脚本,修正发版流程说明
2026-09-17 23:25:33 +08:00

112 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 -*-
"""插件执行子进程入口(进程级隔离)。
由底座 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.buffer,显式 UTF-8 字节)。
插件 print 已改道 stderr,不污染协议;不走文本层是避免 Windows GBK 环境下
stdout 按 locale 编码导致中文变 mojibake(父进程按 UTF-8 解码会对不上)。"""
try:
_PROTO.buffer.write((json.dumps(obj, ensure_ascii=False) + "\n").encode("utf-8"))
_PROTO.buffer.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,UTF-8 字节):显式走 buffer 按 UTF-8 解,
# 不依赖 sys.stdin 的 locale 解码(Windows GBK 环境下中文会被解出乱码/孤立代理字符,
# 导致 fields 值与插件内字符串常量比对失败,如「未知执行模式」)
fields: dict = {}
try:
_raw = sys.stdin.buffer.readline().strip()
if _raw:
fields = json.loads(_raw) 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())