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

此提交实现完整的插件管理产品化闭环:
1. 中心机新增Ed25519密钥、审计/运行上报表、插件扩展字段,实现票据/管控清单签发、鉴权下载能力
2. 部署端新增设备级单活调度器、用户私有插件库、离线/联网校验链、插件下载安装流程
3. 控制面与部署前端同步更新UI与接口适配,新增审计页、插件管理增强功能
4. 修复两个工作流脚本的过滤与Excel导出问题,优化打包依赖与日志面板
5. 新增完整架构设计与实施文档
This commit is contained in:
2026-09-11 09:08:40 +08:00
parent 863f818740
commit 81c456c35a
51 changed files with 11037 additions and 6237 deletions
+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()