Files
37duAutomation/webhost/backend/main.py
T
puddy 3f901d3882 feat: 搭建控制面管理前端并剥离底座管理功能
1. 新增controlplane/frontend Vue3管理前端,实现登录、账号CRUD、插件上传/管理、权限授权
2. 为controlplane/app.py添加CORS中间件并挂载前端静态产物
3. 重构环境变量加载,统一使用app/common/env.load_app_env()
4. 剥离webhost/的管理UI与代理接口,仅保留基础登录能力
5. 新增环境隔离规范文档与架构蓝图说明
2026-09-09 17:10:12 +08:00

403 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""webhost 宿主:FastAPI 后端。
- 承载平台登录态(复用 desktop/shared 的共享登录态单一真源,真实登录/校验)
- 场景插件注册表 + 表单 schema
- 执行 run 到 worker 线程,经 /ws 广播 日志/进度/完成
- 挂载前端构建产物(frontend/dist)实现单产物
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
import socket
import subprocess
import sys
import threading
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.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from webhost.backend import auth as platform_auth
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"
_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", "")
# 统一账户体系为真源:登录态由后端 cookie 会话维护(账号在统一后端 accounts 表)。
# cookie 会话:token -> account;登录后 set-cookie,进程内保持,供代理转发账号。
SESSION_COOKIE = "cp_session"
_SESS: dict[str, str] = {}
_SESS_LOCK = threading.Lock()
def _sess_account(request: Request) -> str:
"""从请求 cookie 会话解析当前登录账号;未登录返回空串。"""
token = request.cookies.get(SESSION_COOKIE, "")
with _SESS_LOCK:
return _SESS.get(token, "")
def _require_login(request: Request) -> str:
"""业务执行接口的统一登录门槛:未登录统一账户(无有效会话 cookie)则拒绝。"""
account = _sess_account(request)
if not account:
raise HTTPException(401, "未登录:请先登录统一账户")
return account
# 平台登录态:标签/展示名来自 auth,在线状态实时校验(非内存假状态)
PLATFORMS: dict = {p["id"]: {"id": p["id"], "label": p["label"]}
for p in platform_auth.platforms()}
# 运行会话:run_id -> {status, result, error}
RUNS: dict = {}
RUN_LOCK = threading.Lock()
MAX_RUNS = 50 # 运行历史上限,超出丢弃最旧记录,避免内存无限增长
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
@asynccontextmanager
async def lifespan(app: FastAPI):
HUB.bind(asyncio.get_running_loop())
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
load_plugins(_resolve_allowed())
yield
app = FastAPI(title="37du Web Host", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
@app.get("/api/admin/me")
def admin_me(request: Request) -> dict:
"""当前登录账号是否为管理员(会话 cookie)。统一后端不可达时视为非管理员。"""
account = _sess_account(request)
if not account:
return {"account": "", "is_admin": False}
try:
return _cp_call("GET", "/api/admin/me", headers=_cp_headers(request))
except HTTPException:
return {"account": account, "is_admin": False}
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()
response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
return {**r, "account": b.account.strip()}
@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)
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:
return {"id": p.id, "name": p.name, "version": p.version,
"description": p.description, "uses_month": getattr(p, "uses_month", False),
"fields": p.fields}
@app.get("/api/meta")
def meta() -> dict:
plugins = [_plugin_schema(p) for p in PLUGINS]
platforms = [{"id": pid, "label": m["label"], "online": platform_auth.is_online(pid)}
for pid, m in PLATFORMS.items()]
return {"appName": "37du 业务场景工具集", "platforms": platforms, "plugins": plugins}
@app.post("/api/platforms/{pid}/login")
def login(pid: str, request: Request) -> dict:
"""真实登录:需先通过统一账户登录(有会话)。复用有效 cookies 或浏览器自动化登录(滑块)。"""
_require_login(request)
plat = PLATFORMS.get(pid)
if not plat:
raise HTTPException(404, "平台不存在")
return platform_auth.login(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
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))})
try:
proc = subprocess.Popen(
[sys.executable, "-u", str(runner), "--plugin", plugin.id,
"--run", run_id],
cwd=str(root), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True, encoding="utf-8",
errors="replace",
)
except Exception as e: # noqa: BLE001 子进程拉起失败
with RUN_LOCK:
RUNS[run_id] = {"status": "error", "result": None,
"error": f"拉起执行子进程失败: {e}"}
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
"error": f"拉起执行子进程失败: {e}"})
return
_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:
proc.kill()
proc.wait(timeout=5)
except (subprocess.TimeoutExpired, OSError):
pass
with _rlock:
ev = dict(_result)
if ev:
ok = bool(ev.get("ok"))
with RUN_LOCK:
RUNS[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)已强制终止"
with RUN_LOCK:
RUNS[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})且未返回结果"
with RUN_LOCK:
RUNS[run_id] = {"status": "error", "result": None, "error": msg}
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": msg})
@app.post("/api/runs", status_code=202)
def start_run(req: RunReq, request: Request) -> dict:
_require_login(request)
try:
plugin = PLUGINS.find(req.plugin_id)
except KeyError:
raise HTTPException(404, "插件不存在")
run_id = uuid.uuid4().hex
with RUN_LOCK:
if len(RUNS) >= MAX_RUNS:
RUNS.pop(next(iter(RUNS))) # dict 有序:弹出最老的记录
RUNS[run_id] = {"status": "running", "result": None, "error": None}
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
"at": datetime.now().strftime("%H:%M:%S")})
threading.Thread(target=_run_target, args=(plugin, req.fields, run_id),
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:
_require_login(request)
with RUN_LOCK:
run = RUNS.get(run_id)
if not run:
raise HTTPException(404, "运行不存在")
return run
@app.websocket("/ws")
async def ws(websocket: WebSocket):
await HUB.connect(websocket)
if DIST.exists():
app.mount("/", StaticFiles(directory=str(DIST), html=True), name="web")
def _port_free(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("127.0.0.1", port)) != 0
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")