refactor: 重构项目目录结构与代码组织

1.  重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包
2.  移动并整理工具脚本到tools子目录,统一管理运维脚本
3.  重构插件运行时、调度、作业管理等核心模块到core子包
4.  更新AGENTS.md文档,明确各代码形态的组织规范
5.  清理重复的旧文件与冗余代码
This commit is contained in:
2026-09-14 12:34:54 +08:00
parent b86bc1bf97
commit a1a06504a5
46 changed files with 3107 additions and 2647 deletions
+5
View File
@@ -0,0 +1,5 @@
# -*- coding: utf-8 -*-
"""webhost 后端领域逻辑核心(core)包。
鉴权/会话/调度/执行/控制面集成/单活/Job 托管等实现模块集合。
"""
+128
View File
@@ -0,0 +1,128 @@
# -*- 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')
# 各平台 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")
+49
View File
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
"""webhost 宿主配置固化:加载本模块 env(webhost/.env) 并输出全部环境常量与路径。
依赖方向:config ← 所有领域逻辑与路由模块(只读,不含业务逻辑)。
"""
from __future__ import annotations
import logging
import os
from pathlib import Path
_LOGGER = logging.getLogger(__name__)
# 部署底座路径根:webhost/(__file__ 位于 webhost/backend/config.py,parents[1]=webhost)
_HOST_ROOT = Path(__file__).resolve().parents[1]
PORT = 8799
DIST = _HOST_ROOT / "frontend" / "dist"
def _load_dotenv() -> None:
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
env_path = _HOST_ROOT / ".env"
if not env_path.is_file():
return
try:
for _ln in env_path.read_text(encoding="utf-8").splitlines():
_line = _ln.strip()
if not _line or _line.startswith("#") or "=" not in _line:
continue
_k, _v = _line.split("=", 1)
_k, _v = _k.strip(), _v.strip()
if _k and _k not in os.environ:
os.environ[_k] = _v
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("读取 .env 失败: %s", _exc)
_load_dotenv()
# ==================== 插件权限源(阶段二:控制面接口;默认全量兜底) ====================
PLUGIN_SOURCE = os.getenv("PLUGIN_SOURCE", "all") # all | controlplane
CONTROLPLANE_URL = os.getenv("CONTROLPLANE_URL", "").rstrip("/")
CONTROLPLANE_ACCOUNT = os.getenv("CONTROLPLANE_ACCOUNT", "")
CONTROLPLANE_TOKEN = os.getenv("CONTROLPLANE_TOKEN", "")
# 钉钉扫码登录(可选):配置了钉钉开放平台应用后前端显示扫码入口。
# 未配置时仅保留账号+密码登录。真实扫码 OAuth 在中心机换取工号/姓名后走 /api/admin/dingtalk/login。
# 兼容旧配置名 DINGTALK_APPKEY:任一名非空即视为已启用扫码。
DINGTALK_APP_KEY = os.getenv("DINGTALK_APP_KEY", "") or os.getenv("DINGTALK_APPKEY", "")
+85
View File
@@ -0,0 +1,85 @@
# -*- coding: utf-8 -*-
"""webhost 宿主 ↔ 中心机(统一后端) 集成:权限白名单解析 + 数据库 API 代理 + 离线授权同步。
底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
"""
from __future__ import annotations
import logging
from fastapi import HTTPException, Request
from webhost.backend.core import licensing
from webhost.backend.core import config
from webhost.backend.core.session import _sess_account
_LOGGER = logging.getLogger(__name__)
def _resolve_allowed() -> set | None:
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
if config.PLUGIN_SOURCE != "controlplane" or not config.CONTROLPLANE_URL:
return None
if not config.CONTROLPLANE_ACCOUNT:
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
return None
import requests
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
try:
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
params={"account": config.CONTROLPLANE_ACCOUNT},
headers=headers, timeout=5)
r.raise_for_status()
allowed = {p["id"] for p in r.json().get("plugins", [])}
_LOGGER.info("控制面权限清单(%s):%s", config.CONTROLPLANE_ACCOUNT,
sorted(allowed) or "(空)")
return allowed
except Exception as _exc: # noqa: BLE001
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
return None
def _cp_headers(request: Request) -> dict:
h = {"X-Admin-User": _sess_account(request)}
if config.CONTROLPLANE_TOKEN:
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
return h
def _cp_call(method: str, path: str, **kw) -> dict:
if not config.CONTROLPLANE_URL:
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
import requests
r = requests.request(method, f"{config.CONTROLPLANE_URL}{path}", timeout=30, **kw)
try:
body = r.json()
except ValueError:
body = {"detail": r.text[:300]}
if r.status_code >= 400:
raise HTTPException(r.status_code, body.get("detail", f"统一后端 {r.status_code}"))
return body
def _sync_licensing(account: str) -> None:
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
"""
if not config.CONTROLPLANE_URL or not account:
return
import requests
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/pubkey", headers=headers, timeout=5)
r.raise_for_status()
licensing.cache_public_key(r.json().get("pub", ""))
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/license",
params={"account": account}, headers=headers, timeout=5)
r.raise_for_status()
licensing.save_license(r.json())
r = requests.get(f"{config.CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
r.raise_for_status()
licensing.save_control(r.json())
licensing.flush_offline_reports()
+47
View File
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
"""WebSocket 广播枢纽:把插件 run 线程产生的 日志/进度/完成 事件实时推给前端。
run 在 worker 线程执行,publish 通过 run_coroutine_threadsafe 投递到主事件循环。
"""
from __future__ import annotations
import asyncio
import threading
from typing import Dict
class Hub:
def __init__(self):
self._loop: asyncio.AbstractEventLoop | None = None
self._clients: list = []
self._lock = threading.Lock()
def bind(self, loop: asyncio.AbstractEventLoop):
self._loop = loop
async def connect(self, websocket) -> None:
await websocket.accept()
with self._lock:
self._clients.append(websocket)
try:
await websocket.receive_text() # 挂起直到客户端断开
finally:
with self._lock:
self._clients.remove(websocket)
def publish(self, event: Dict) -> None:
if self._loop is None:
return
asyncio.run_coroutine_threadsafe(self._send(event), self._loop)
async def _send(self, event: Dict) -> None:
with self._lock:
clients = list(self._clients)
for ws in clients:
try:
await ws.send_json(event)
except Exception:
with self._lock:
self._clients.remove(ws)
HUB = Hub()
+283
View File
@@ -0,0 +1,283 @@
# -*- coding: utf-8 -*-
"""部署端产品化能力层:离线授权/管控清单缓存、中心机公钥缓存、联网判定、验签、运行上报。
职责(对应架构设计七、八节):
- 以 %LOCALAPPDATA%\\37duAutomation 为根,缓存:
license.json (离线授权票据,Ed25519 签名,离线一直有效)
control.json (管控清单缓存:revoked/disabled/forcedUpdates + updatedAt)
keys\\pub.pem (中心机公钥,首次联网拉取缓存,供离线验签)
- is_online() —— 收敛的单一联网判定:最近一次成功拉取/心跳时间戳 + 失败二次确认。
离线只豁免「强制更新 deadline」,票据验签/授权/下架禁用离线仍生效。
- verify_license() / verify_control() —— 用缓存公钥离线验签。
- report() —— 运行上报到中心机(联网时实时上报;离线记录暂存,重连后补报)。
"""
from __future__ import annotations
import base64
import json
import logging
import os
import time
from datetime import datetime
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
_LOGGER = logging.getLogger(__name__)
# 数据根目录:与影刀版共享 %LOCALAPPDATA%\37duAutomation
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
or Path.home(), "37duAutomation")
KEYS_DIR = _APP_DATA / "keys"
license_path = _APP_DATA / "license.json"
control_path = _APP_DATA / "control.json"
reports_path = _APP_DATA / "offline_reports.jsonl" # 离线上报暂存,重连后补报
# 联网判定阈值:超过此秒数未成功拉取/心跳即视为离线
_ONLINE_TTL = 180
_last_sync = 0.0
_sync_lock = None # 由 import 后注入 threading.Lock(避免循环依赖按模块初始化)
_CONTROLPLANE_URL = "" # 由 main.py 注入
def init(controlplane_url: str, sync_lock) -> None:
"""注入控制面地址与同步锁(main.py 启动时调用)。"""
global _CONTROLPLANE_URL, _sync_lock
_CONTROLPLANE_URL = (controlplane_url or "").rstrip("/")
_sync_lock = sync_lock
_APP_DATA.mkdir(exist_ok=True)
KEYS_DIR.mkdir(exist_ok=True)
# ==================== 联网判定 ====================
def touch_sync() -> None:
"""标记最近一次与控制面成功同步的时点(拉票/清单/心跳成功后调用)。"""
global _last_sync
with _sync_lock:
_last_sync = time.time()
def is_online() -> bool:
"""收敛的单一联网判定:默认联网(无缓存/从未同步视联网),最大 _ONLINE_TTL 未同步判离线。"""
with _sync_lock:
return (time.time() - _last_sync) <= _ONLINE_TTL
# ==================== 公钥缓存与验签 ====================
def _pub_pem_path() -> Path:
return KEYS_DIR / "pub.pem"
def cache_public_key(pem_text: str) -> None:
"""缓存中心机公钥(首次联网拉取)。用于后续离线验签。"""
pem_text = (pem_text or "").strip()
if not pem_text:
return
_pub_pem_path().write_text(pem_text, encoding="ascii")
touch_sync()
def _load_public_key() -> Ed25519PublicKey | None:
try:
return serialization.load_pem_public_key(_pub_pem_path().read_bytes())
except Exception: # noqa: BLE001 无缓存/损坏视为无公钥
return None
def _verify_blob(blob: str, pub: Ed25519PublicKey) -> dict:
"""验签返回 payload;签名非法抛 ValueError。"""
if "." not in blob:
raise ValueError("bad blob")
b64, sig64 = blob.rsplit(".", 1)
canon = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4))
sig = base64.urlsafe_b64decode(sig64 + "=" * (-len(sig64) % 4))
if len(sig) != 64:
raise ValueError("bad signature len")
pub.verify(sig, canon)
return json.loads(canon)
def verify_license() -> dict:
"""验签本地缓存授权票据,返回 payload;无缓存/验签失败抛异常。"""
if not license_path.is_file():
raise ValueError("无本地授权票据(license.json)")
pub = _load_public_key()
if pub is None:
raise ValueError("缺少中心机公钥,无法验签授权票据")
data = json.loads(license_path.read_text(encoding="utf-8"))
return _verify_blob(data["ticket"], pub)
def verify_control() -> dict:
"""验签本地缓存管控清单,返回 payload;无缓存时返回空管控(不禁止任何插件)。"""
if not control_path.is_file():
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
pub = _load_public_key()
if pub is None:
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
try:
data = json.loads(control_path.read_text(encoding="utf-8"))
payload = _verify_blob(data["ticket"], pub)
return payload if isinstance(payload, dict) else {}
except Exception: # noqa: BLE001 缓存损坏按"不禁止"兜底,联网后会重新拉取
return {"revokedPlugins": [], "disabledPlugins": [], "forcedUpdates": []}
# ==================== 缓存写读 ====================
def save_license(ticket_json: dict | str) -> None:
"""持久化授权票据。ticket 可为 {ticket,...} 或原始签名串。"""
if isinstance(ticket_json, dict):
text = json.dumps(ticket_json, ensure_ascii=False)
else:
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
license_path.write_text(text, encoding="utf-8")
touch_sync()
def save_control(ticket_json: dict | str) -> None:
"""持久化管控清单缓存。"""
if isinstance(ticket_json, dict):
text = json.dumps(ticket_json, ensure_ascii=False)
else:
text = json.dumps({"ticket": ticket_json}, ensure_ascii=False)
control_path.write_text(text, encoding="utf-8")
touch_sync()
def run_check_allowed(plugin_id: str, account: str, online: bool) -> str | None:
"""启动前校验链(离线/联网通用骨架),返回 None=可运行,否则返回拒绝原因字符串。
- 验签授权票据,校验该插件 canRun。
- 下架/禁用(用本地缓存清单;联网时旧缓存同样先校验,联网后再拉最新)。
- 离线:跳过强制更新 deadline 检查(不联网一直能用)。
- 联网:额外校验强制更新 deadline 已过则拒启旧版本。
"""
control = verify_control()
if plugin_id in control.get("revokedPlugins", []):
return "插件已被下架(revoked),禁止运行"
if plugin_id in control.get("disabledPlugins", []):
return "插件已被禁用(disabled),禁止运行"
# 授权:先验签本地授权票据(离线可用)
try:
lic = verify_license()
except Exception as _exc: # noqa: BLE001 授权票据不可用
return f"本地授权票据校验失败:{_exc}" if online else "本地授权票据校验失败"
lic_plugins = {p.get("pluginId"): p for p in lic.get("plugins", [])}
grant = lic_plugins.get(plugin_id)
if not grant:
return f"账号 {account} 无插件「{plugin_id}」的授权"
if not grant.get("canRun"):
return f"账号 {account} 无「{plugin_id}」的运行授权"
# 强制更新:仅联网时严格校验 deadline;离线跳过(核心规则)
if online:
forced = next((f for f in control.get("forcedUpdates", [])
if f.get("pluginId") == plugin_id), None)
if forced:
min_ver = forced.get("minVersion", "")
deadline = forced.get("deadline", "")
if min_ver and deadline and _deadline_passed(deadline):
installed = _installed_version(plugin_id)
if installed and _version_lt(installed, min_ver):
return (f"插件需强制升级到 v{min_ver} 以上(deadline 已过),"
f"当前 v{installed} 已禁止启动,请先更新")
return None
def _installed_version(plugin_id: str) -> str:
"""读取本机当前已装版本(active.json 或插件目录)。有则不返回最新,供强制更新判断。"""
act = _APP_DATA / "active.json"
try:
d = json.loads(act.read_text(encoding="utf-8")) if act.is_file() else {}
return d.get("version", "") if d.get("pluginId") == plugin_id else ""
except Exception: # noqa: BLE001
return ""
def _deadline_passed(deadline: str) -> bool:
try:
dt = datetime.fromisoformat(deadline.replace("Z", "+00:00"))
return datetime.now(dt.tzinfo) > dt
except Exception: # noqa: BLE001
# 解析失败时按未过期兜底(不误伤在线用户)
return False
def _version_lt(a: str, b: str) -> bool:
"""版本比较:数字段按 int,非数字段按 str 小写。"""
def _k(s):
try:
return (1, int(s))
except ValueError:
return (0, str(s).lower())
return tuple(_k(x) for x in str(a).split(".")) < tuple(_k(x) for x in str(b).split("."))
# ==================== 运行上报 ====================
def report(account: str, device_id: str, plugin_id: str, version: str,
status: str, msg: str = "", duration_sec: int = 0) -> None:
"""运行上报:联网实时 POST;离线暂存 jsonl,重连后补报。失败不阻断主流程。"""
rec = {"account": account, "device_id": device_id, "plugin_id": plugin_id,
"version": version, "status": status, "msg": msg,
"duration_sec": int(duration_sec),
"at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
if not _CONTROLPLANE_URL:
return
if _push_report(rec):
touch_sync()
return
# 离线:暂存待补报
try:
with open(reports_path, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
except OSError:
pass
def _push_report(rec: dict) -> bool:
"""同步上报一条到中心机;成功返回 True。"""
try:
_push_via_tempfile(rec) # 用 go-offset 方式直连
return True
except Exception: # noqa: BLE001
return False
def _push_via_tempfile(rec: dict) -> None:
"""向 /api/runtime/report 的同步 POST(requests)。"""
import requests
r = requests.post(f"{_CONTROLPLANE_URL}/api/runtime/report",
json=rec, timeout=5)
r.raise_for_status()
def flush_offline_reports() -> int:
"""重连后补报此前暂存的离线记录;返回补报条数。"""
if not reports_path.is_file():
return 0
sent = 0
pending = []
try:
lines = [l for l in reports_path.read_text(encoding="utf-8").splitlines() if l.strip()]
for ln in lines:
try:
rec = json.loads(ln)
except ValueError:
continue
try:
_push_via_tempfile(rec)
sent += 1
except Exception: # noqa: BLE001
pending.append(ln) # 仍失败则保留下次再补
if not pending:
reports_path.unlink(missing_ok=True) # 全部成功则清空
else:
reports_path.write_text("\n".join(pending) + "\n", encoding="utf-8")
except OSError:
pass
return sent
+114
View File
@@ -0,0 +1,114 @@
# -*- coding: utf-8 -*-
"""webhost 宿主插件元数据 / 平台权限解析。
- 插件元数据由 plugin.json(manifest) 驱动,离线与旧插件兼容
- 平台/插件白名单来自中心机,按账号过滤(三态降级:授权集 / 空集防越权 / None 离线兜底全量)
"""
from __future__ import annotations
import json
import logging
import sys
from pathlib import Path
from webhost.backend.core import config
from webhost.backend.core.session import _ACCT_CLOUD_TOKEN
_LOGGER = logging.getLogger(__name__)
def _plugin_schema(p) -> dict:
"""组装插件元数据(manifest 驱动)。
plugin.json(与插件代码同目录)为权威:存在则其字段/能力/权限优先,仅当缺失时才
回退到 ScenePlugin 类上的 fields/capabilities,保证离线与旧插件兼容。
"""
manifest = _read_own_manifest(p)
name = (manifest or {}).get("name") or p.name
description = (manifest or {}).get("description")
if description is None:
description = p.description
fields = _fields_from_schema((manifest or {}).get("fields")) if manifest else None
if fields is None:
fields = p.fields
caps = (manifest or {}).get("capabilities") or p.capabilities
perms = (manifest or {}).get("permissions") or p.permissions
return {"id": p.id, "name": name, "version": p.version,
"description": description, "uses_month": getattr(p, "uses_month", False),
"capabilities": caps, "permissions": perms, "fields": fields}
def _read_own_manifest(p) -> dict | None:
"""读取与插件注册模块同目录的 plugin.json;缺文件或解析失败返回 None(不阻断)。"""
try:
mod = sys.modules.get(type(p).__module__)
jar = (mod and Path(mod.__file__).resolve().parent / "plugin.json")
if not jar or not jar.is_file():
return None
return json.loads(jar.read_text(encoding="utf-8"))
except Exception: # noqa: BLE001
return None
def _fields_from_schema(schema: dict) -> list | None:
"""JSON-Schema(object.properties) → 前端表单 [{key,label,type,default,options}]。"""
if not schema or schema.get("type") != "object" or not schema.get("properties"):
return None
out = []
for key, prop in schema["properties"].items():
item = {"key": key, "label": prop.get("title", key),
"default": prop.get("default", "")}
t = prop.get("type", "string")
if t == "integer" or t == "number":
item["type"] = "int"
elif t == "string" and "enum" in prop:
item["type"] = "select"
item["options"] = prop["enum"]
else:
item["type"] = "text"
d = prop.get("description")
if d:
item["description"] = d
out.append(item)
return out
def _account_allowed_platforms(account: str) -> set | None:
"""调中心机获取账号可登录平台白名单;控制面不可达返回 None(调用方决定拒绝)。"""
if not config.CONTROLPLANE_URL:
return None
import requests
headers = {"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}
try:
r = requests.get(f"{config.CONTROLPLANE_URL}/api/platforms/allowed",
params={"account": account}, headers=headers, timeout=5)
r.raise_for_status()
return set(r.json().get("allowed", []))
except Exception: # noqa: BLE001
return None
def _cloud_plugin_ids(account: str) -> set | None:
"""已登录且有云端会话 token 时,用 Bearer 向中心机 /api/plugins 拉账号可用插件 id 集(§2.2)。
降级策略(三态):
- 200 → 返回账号允许的插件 id 集(真正按员工权限过滤)
- 401 → 云端可达但 token 失效(如云端重启):返回空集,**不给全量**,防越权泄露
- 其它(超时/断连/5xx) → 返回 None,调用方按离线兜底放行本地全量(§2.5)
"""
token = (_ACCT_CLOUD_TOKEN or {}).get(account) if account else None
if not token or not config.CONTROLPLANE_URL:
return None
import requests
try:
r = requests.get(f"{config.CONTROLPLANE_URL}/api/plugins",
headers={"Authorization": f"Bearer {token}"}, timeout=5)
except Exception: # noqa: BLE001 云端不可达 → 离线兜底
return None
if r.status_code == 401:
return set()
if r.status_code != 200:
return None
return {p["id"] for p in r.json().get("plugins", [])}
+104
View File
@@ -0,0 +1,104 @@
# -*- 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。"""
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())
+159
View File
@@ -0,0 +1,159 @@
# -*- coding: utf-8 -*-
"""webhost 宿主 run 执行核心:登记运行记录 + 进程级隔离执行插件 + 结束后上报。
进程级隔离:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀;
由 Windows Job Object 整树托管(含浏览器孙进程)。
"""
from __future__ import annotations
import json
import logging
import os
import subprocess
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
from pydantic import BaseModel
from webhost.backend.core import scheduler as _scheduler
from webhost.backend.core import winjob as _winjob
from webhost.backend.core import licensing
from webhost.backend.core import state as _st
from webhost.backend.core.hub import HUB
_LOGGER = logging.getLogger(__name__)
class RunReq(BaseModel):
plugin_id: str
fields: dict = {}
def _run_target(plugin, fields: dict, run_id: str) -> None:
"""进程级隔离执行插件:拉起独立 python 子进程,stdout JSON 事件转发 /ws,超时强杀。
插件在此子进程内 `run()`,本地崩溃(死循环/sys.exit/内存爬升)不会拖垮底座;
登录态由子进程直接读取共享 cookie 文件重建,无需主进程中转。
"""
runner = Path(__file__).with_name("plugin_runner.py")
root = Path(__file__).resolve().parents[3] # core/runner.py → 项目根
timeout = int(os.getenv("RUN_TIMEOUT", "1800")) # 秒;浏览器类插件默认 30min
max_mem_mb = int(os.getenv("RUN_MAX_MEM_MB", "2048")) # 子进程作业内存上限(MB)
cmd = [sys.executable, "-u", str(runner), "--plugin", plugin.id, "--run", run_id]
if _st.ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
cmd += ["--allowed", ",".join(sorted(_st.ALLOWED))]
# Windows Job Object:整树托管(含浏览器孙进程),超时整树强杀 + 内存上限兜底
job = _winjob.Job(max_mem_mb=max_mem_mb)
try:
proc = subprocess.Popen(
cmd,
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, encoding="utf-8",
errors="replace",
)
job.assign(proc)
except Exception as e: # noqa: BLE001 子进程拉起失败
job.close()
_st._set_run(run_id, status="error", result=None, error=f"拉起执行子进程失败: {e}")
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
"error": f"拉起执行子进程失败: {e}"})
return
def _publish_event(ev: dict):
t = ev.get("ev")
if t == "log":
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": ev.get("level", "INFO"), "msg": ev.get("msg", "")})
elif t == "progress":
HUB.publish({"t": "progress", "run_id": run_id, "plugin_id": plugin.id,
"pct": int(ev.get("pct", 0))})
_result: dict = {}
_rlock = threading.Lock()
def _drain_out():
for line in proc.stdout:
line = line.strip()
if not line:
continue
try:
ev = json.loads(line)
except ValueError:
continue
if ev.get("ev") in ("log", "progress"):
_publish_event(ev)
elif ev.get("ev") == "result":
with _rlock:
_result.update(ev)
def _drain_err():
for line in proc.stderr:
line = line.strip()
if line:
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "ERROR", "msg": line})
t_out = threading.Thread(target=_drain_out, daemon=True, name=f"out-{run_id}")
t_err = threading.Thread(target=_drain_err, daemon=True, name=f"err-{run_id}")
t_out.start(); t_err.start()
try:
proc.stdin.write(json.dumps(fields, ensure_ascii=False))
proc.stdin.close()
except OSError:
pass
timed_out = False
try:
proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
timed_out = True
try:
job.terminate() # 整树终止(含 DrissionPage 浏览器等孙进程)
proc.wait(timeout=5)
except (subprocess.TimeoutExpired, OSError):
pass
try:
with _rlock:
ev = dict(_result)
if ev:
ok = bool(ev.get("ok"))
_st._set_run(run_id, status="done" if ok else "error",
result=ev.get("result"), error=ev.get("error"))
HUB.publish({"t": "run_done", "run_id": run_id, "ok": ok,
"error": ev.get("error")})
elif timed_out:
msg = f"插件执行超时({timeout}s)已强制终止"
_st._set_run(run_id, status="error", result=None, error=msg)
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
else:
msg = f"执行进程异常退出(exit={proc.returncode})且未返回结果"
_st._set_run(run_id, status="error", result=None, error=msg)
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
finally:
_scheduler.mark_done(plugin.id, run_id) # 单活槽位回空闲并唤醒排队请求
_report_run(plugin.id, run_id) # 运行上报(联网实时/离线暂存补报)
job.close() # KILL_ON_JOB_CLOSE 兜底清理残留子进程
def _report_run(plugin_id: str, run_id: str) -> None:
"""运行结束后上报中心机:读取本次运行最终状态与服务时长,联网实时、离线暂存补报。"""
try:
with _st.RUN_LOCK:
run = _st.RUNS.get(run_id) or {}
account = run.get("account", "")
status = "done" if run.get("status") == "done" else \
("running" if run.get("status") == "running" else "error")
msg = run.get("error") or ""
duration = int(time.time() - float(run.get("started", time.time()))) if run.get("started") else 0
licensing.report(account=account, device_id="",
plugin_id=plugin_id, version=run.get("version", ""),
status=status, msg=msg, duration_sec=duration)
except Exception as _exc: # noqa: BLE001 上报失败不阻断主流程
_LOGGER.warning("运行上报失败:%s", _exc)
+120
View File
@@ -0,0 +1,120 @@
# -*- coding: utf-8 -*-
"""设备级单活调度器:整机同一时刻只运行一个插件进程。
- active.json 记录设备级当前运行 {userId, pluginId, version, status, startedAt}。
- 模块级锁 + 磁盘状态双重保证单活:同一时刻只有一个插件在跑,与用户无关。
- 用户切换插件/切换用户 = 停旧插件(整树终止) → 清理 → 启动新插件 → 健康检查 → 激活;
启动失败回滚到"空闲",不让半激活状态阻塞后续启动。
"""
from __future__ import annotations
import json
import logging
import os
import subprocess
import sys
import threading
import time
from datetime import datetime
from pathlib import Path
_LOGGER = logging.getLogger(__name__)
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
or Path.home(), "37duAutomation")
ACTIVE_PATH = _APP_DATA / "active.json"
# 全局单活条件变量:同一时刻只能有一个插件进程。请求先等待当前插件执行完成(完全不能并发)。
_SCHED_COND = threading.Condition()
def init_active() -> None:
"""初始化 active.json(无则写入空闲态),并确保数据目录可写。
进程启动时若残留 running/switching(上次异常退出/断电),复位为空闲,
防止 request_start 的死等条件永远不满足导致所有插件永久排队。"""
_APP_DATA.mkdir(exist_ok=True)
if not ACTIVE_PATH.is_file():
write_active(userId="", pluginId="", version="", status="idle")
elif read_active().get("status") in ("running", "switching"):
_LOGGER.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲")
write_active(status="idle", userId="", pluginId="", version="", runId="", startedAt="")
def read_active() -> dict:
try:
d = json.loads(ACTIVE_PATH.read_text(encoding="utf-8")) if ACTIVE_PATH.is_file() else {}
return d if isinstance(d, dict) else {}
except Exception: # noqa: BLE001
return {}
def _is_busy() -> bool:
return read_active().get("status") in ("running", "switching")
def write_active(**kw) -> None:
"""写回 active.json(保留既有键,仅更新传入字段)。"""
d = read_active()
d.update(kw)
d.setdefault("userId", "")
d.setdefault("pluginId", "")
d.setdefault("version", "")
d.setdefault("status", "idle")
d.setdefault("startedAt", "")
d.setdefault("runId", "")
try:
# 原子写:先写临时文件再 os.replace,避免写入中断留下半截 JSON 被误读
tmp = ACTIVE_PATH.with_suffix(".json.tmp")
tmp.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
os.replace(tmp, ACTIVE_PATH)
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("写 active.json 失败:%s", _exc)
def current() -> dict:
"""当前活动插件(空闲则返回空映射)。"""
return read_active()
def is_active(plugin_id: str) -> bool:
"""当前设备是否正在跑该插件。"""
a = read_active()
return bool(a.get("status") == "running" and a.get("pluginId") == plugin_id)
def request_start(user: str, plugin_id: str, version: str, start_fn) -> dict:
"""设备级单活启动:阻塞等待当前插件执行完成后再启动目标(完全不能并发)。
- 若设备正有插件在跑(running/switching),本请求会在此等待,直至该插件执行结束。
- `start_fn` 负责拉起子进程并返回 run_id(不可阻塞),即视为占用单活槽位。
- 启动失败回滚到"空闲"并唤醒等待者。
"""
with _SCHED_COND:
while _is_busy():
_SCHED_COND.wait()
write_active(status="switching", startedAt=_now())
try:
run_id = start_fn()
except Exception as _exc: # noqa: BLE001
write_active(status="idle")
_SCHED_COND.notify_all()
return {"ok": False, "error": f"启动失败:{_exc}"}
write_active(userId=user, pluginId=plugin_id, version=version,
status="running", runId=run_id, startedAt=_now())
return {"ok": True, "run_id": run_id}
def mark_done(plugin_id: str, run_id: str) -> None:
"""运行结束:若 active 仍是该插件则回空闲,并唤醒等待的后续请求(幂等)。"""
with _SCHED_COND:
a = read_active()
if a.get("pluginId") == plugin_id and a.get("runId") == run_id:
write_active(status="idle")
_SCHED_COND.notify_all()
elif a.get("pluginId") == plugin_id:
write_active(status="idle")
_SCHED_COND.notify_all()
def _now() -> str:
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+87
View File
@@ -0,0 +1,87 @@
# -*- coding: utf-8 -*-
"""webhost 宿主统一账户会话:cookie 会话唯一真源 + 本机会话落盘持久化 + 云端 token 缓存。
会话状态(token->account 活跃ts)只在此模块定义;admin/dingtalk/meta 等路由经本模块访问。
"""
from __future__ import annotations
import json
import logging
import threading
import time
from pathlib import Path
from fastapi import HTTPException, Request
_LOGGER = logging.getLogger(__name__)
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
# 会话空闲有效期:7 天滑动续期(每次有效请求刷新 TTL;天天用永不重登,超期需重登)
_SESS_TTL = 7 * 24 * 3600
_SESS: dict[str, tuple] = {}
_SESS_LOCK = threading.Lock()
# 本机会话落盘文件:重启后端不丢会话(兑现"双击壳直接进插件页、不必每次重登")
_SESS_FILE = Path(__file__).resolve().parents[1] / "_cp_sessions.json"
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
def _sess_persist():
"""把本机会话快照落盘为首存(token → [account, 最近活跃ts]),进程重启后仍有效。"""
try:
with _SESS_LOCK:
_payload = {t: [a, int(_ts)] for t, (a, _ts) in _SESS.items()}
_SESS_FILE.write_text(json.dumps(_payload, ensure_ascii=False), encoding="utf-8")
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("本机会话持久化失败: %s", _exc)
def _sess_load():
"""启动时从磁盘恢复本机会话(惰性丢弃已过期条)。"""
if not _SESS_FILE.is_file():
return
try:
_raw = json.loads(_SESS_FILE.read_text(encoding="utf-8"))
except (OSError, ValueError):
return
_now = time.time()
with _SESS_LOCK:
for _t, _it in (_raw or {}).items():
try:
_a, _ts = _it[0], float(_it[1])
except (KeyError, IndexError, TypeError, ValueError):
continue
if _now - _ts <= _SESS_TTL:
_SESS[_t] = (_a, _ts)
def _sess_account(request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录/过期返回空串(过期顺手清理并落盘)。"""
token = request.cookies.get(SESSION_COOKIE, "")
account = ""
with _SESS_LOCK:
item = _SESS.get(token)
if item:
_account, _ts = item
if time.time() - _ts <= _SESS_TTL:
_SESS[token] = (_account, time.time()) # 滑动续期
account = _account
else:
_SESS.pop(token, None)
if account:
_sess_persist() # 滑动续期也落盘,重启后仍有效
return account
def _require_login(request: Request) -> str:
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
account = _sess_account(request)
if not account:
raise HTTPException(401, "未登录:请先登录统一账户")
return account
_sess_load() # 启动即恢复本机会话(重启后端不丢会话)
+52
View File
@@ -0,0 +1,52 @@
# -*- coding: utf-8 -*-
"""webhost 宿主运行时共享状态:模块级可变全局的唯一真源(单一 owner,禁止他处另建副本)。
- ALLOWED 在启动(lifespan)时决定且会被整体重新赋值,故一律经 state 模块引用读写
(`from webhost.backend import state as st; st.ALLOWED / st.set_allowed(v)`),
避免 from-import 复制绑定读不到最新值。
- RUNS/RUN_LOCK/_NS_LOCKS/PLATFORMS 均为可变对象,跨模块传的是同一引用。
依赖方向:state ← 领域逻辑与路由模块。
"""
from __future__ import annotations
import threading
from webhost.backend.core import auth as platform_auth
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
for p in platform_auth.platforms()}
# 运行会话:run_id -> {status, account, result, error}
RUNS: dict = {}
RUN_LOCK = threading.Lock()
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
# 插件权限白名单(启动时决定;执行子进程透传同款白名单,保证两侧加载一致)
ALLOWED: set | None = None
def set_allowed(v: set | None) -> None:
global ALLOWED
ALLOWED = v
# 平台命名空间并发闸:同平台(hr/oa/…)任务串行执行,保护共享登录态 cookies 不被并发争抢
_NS_LOCKS: dict[str, threading.Lock] = {}
_NS_GUARD = threading.Lock()
def _ns_gate(platform: str) -> threading.Lock:
key = (platform or "").strip() or "local"
with _NS_GUARD:
if key not in _NS_LOCKS:
_NS_LOCKS[key] = threading.Lock()
return _NS_LOCKS[key]
def _set_run(run_id: str, **kw) -> None:
"""更新运行记录字段(保留 account 等既有键)。"""
with RUN_LOCK:
run = RUNS.get(run_id)
if run is not None:
run.update(kw)
+99
View File
@@ -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