feat: 完成插件管理系统产品化P0闭环落地

此提交实现完整的插件管理产品化闭环:
1. 中心机新增Ed25519密钥、审计/运行上报表、插件扩展字段,实现票据/管控清单签发、鉴权下载能力
2. 部署端新增设备级单活调度器、用户私有插件库、离线/联网校验链、插件下载安装流程
3. 控制面与部署前端同步更新UI与接口适配,新增审计页、插件管理增强功能
4. 修复两个工作流脚本的过滤与Excel导出问题,优化打包依赖与日志面板
5. 新增完整架构设计与实施文档
This commit is contained in:
2026-09-11 09:08:40 +08:00
parent 42c7cf24f2
commit d605a7f9cc
51 changed files with 11037 additions and 6237 deletions
+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
+270 -5
View File
@@ -25,9 +25,13 @@ from pathlib import Path
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from urllib.parse import urlencode
from webhost.backend import auth as platform_auth
from webhost.backend import licensing
from webhost.backend import scheduler as _scheduler
from webhost.backend import winjob as _winjob
from webhost.backend.hub import HUB
from webhost.backend.plugins import PLUGINS, load_plugins # PLUGINS 为注册表,启动时显式填装
@@ -64,6 +68,10 @@ 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", "")
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
# cookie 会话:token -> (account, 活跃时间戳);登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
@@ -183,6 +191,30 @@ def _cp_call(method: str, path: str, **kw) -> dict:
return body
# ==================== 产品化:离线授权同步 + 单活调度终止注册表 ====================
def _sync_licensing(account: str) -> None:
"""联网拉取并缓存 中心机公钥 + 该账号离线授权票据 + 管控清单;成功后补报离线记录。
离线票据/管控清单持久化到 %LOCALAPPDATA%\\37duAutomation,供断网时在线验签运行。
"""
if not CONTROLPLANE_URL or not account:
return
import requests
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
r = requests.get(f"{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"{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"{CONTROLPLANE_URL}/api/me/control-list", headers=headers, timeout=5)
r.raise_for_status()
licensing.save_control(r.json())
licensing.flush_offline_reports()
@asynccontextmanager
async def lifespan(app: FastAPI):
HUB.bind(asyncio.get_running_loop())
@@ -190,6 +222,15 @@ async def lifespan(app: FastAPI):
global ALLOWED
ALLOWED = _resolve_allowed()
load_plugins(ALLOWED)
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
licensing.init(CONTROLPLANE_URL, threading.Lock())
_scheduler.init_active()
if CONTROLPLANE_URL:
try:
_sync_licensing(CONTROLPLANE_ACCOUNT)
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", CONTROLPLANE_ACCOUNT)
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
yield
@@ -231,9 +272,135 @@ def admin_login(b: _LoginIn, response: Response) -> dict:
with _SESS_LOCK:
_SESS[token] = (b.account.strip(), time.time())
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
if CONTROLPLANE_URL:
try:
_sync_licensing(b.account.strip())
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {**r, "account": b.account.strip()}
class _DingTalkIn(BaseModel):
account: str # 钉钉工号(作为统一账号)
nickname: str = "" # 钉钉姓名
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
@app.post("/api/admin/dingtalk/login")
def admin_dingtalk_login(d: _DingTalkIn, response: Response) -> dict:
"""钉钉扫码登录(链接授权后回跳):account/nickname 已由中心机换取,直接建立会话。"""
if not d.account:
raise HTTPException(400, "工号不能为空")
return _dingtalk_establish(d.account.strip(), d.nickname, d.dingtalk_uid, response)
def _dingtalk_establish(account: str, nickname: str, dingtalk_uid: str, response: Response) -> dict:
"""统一建立钉钉账号会话:中心机找建账号 → 写本机会话 cookie → 同步离线票据。
账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用此通路,保证登录态一致。
"""
r = _cp_call(
"POST", "/api/admin/dingtalk/auth",
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
json={"account": account, "nickname": nickname, "dingtalk_uid": dingtalk_uid})
acct = r.get("account") or account
token = uuid.uuid4().hex
with _SESS_LOCK:
_SESS[token] = (acct, time.time())
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
if CONTROLPLANE_URL:
try:
_sync_licensing(acct)
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
return {"ok": True, "account": acct, "is_admin": bool(r.get("is_admin")),
"created": bool(r.get("created")), "must_change_pwd": bool(r.get("must_change_pwd"))}
class _InlineIn(BaseModel):
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
@app.post("/api/admin/dingtalk/inline")
def admin_dingtalk_inline(d: _InlineIn, response: Response) -> dict:
"""内嵌二维码扫码登录:loginTmpCode → 中心机换工号/姓名 → 建立会话。
登录页用钉钉 DDLogin 在本页内渲染二维码,扫码后前端拿到 loginTmpCode 传本接口,
由中心机换出工号/姓名(可信身份源),再走 _dingtalk_establish 建会话——全程不弹浏览器。
"""
if not d.code.strip():
raise HTTPException(400, "缺少扫码截图码")
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
info = _cp_call(
"POST", "/api/admin/dingtalk/sns",
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
json={"code": d.code.strip()})
account = (info.get("account") or "").strip()
if not account:
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
return _dingtalk_establish(account, info.get("nickname") or "", info.get("unionid") or "", response)
@app.get("/api/admin/dingtalk/inline_qr")
def admin_dingtalk_inline_qr(request: Request) -> dict:
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
if not CONTROLPLANE_URL:
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return _cp_call(
"GET", "/api/admin/dingtalk/inline_qr",
params={"back": back},
headers=({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}))
# ==================== 钉钉真实扫码:扫码URL + 静默回调页 ====================
# 扫码 URL 指向中心机 /api/admin/dingtalk/scan(back 回跳到本机 /cb);
# 扫码成功 → 中心机 /cb 302 回本机 /cb?account=&nickname= → 本页静默调 dingtalk/login 建会话
# → 刷新父窗口(登录完成)。身份源为钉钉+中心机(可信),与账号密码登录同会话机制。
_DINGTALK_CB_HTML = """<!doctype html><html><head><meta charset="utf-8"><title>登录中</title></head>
<body style="margin:0;background:#f5f6fa;font-family:system-ui,-apple-system,sans-serif">
<div style="padding:60px 20px;text-align:center;color:#5c6470">钉钉登录中,请稍候…</div>
<script>
(async function(){
var q = new URLSearchParams(location.search);
var account = q.get('account') || '';
var nickname = q.get('nickname') || '';
if (account) {
try {
await fetch('/api/admin/dingtalk/login', {
method:'POST', headers:{'Content-Type':'application/json'},
body: JSON.stringify({ account: account, nickname: nickname })
});
} catch (e) {}
}
try { window.opener && window.opener.location.reload(); } catch (e) {}
setTimeout(function(){ try { window.close(); } catch (e) {} }, 500);
})();
</script></body></html>"""
@app.get("/api/admin/dingtalk/qr")
def dingtalk_qr(request: Request) -> dict:
"""返回中心机扫码登录 URL。
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
"""
if not CONTROLPLANE_URL:
return {"url": ""}
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
return {"url": f"{CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
@app.get("/api/admin/dingtalk/cb")
def dingtalk_cb() -> HTMLResponse:
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
return HTMLResponse(_DINGTALK_CB_HTML)
@app.post("/api/admin/logout")
def admin_logout(request: Request, response: Response) -> dict:
"""登出:清除会话 cookie 与内存会话。"""
@@ -264,9 +431,59 @@ def admin_overview(request: Request) -> dict:
def _plugin_schema(p) -> dict:
return {"id": p.id, "name": p.name, "version": p.version,
"description": p.description, "uses_month": getattr(p, "uses_month", False),
"fields": p.fields}
"""组装插件元数据(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:
@@ -296,7 +513,14 @@ def meta(request: Request) -> dict:
# 已登录时按账号白名单;未登录/中心机不可达默认展示
"allowed": (pid in allowed) if allowed is not None else True}
for pid, m in PLATFORMS.items()]
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
return {
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
"controlplane": CONTROLPLANE_URL,
"appName": "37du 业务场景工具集",
"dingtalkScan": bool(DINGTALK_APP_KEY),
"platforms": platforms,
"plugins": plugins,
}
@app.post("/api/platforms/{pid}/login")
@@ -429,9 +653,28 @@ def _run_target(plugin, fields: dict, run_id: str) -> None:
_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 RUN_LOCK:
run = 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)
@app.post("/api/runs", status_code=202)
def start_run(req: RunReq, request: Request) -> dict:
account = _require_login(request)
@@ -439,14 +682,24 @@ def start_run(req: RunReq, request: Request) -> dict:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
raise HTTPException(404, "插件不存在")
# 产品化前置校验链:验签本地授权票据(canRun) + 下架/禁用 + 联网时强制更新 deadline
online = licensing.is_online()
deny = licensing.run_check_allowed(plugin.id, account, online)
if deny:
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
raise HTTPException(403, deny)
run_id = uuid.uuid4().hex
with RUN_LOCK:
if len(RUNS) >= MAX_RUNS:
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
RUNS[run_id] = {"status": "running", "account": account,
"version": getattr(plugin, "version", "0"),
"started": time.time(),
"result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
licensing.report(account=account, device_id="", plugin_id=plugin.id,
version=getattr(plugin, "version", "0"), status="start")
def _queued():
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
@@ -456,7 +709,19 @@ def start_run(req: RunReq, request: Request) -> dict:
"level": "INFO",
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
with gate:
_run_target(plugin, req.fields, run_id)
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
if _scheduler._is_busy():
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
"level": "INFO",
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
def _start(_run_id):
threading.Thread(target=_run_target,
args=(plugin, req.fields, _run_id),
daemon=True, name=f"exec-{plugin.id}").start()
return _run_id
_scheduler.request_start(account, plugin.id,
getattr(plugin, "version", "0"), _start)
threading.Thread(target=_queued, daemon=True,
name=f"run-{plugin.id}").start()
+4
View File
@@ -54,6 +54,10 @@ class ScenePlugin:
# 表单字段定义:[{key,label,type,default,options}]
# type ∈ int | text | select
fields: List[dict] = []
# 声明式能力/权限(manifest 驱动):与插件包 plugin.json 保持一致;
# 缺省场景可用本地类补充,plugin.json 存在时以其为权威。
capabilities: List[str] = []
permissions: dict = {}
def run(self, fields: dict, ctx: RunContext) -> dict:
raise NotImplementedError(f"插件 {self.id} 未实现 run")
@@ -0,0 +1,24 @@
{
"schema_version": 1,
"id": "seal_check",
"name": "考勤月报封存检查",
"version": "1.0.0",
"description": "填写每月正休规则,一键执行五项检查并导出多 Sheet Excel 报告",
"category": "考勤",
"icon": "",
"platform": "hr",
"uses_month": true,
"capabilities": ["seal_check", "hr.seal_check"],
"permissions": {
"platforms": ["hr"]
},
"fields": {
"type": "object",
"properties": {
"fixed_rest_days": { "type": "integer", "title": "固休应休天数", "default": 5, "description": "" },
"size_rest_days": { "type": "integer", "title": "大小休应休天数", "default": 6, "description": "" },
"quota_rest_days": { "type": "integer", "title": "限额排休上限", "default": 8, "description": "" }
},
"required": []
}
}
+112
View File
@@ -0,0 +1,112 @@
# -*- 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(无则写入空闲态),并确保数据目录可写。"""
_APP_DATA.mkdir(exist_ok=True)
if not ACTIVE_PATH.is_file():
write_active(user="", plugin="", version="", status="idle")
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:
ACTIVE_PATH.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
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")