refactor: 重构项目目录结构与代码组织
1. 重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包 2. 移动并整理工具脚本到tools子目录,统一管理运维脚本 3. 重构插件运行时、调度、作业管理等核心模块到core子包 4. 更新AGENTS.md文档,明确各代码形态的组织规范 5. 清理重复的旧文件与冗余代码
This commit is contained in:
@@ -1,3 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端:场景插件宿主
|
||||
"""
|
||||
"""webhost 后端(执行机底座):场景插件宿主。
|
||||
|
||||
组装层 main.py 之外的领域逻辑已归入 core 子包。本 `__init__` 作为 facade 再导出
|
||||
core 内各模块,以兼容 `from webhost.backend import X` 的既有用法(含插件 `auth` 引用)。
|
||||
"""
|
||||
from webhost.backend.core import ( # noqa: F401
|
||||
auth,
|
||||
config,
|
||||
cpapi,
|
||||
hub,
|
||||
licensing,
|
||||
meta,
|
||||
runner,
|
||||
scheduler,
|
||||
session,
|
||||
state,
|
||||
winjob,
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主 API 路由子包:各领域路由模块导出 APIRouter,由 backend/main.py 组装 include。"""
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「管理台基础」路由:统一账户登录 / 当前账号 / 登出 / 改密 / 概览。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _cp_headers, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _SESS, _SESS_LOCK,
|
||||
_sess_account, _sess_persist)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@router.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
@router.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
# 登录成功即联网同步该账号的离线授权票据 + 管控清单 + 中心机公钥(供离线运行)
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(b.account.strip())
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录本身
|
||||
import logging
|
||||
logging.getLogger(__name__).warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return {**r, "account": b.account.strip()}
|
||||
|
||||
|
||||
@router.post("/api/admin/logout")
|
||||
def admin_logout(request: Request, response: Response) -> dict:
|
||||
"""登出:清除会话 cookie 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@router.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
@@ -0,0 +1,224 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「钉钉」路由:账号工号登录、内嵌二维码登录、链接授权回跳、真实扫码回调。
|
||||
|
||||
- 账号密码登录与两种钉钉扫码(链接授权 / 内嵌二维码)共用 _dingtalk_establish 建会话。
|
||||
- 云端(cp)只参与换 token,AppSecret 不出云端;会话存本机、重启不掉。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, Response
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend import config
|
||||
from webhost.backend.core.cpapi import _cp_call, _sync_licensing
|
||||
from webhost.backend.core.session import (SESSION_COOKIE, _ACCT_CLOUD_TOKEN, _SESS,
|
||||
_SESS_LOCK, _sess_persist)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
# 登录回跳 state 有效期与缓存(防 CSRF 回跳伪造)
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class _DingTalkIn(BaseModel):
|
||||
account: str # 钉钉工号(作为统一账号)
|
||||
nickname: str = "" # 钉钉姓名
|
||||
dingtalk_uid: str = "" # 钉钉 userid/openId(便于二次扫码精确复用)
|
||||
|
||||
|
||||
class _InlineIn(BaseModel):
|
||||
code: str # 内嵌二维码扫码后钉钉 JS 返回的 loginTmpCode
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
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": config.CONTROLPLANE_TOKEN} if config.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())
|
||||
_sess_persist()
|
||||
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
|
||||
if config.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"))}
|
||||
|
||||
|
||||
@router.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)
|
||||
|
||||
|
||||
@router.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 config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址,无法扫码登录")
|
||||
info = _cp_call(
|
||||
"POST", "/api/admin/dingtalk/sns",
|
||||
headers=({"X-API-Token": config.CONTROLPLANE_TOKEN} if config.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)
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/inline_qr")
|
||||
def admin_dingtalk_inline_qr(request: Request) -> dict:
|
||||
"""内嵌二维码登录:代理中心机构造 DDLogin 的 goto 参数(登录页在本页内渲染二维码)。"""
|
||||
if not config.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": config.CONTROLPLANE_TOKEN} if config.CONTROLPLANE_TOKEN else {}))
|
||||
|
||||
|
||||
@router.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not config.DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not config.CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{config.PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": config.DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@router.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
_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>"""
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/qr")
|
||||
def dingtalk_qr(request: Request) -> dict:
|
||||
"""返回中心机扫码登录 URL。
|
||||
|
||||
扫码换取工号/姓名在中心机完成(中心机 .env 的 DINGTALK_APP_KEY),
|
||||
部署机只需能访问中心机即可,无需自带钉钉应用凭证。
|
||||
未配置中心机(CONTROLPLANE_URL)时返回空串,前端隐藏扫码入口。
|
||||
"""
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return {"url": ""}
|
||||
back = f"{request.url.scheme}://{request.url.netloc}/api/admin/dingtalk/cb"
|
||||
return {"url": f"{config.CONTROLPLANE_URL}/api/admin/dingtalk/scan?{urlencode({'back': back})}"}
|
||||
|
||||
|
||||
@router.get("/api/admin/dingtalk/cb")
|
||||
def dingtalk_cb() -> HTMLResponse:
|
||||
"""钉钉扫码成功后的静默回调页:建会话并刷新父窗口。"""
|
||||
return HTMLResponse(_DINGTALK_CB_HTML)
|
||||
@@ -0,0 +1,67 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「业务元数据与平台登录」路由:/api/meta 聚合 + 平台真实登录/登出。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend import meta as _meta
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _meta._cloud_plugin_ids(account)
|
||||
plugins = ([_meta._plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_meta._plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _meta._account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in _st.PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": config.CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(config.DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/login")
|
||||
def platform_login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _meta._account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@router.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = _st.PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/api/runs", status_code=202)
|
||||
def start_run(req: RunReq, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
try:
|
||||
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 _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.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 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
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()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@router.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with _st.RUN_LOCK:
|
||||
run = _st.RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@router.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
@@ -0,0 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 后端领域逻辑核心(core)包。
|
||||
|
||||
鉴权/会话/调度/执行/控制面集成/单活/Job 托管等实现模块集合。
|
||||
"""
|
||||
@@ -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", "")
|
||||
@@ -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()
|
||||
@@ -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", [])}
|
||||
@@ -1,7 +1,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件执行子进程入口(进程级隔离)。
|
||||
|
||||
由底座 main 以 `python -m webhost.backend.plugin_runner --plugin <id>` 拉起,
|
||||
由底座 main 以 `python -m webhost.backend.core.plugin_runner --plugin <id>` 拉起,
|
||||
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
|
||||
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
|
||||
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
|
||||
@@ -16,7 +16,8 @@ import sys
|
||||
|
||||
def _bootstrap_paths() -> str:
|
||||
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
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
|
||||
@@ -46,7 +47,7 @@ def _run() -> int:
|
||||
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend.core import auth as platform_auth
|
||||
|
||||
# 解析参数
|
||||
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
|
||||
@@ -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)
|
||||
@@ -34,7 +34,7 @@ def init_active() -> None:
|
||||
防止 request_start 的死等条件永远不满足导致所有插件永久排队。"""
|
||||
_APP_DATA.mkdir(exist_ok=True)
|
||||
if not ACTIVE_PATH.is_file():
|
||||
write_active(user="", plugin="", version="", status="idle")
|
||||
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="")
|
||||
@@ -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() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
@@ -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)
|
||||
+30
-883
@@ -1,273 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主:FastAPI 后端。
|
||||
"""webhost 宿主(组装层):创建 FastAPI app,装配各领域路由,执行重启初始化。
|
||||
|
||||
- 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验)
|
||||
- 场景插件注册表 + 表单 schema
|
||||
- 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成
|
||||
- 挂载前端构建产物(frontend/dist)实现单产物
|
||||
业务逻辑已按领域拆到 sibling 模块:
|
||||
- config.py 环境配置 - state.py 共享可变状态 - session.py 统一账户会话
|
||||
- cpapi.py 中心机代理 - runner.py run 执行 - meta.py 插件元数据/平台权限
|
||||
- apis/ 路由子包(admin / dingtalk / meta / runs)
|
||||
本文件仅承担:lifespan 初始化、创建 app、include_router、静态前端挂载、uvicorn 启动。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import secrets
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
|
||||
from pydantic import BaseModel
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import HTMLResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from urllib.parse import urlencode
|
||||
|
||||
from webhost.backend import auth as platform_auth
|
||||
from webhost.backend import config
|
||||
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 为注册表,启动时显式填装
|
||||
|
||||
PORT = 8799
|
||||
DIST = Path(__file__).resolve().parents[1] / "frontend" / "dist"
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.cpapi import _resolve_allowed, _sync_licensing
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import load_plugins
|
||||
from webhost.backend.apis import admin as api_admin
|
||||
from webhost.backend.apis import dingtalk as api_dingtalk
|
||||
from webhost.backend.apis import meta as api_meta
|
||||
from webhost.backend.apis import runs as api_runs
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# ==================== 配置固化:加载本模块 env(webhost/.env;免命令行传参;环境变量优先) ====================
|
||||
def _load_dotenv() -> None:
|
||||
"""轻量读取 webhost/.env,灌入 os.environ(仅当变量缺失时)。UTF-8、'#'/'空行'跳过。"""
|
||||
env_path = Path(__file__).resolve().parents[1] / ".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", "")
|
||||
# 统一账户体系为真源:登录态由后端 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"
|
||||
|
||||
|
||||
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() # 启动即恢复本机会话(重启后端不丢会话)
|
||||
|
||||
|
||||
# 平台登录态:标签/展示名来自 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
|
||||
|
||||
# 平台命名空间并发闸:同平台(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)
|
||||
|
||||
|
||||
class RunReq(BaseModel):
|
||||
plugin_id: str
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def _resolve_allowed() -> set | None:
|
||||
"""按权限源决定可加载插件白名单。None = 全量加载(默认/控制面不可达兜底)。"""
|
||||
if PLUGIN_SOURCE != "controlplane" or not CONTROLPLANE_URL:
|
||||
return None
|
||||
if not CONTROLPLANE_ACCOUNT:
|
||||
_LOGGER.warning("PLUGIN_SOURCE=controlplane 但未设置 CONTROLPLANE_ACCOUNT,回退全量加载")
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{CONTROLPLANE_URL}/api/plugins",
|
||||
params={"account": CONTROLPLANE_ACCOUNT},
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
allowed = {p["id"] for p in r.json().get("plugins", [])}
|
||||
_LOGGER.info("控制面权限清单(%s):%s", CONTROLPLANE_ACCOUNT,
|
||||
sorted(allowed) or "(空)")
|
||||
return allowed
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("拉取控制面权限清单失败,回退全量加载:%s", _exc)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 统一后端(数据库 API)代理:底座前端访问统一后端的唯一通道 ====================
|
||||
# 底座前端不直连统一后端/数据库;全部经本层代理转发,并注入「当前登录账号 + 内部凭证」。
|
||||
|
||||
|
||||
def _cp_headers(request: Request) -> dict:
|
||||
h = {"X-Admin-User": _sess_account(request)}
|
||||
if CONTROLPLANE_TOKEN:
|
||||
h["X-API-Token"] = CONTROLPLANE_TOKEN
|
||||
return h
|
||||
|
||||
|
||||
def _cp_call(method: str, path: str, **kw) -> dict:
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "统一后端未配置(CONTROLPLANE_URL)")
|
||||
import requests
|
||||
|
||||
r = requests.request(method, f"{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 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())
|
||||
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
|
||||
global ALLOWED
|
||||
ALLOWED = _resolve_allowed()
|
||||
load_plugins(ALLOWED)
|
||||
_st.set_allowed(_resolve_allowed())
|
||||
load_plugins(_st.ALLOWED)
|
||||
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
|
||||
licensing.init(CONTROLPLANE_URL, threading.Lock())
|
||||
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
|
||||
_scheduler.init_active()
|
||||
if CONTROLPLANE_URL:
|
||||
if config.CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", CONTROLPLANE_ACCOUNT)
|
||||
_sync_licensing(config.CONTROLPLANE_ACCOUNT)
|
||||
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", config.CONTROLPLANE_ACCOUNT)
|
||||
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
|
||||
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
|
||||
yield
|
||||
@@ -276,646 +55,14 @@ async def lifespan(app: FastAPI):
|
||||
app = FastAPI(title="37du Web Host", lifespan=lifespan)
|
||||
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
|
||||
|
||||
app.include_router(api_admin.router)
|
||||
app.include_router(api_dingtalk.router)
|
||||
app.include_router(api_meta.router)
|
||||
app.include_router(api_runs.router)
|
||||
|
||||
@app.get("/api/admin/me")
|
||||
def admin_me(request: Request) -> dict:
|
||||
"""当前登录账号是否管理员(会话 cookie)。
|
||||
|
||||
账号一律以**壳本机会话**为准(登录即有效);is_admin/部门 尽量从云端补齐,
|
||||
云端未授信 X-Admin-User(未配 CONTROLPLANE_TOKEN)或不可达时,仅降级 is_admin=False,
|
||||
不影响员工正常进入插件页(前端以 account 非空判登录)。
|
||||
"""
|
||||
account = _sess_account(request)
|
||||
if not account:
|
||||
return {"account": "", "is_admin": False, "dept": "", "nickname": ""}
|
||||
try:
|
||||
r = _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
|
||||
if r.get("account") == account:
|
||||
return r
|
||||
except HTTPException:
|
||||
pass
|
||||
return {"account": account, "is_admin": False, "dept": "", "nickname": ""}
|
||||
|
||||
|
||||
class _LoginIn(BaseModel):
|
||||
account: str
|
||||
password: str
|
||||
|
||||
|
||||
@app.post("/api/admin/login")
|
||||
def admin_login(b: _LoginIn, response: Response) -> dict:
|
||||
"""统一账户登录:校验账号+密码通过后,写会话 cookie 记为当前登录账号。"""
|
||||
try:
|
||||
r = _cp_call("POST", "/api/admin/auth",
|
||||
headers={"X-Admin-User": b.account.strip(),
|
||||
**({"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}),
|
||||
"Content-Type": "application/json"},
|
||||
json={"account": b.account, "password": b.password})
|
||||
except HTTPException as e:
|
||||
raise e
|
||||
if not r.get("ok"):
|
||||
return r
|
||||
token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[token] = (b.account.strip(), time.time())
|
||||
_sess_persist()
|
||||
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())
|
||||
_sess_persist()
|
||||
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 {}))
|
||||
|
||||
|
||||
# ==================== v3 钉钉直连接登录:/api/auth/dingtalk + /auth/done(§2.1,待 §0 验证后实测) ====================
|
||||
# 浏览器跳转模型:壳生成 state → 打开钉钉授权URL(redirect_uri=http://localhost:8799/auth/done)
|
||||
# → 用户本机浏览器带回 code+state → 壳校验 state → POST 云端 /auth/exchange{code} 换工号+云端token → 建本机会话。
|
||||
# 云端只参与换 token,AppSecret 不出云端;会话存本机、重启不掉(见上方 _SESS 持久化)。
|
||||
_LOGIN_STATE_TTL = 5 * 60 # state 有效期(秒)
|
||||
_LOGIN_STATES: dict[str, float] = {} # state -> expiry(待回跳校验)
|
||||
_LOGIN_LOCK = threading.Lock()
|
||||
# account -> 最近云端会话 token(7 天,供壳后续调 /api/plugins 用 Bearer,见 §2.2)
|
||||
_ACCT_CLOUD_TOKEN: dict[str, str] = {}
|
||||
|
||||
|
||||
def _login_state_new() -> str:
|
||||
with _LOGIN_LOCK:
|
||||
_now = time.time()
|
||||
for s in [s for s, e in _LOGIN_STATES.items() if e < _now]:
|
||||
_LOGIN_STATES.pop(s, None)
|
||||
state = secrets.token_urlsafe(24)
|
||||
_LOGIN_STATES[state] = _now + _LOGIN_STATE_TTL
|
||||
return state
|
||||
|
||||
|
||||
def _login_state_take(state: str) -> bool:
|
||||
with _LOGIN_LOCK:
|
||||
exp = _LOGIN_STATES.pop(state, None)
|
||||
return bool(exp and exp >= time.time())
|
||||
|
||||
|
||||
def _auth_done_page(text: str) -> HTMLResponse:
|
||||
return HTMLResponse(f"""<!doctype html><html><head><meta charset="utf-8"><title>登录</title></head>
|
||||
<body style="font-family:sans-serif;text-align:center;padding:60px">
|
||||
<p>{text}</p><p><a href="/">返回</a></p></body></html>""")
|
||||
|
||||
|
||||
@app.get("/api/auth/dingtalk")
|
||||
def auth_dingtalk_url() -> dict:
|
||||
"""生成并返回钉钉扫码授权 URL(redirect_uri=本机 /auth/done)。前端「钉钉登录」当前窗口跳转该 URL。"""
|
||||
if not DINGTALK_APP_KEY:
|
||||
raise HTTPException(503, "未配置钉钉开放平台应用(DINGTALK_APP_KEY)")
|
||||
if not CONTROLPLANE_URL:
|
||||
raise HTTPException(503, "未配置中心机地址(CONTROLPLANE_URL)")
|
||||
state = _login_state_new()
|
||||
redirect_uri = f"http://localhost:{PORT}/auth/done"
|
||||
login_url = "https://login.dingtalk.com/oauth2/challenge.htm?" + urlencode({
|
||||
"redirect_uri": redirect_uri,
|
||||
"response_type": "code",
|
||||
"client_id": DINGTALK_APP_KEY,
|
||||
"scope": "openid",
|
||||
"prompt": "consent",
|
||||
"state": state})
|
||||
return {"url": login_url, "state": state}
|
||||
|
||||
|
||||
@app.get("/auth/done")
|
||||
def auth_done(code: str = "", state: str = "", error: str = "") -> Response:
|
||||
"""钉钉回跳落点(浏览器):收 code+state → 校验 state → 云端 /auth/exchange 换工号 → 建本机会话。
|
||||
|
||||
成功后写会话 cookie 并 302 回主页;任何失败给 HTML 提示,不建立会话。
|
||||
"""
|
||||
if error:
|
||||
return _auth_done_page("钉钉登录被取消或失败,请返回重试。")
|
||||
if not (code and state) or not _login_state_take(state):
|
||||
return _auth_done_page("登录状态无效或已过期,请返回重新扫码。")
|
||||
try:
|
||||
info = _cp_call("POST", "/auth/exchange", json={"code": code})
|
||||
except HTTPException as e:
|
||||
return _auth_done_page(f"登录失败:{e.detail}")
|
||||
account = (info.get("account") or "").strip()
|
||||
if not account or not info.get("exists"):
|
||||
return _auth_done_page("账号未开通或未解析到有效工号,请联系管理员。")
|
||||
# 建本机会话(写内存+落盘+set-cookie),并存云端 token 供后续调云端 API(§2.2)。
|
||||
_token = uuid.uuid4().hex
|
||||
with _SESS_LOCK:
|
||||
_SESS[_token] = (account, time.time())
|
||||
_sess_persist()
|
||||
if info.get("token"):
|
||||
_ACCT_CLOUD_TOKEN[account] = info["token"]
|
||||
resp = RedirectResponse("/")
|
||||
resp.set_cookie(SESSION_COOKIE, _token, httponly=True, samesite="lax")
|
||||
if CONTROLPLANE_URL:
|
||||
try:
|
||||
_sync_licensing(account)
|
||||
except Exception as _exc: # noqa: BLE001 同步失败不影响登录
|
||||
_LOGGER.warning("登录后同步离线授权票据失败:%s", _exc)
|
||||
return resp
|
||||
|
||||
|
||||
# ==================== 钉钉真实扫码:扫码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 与内存会话。"""
|
||||
token = request.cookies.get(SESSION_COOKIE, "")
|
||||
with _SESS_LOCK:
|
||||
_SESS.pop(token, None)
|
||||
_sess_persist()
|
||||
response.delete_cookie(SESSION_COOKIE)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
class _PwdIn(BaseModel):
|
||||
account: str
|
||||
old_password: str
|
||||
new_password: str
|
||||
|
||||
|
||||
@app.post("/api/admin/password")
|
||||
def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/password",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=b.model_dump())
|
||||
|
||||
|
||||
@app.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
|
||||
|
||||
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 CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
headers = {"X-API-Token": CONTROLPLANE_TOKEN} if CONTROLPLANE_TOKEN else {}
|
||||
try:
|
||||
r = requests.get(f"{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 CONTROLPLANE_URL:
|
||||
return None
|
||||
import requests
|
||||
|
||||
try:
|
||||
r = requests.get(f"{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", [])}
|
||||
|
||||
|
||||
@app.get("/api/meta")
|
||||
def meta(request: Request) -> dict:
|
||||
account = _sess_account(request)
|
||||
# 插件清单仅对已登录账号可见(未登录不泄露插件元数据);
|
||||
# 已登录且能按云端权限(authorization)解析时,仅返回该员工被授权插件(§2.2 权限隔离)。
|
||||
if account:
|
||||
allowed = _cloud_plugin_ids(account)
|
||||
plugins = ([_plugin_schema(p) for p in PLUGINS if p.id in allowed]
|
||||
if allowed is not None # 云端按员工返回了授权集(也可能是空集=无权限)
|
||||
else [_plugin_schema(p) for p in PLUGINS]) # 无 token/云端不可达 → 离线兜底全量
|
||||
else:
|
||||
plugins = []
|
||||
allowed_plats = _account_allowed_platforms(account) if account else None
|
||||
platforms = [{"id": pid, "label": m["label"],
|
||||
"online": platform_auth.is_online(pid),
|
||||
# 已登录时按账号白名单;未登录/中心机不可达默认展示
|
||||
"allowed": (pid in allowed_plats) if allowed_plats is not None else True}
|
||||
for pid, m in PLATFORMS.items()]
|
||||
return {
|
||||
# controlplane_url 供前端管理员跳转控制面;未配置时为空(前端隐藏管理入口)
|
||||
"controlplane": CONTROLPLANE_URL,
|
||||
"appName": "37du 自动化工作台",
|
||||
"dingtalkScan": bool(DINGTALK_APP_KEY),
|
||||
"platforms": platforms,
|
||||
"plugins": plugins,
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/login")
|
||||
def login(pid: str, request: Request) -> dict:
|
||||
"""真实登录:需先通过统一账户登录(有会话),且该账号已获中心机平台授权。"""
|
||||
account = _require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
allowed = _account_allowed_platforms(account)
|
||||
if allowed is None:
|
||||
raise HTTPException(503, "控制面不可达,无法校验平台权限")
|
||||
if pid not in allowed:
|
||||
raise HTTPException(403, "无该平台访问权限,请联系管理员在控制面授权")
|
||||
return platform_auth.login(pid)
|
||||
|
||||
|
||||
@app.post("/api/platforms/{pid}/logout")
|
||||
def platform_logout(pid: str, request: Request) -> dict:
|
||||
"""登出平台:清除共享 cookies,使该平台登录态失效(需已登录统一账户)。"""
|
||||
_require_login(request)
|
||||
plat = PLATFORMS.get(pid)
|
||||
if not plat:
|
||||
raise HTTPException(404, "平台不存在")
|
||||
return platform_auth.logout(pid)
|
||||
|
||||
|
||||
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[2]
|
||||
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 ALLOWED is not None: # 子进程加载与宿主一致的白名单,杜绝越权 import
|
||||
cmd += ["--allowed", ",".join(sorted(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()
|
||||
_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"))
|
||||
_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)已强制终止"
|
||||
_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})且未返回结果"
|
||||
_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)
|
||||
try:
|
||||
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 不被并发争抢
|
||||
gate = _ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
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()
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
@app.get("/api/runs/{run_id}")
|
||||
def get_run(run_id: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
with RUN_LOCK:
|
||||
run = RUNS.get(run_id)
|
||||
if not run or run.get("account") != account: # 仅属主可读运行结果
|
||||
raise HTTPException(404, "运行不存在")
|
||||
return run
|
||||
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def ws(websocket: WebSocket):
|
||||
if not _sess_account(websocket): # WS 握手需有效统一账户会话
|
||||
await websocket.close(code=1008)
|
||||
return
|
||||
await HUB.connect(websocket)
|
||||
|
||||
|
||||
if DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
|
||||
if config.DIST.exists():
|
||||
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
|
||||
|
||||
|
||||
def _port_free(port: int) -> bool:
|
||||
@@ -926,5 +73,5 @@ def _port_free(port: int) -> bool:
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
print(f"[webhost] port {PORT} free = {_port_free(PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=PORT, log_level="info")
|
||||
print(f"[webhost] port {config.PORT} free = {_port_free(config.PORT)}")
|
||||
uvicorn.run(app, host="127.0.0.1", port=config.PORT, log_level="info")
|
||||
Reference in New Issue
Block a user