refactor: 重构执行机架构为 Electron 壳内置 Python 运行时子集

将原 webhost 底座的后端、前端、工具等代码迁移至 electron-shell 目录,构建自包含的 Python 环境包,移除冗余的前端代码、旧的后端模块及相关依赖,更新版本号至 1.0.6,优化平台登录态预检逻辑,统一代码结构为单一真源,避免多副本维护问题。
This commit is contained in:
2026-10-05 14:13:47 +08:00
parent 23e8082511
commit 71f18a4d22
173 changed files with 147 additions and 29432 deletions
@@ -0,0 +1,5 @@
# -*- coding: utf-8 -*-
"""webhost 后端领域逻辑核心(core)包。
鉴权/会话/调度/执行/控制面集成/单活/Job 托管等实现模块集合。
"""
@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*-
"""平台登录态管理(webhost 宿主壳 · 复用 desktop/shared 单一真源)
- cookies 与 desktop/影刀版共用同一份共享文件(%LOCALAPPDATA%\37duAutomation\.sessions),
任一端登录成功后,webhost 直接复用,无需重复登录
- is_online():真实校验(轻量 API 校验 cookies 有效性),不是内存假状态
- login():真实登录(cookies 有效则秒级复用;失效则浏览器自动化滑块登录)
- build_session():从共享 cookies 构建 requests.Session,供插件直接调用 shared 数据模块
约定:webhost 只依赖 desktop/shared 的真源登录模块,不复制登录逻辑。
"""
from __future__ import annotations
import json
import os
import requests
from webhost.backend.shared import hr_login as _hr
from webhost.backend.shared import oa_login as _oa
from webhost.backend.shared import seal_data_export as _seal
_LABELS = {"hr": "HR 系统", "oa": "OA 系统"}
# 共享 cookies:与 desktop/shared 版本使用同一份文件,路径约定保持一致
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
# 按账号隔离会话目录:PLATFORM_ACCOUNT 指定当前登录账号(壳/插件由执行机注入),
# 未设置时沿用共享目录(兼容旧逻辑)
_ACCOUNT = os.getenv('PLATFORM_ACCOUNT', '').strip()
if _ACCOUNT:
_SESSIONS_DIR = os.path.join(_SESSIONS_DIR, _ACCOUNT)
# 各平台 cookie 文件与域名(构建 session 时按域过滤)
_COOKIE_DEFS = {
"hr": {"file": "hr_cookies.json", "domain": "hr.37du.co"},
"oa": {"file": "oa_cookies.json", "domain": "oa.37du.co"},
}
# 登录模块(desktop/shared 真源)
_LOGIN_MODS = {"hr": _hr, "oa": _oa}
class PlatformAuthError(Exception):
"""平台不存在 / 登录态不可用等宿主层错误。"""
def platforms() -> list:
return [{"id": pid, "label": label} for pid, label in _LABELS.items()]
def is_online(pid: str) -> bool:
"""真实校验平台登录态(发起轻量 API 校验,非内存假状态)。"""
if pid == "hr":
return _hr._is_hr_session_valid()
if pid == "oa":
return _oa._is_oa_session_valid()
return False
def login(pid: str) -> dict:
"""真实登录:cookies 有效则复用(不弹浏览器),失效则浏览器自动化登录。
返回 {id, label, online, message}
"""
if pid not in _LOGIN_MODS:
raise PlatformAuthError(f"未知平台: {pid}")
result = _LOGIN_MODS[pid].ensure_login(force=False)
ok = bool(result and result.get("success"))
return {"id": pid, "label": _LABELS[pid], "online": ok,
"message": (result or {}).get("message", "")}
def logout(pid: str) -> dict:
"""登出平台:删除共享 cookies 文件,使该平台登录态失效。
返回 {id, label, online}
"""
if pid not in _COOKIE_DEFS:
raise PlatformAuthError(f"未知平台: {pid}")
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
if os.path.exists(path):
os.remove(path)
return {"id": pid, "label": _LABELS[pid], "online": False}
def build_session(pid: str) -> "requests.Session":
"""从共享 cookies 构建已登录 requests.Session(供插件调用 shared 数据模块)。
若登录态缺失则抛 PlatformAuthError,提示先登录。
"""
if pid not in _COOKIE_DEFS:
raise PlatformAuthError(f"未知平台: {pid}")
path = os.path.join(_SESSIONS_DIR, _COOKIE_DEFS[pid]["file"])
if not os.path.exists(path):
raise PlatformAuthError(
f"未找到 {_LABELS[pid]} 登录态({path}),请先在页面点击登录")
with open(path, encoding="utf-8") as f:
cookies = json.load(f)
if not cookies:
raise PlatformAuthError(f"{_LABELS[pid]} 登录态为空,请重新登录")
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
})
domain = _COOKIE_DEFS[pid]["domain"]
injected: set = set()
for c in cookies:
if c.get("domain") and domain in c["domain"]:
session.cookies.set(c["name"], c["value"],
domain=c["domain"], path=c.get("path", "/"))
injected.add(c["name"])
# 兜底:domain 未命中目标域名的 cookie(如别名域名),且 name 尚未注入时,
# 按目标域名补注入,避免漏掉关键 cookie 导致接口鉴权失败。
for c in cookies:
name = c.get("name")
if name and name not in injected:
session.cookies.set(name, c.get("value", ""),
domain=domain, path=c.get("path", "/"))
return session
def get_user_id(pid: str) -> str:
"""获取平台用户 ID(HR 数据接口大多需要 user_id 参数)。"""
if pid == "hr":
session = build_session("hr")
info = _seal.fetch_cur_user_info(session)
return str(info.get("userId") or "")
raise PlatformAuthError(f"平台 {pid} 暂不支持取 user_id")
@@ -0,0 +1,128 @@
# -*- 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())
@@ -0,0 +1,112 @@
# -*- 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())
@@ -0,0 +1,99 @@
# -*- coding: utf-8 -*-
"""Windows Job Object 封装:插件执行子进程整树托管。
- KILL_ON_JOB_CLOSE:句柄关闭/宿主崩溃时,作业内全部进程(含 DrissionPage 拉起的
浏览器等孙进程)一并终止,杜绝超时强杀后残留孤儿进程;
- PROCESS_MEMORY_LIMIT:作业级内存上限兜底,防插件内存爬升拖垮底座。
非 Windows 平台所有方法安全降级为 no-op。
"""
from __future__ import annotations
import ctypes
import logging
import sys
_LOGGER = logging.getLogger(__name__)
_AVAILABLE = sys.platform == "win32"
if _AVAILABLE:
try:
_K32 = ctypes.WinDLL("kernel32", use_last_error=True)
except AttributeError: # 非 Windows 误导入
_AVAILABLE = False
_JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
_JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x0000_2000
_JOB_OBJECT_LIMIT_PROCESS_MEMORY = 0x0000_0100
_PROCESS_SET_QUOTA = 0x0100
_PROCESS_TERMINATE = 0x0001
if _AVAILABLE:
class _IO_COUNTERS(ctypes.Structure):
_fields_ = [(n, ctypes.c_uint64) for n in (
"ReadOperationCount", "WriteOperationCount", "OtherOperationCount",
"ReadTransferCount", "WriteTransferCount", "OtherTransferCount")]
class _BASIC_LIMIT_INFO(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_int64),
("PerJobUserTimeLimit", ctypes.c_int64),
("LimitFlags", ctypes.c_uint32),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", ctypes.c_uint32),
("Affinity", ctypes.c_size_t),
("PriorityClass", ctypes.c_uint32),
("SchedulingClass", ctypes.c_uint32),
]
class _EXT_LIMIT_INFO(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", _BASIC_LIMIT_INFO),
("IoInfo", _IO_COUNTERS),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
class Job:
"""一次性的插件子进程作业。用法:job = Job(); job.assign(proc); …; job.terminate()/close()。"""
def __init__(self, max_mem_mb: int = 0):
self._h = None
if not _AVAILABLE:
return
h = _K32.CreateJobObjectW(None, None)
if not h:
_LOGGER.warning("创建 Job Object 失败(winerror=%s),退化为无作业托管", ctypes.get_last_error())
return
info = _EXT_LIMIT_INFO()
info.BasicLimitInformation.LimitFlags = _JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
if max_mem_mb > 0:
info.BasicLimitInformation.LimitFlags |= _JOB_OBJECT_LIMIT_PROCESS_MEMORY
info.ProcessMemoryLimit = max_mem_mb * 1024 * 1024
if not _K32.SetInformationJobObject(
h, _JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
ctypes.byref(info), ctypes.sizeof(info)):
_LOGGER.warning("设置 Job Object 限制失败(winerror=%s)", ctypes.get_last_error())
self._h = h
def assign(self, proc) -> None:
"""把子进程(及其后代)纳入作业托管。"""
if not self._h:
return
if not _K32.AssignProcessToJobObject(self._h, int(proc._handle)):
_LOGGER.warning("子进程纳入 Job Object 失败(winerror=%s)", ctypes.get_last_error())
def terminate(self, exit_code: int = 1) -> None:
"""终止作业内全部进程(整树强杀,含浏览器等孙进程)。"""
if self._h:
_K32.TerminateJobObject(self._h, exit_code)
def close(self) -> None:
"""关闭作业句柄;KILL_ON_JOB_CLOSE 保证句柄消失后作业内进程全部退出。"""
if self._h:
_K32.CloseHandle(self._h)
self._h = None