feat: 搭建控制面管理前端并剥离底座管理功能
1. 新增controlplane/frontend Vue3管理前端,实现登录、账号CRUD、插件上传/管理、权限授权 2. 为controlplane/app.py添加CORS中间件并挂载前端静态产物 3. 重构环境变量加载,统一使用app/common/env.load_app_env() 4. 剥离webhost/的管理UI与代理接口,仅保留基础登录能力 5. 新增环境隔离规范文档与架构蓝图说明
This commit is contained in:
+124
-74
@@ -9,16 +9,19 @@
|
||||
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, File, HTTPException, Request, Response, UploadFile, WebSocket
|
||||
from fastapi import FastAPI, HTTPException, Request, Response, WebSocket
|
||||
from pydantic import BaseModel
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -26,13 +29,34 @@ 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 为注册表,启动时显式填装
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
|
||||
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("/")
|
||||
@@ -199,71 +223,8 @@ def admin_password(b: _PwdIn, request: Request) -> dict:
|
||||
|
||||
@app.get("/api/admin/overview")
|
||||
def admin_overview(request: Request) -> dict:
|
||||
return _cp_call("GET", "/api/admin/overview", headers=_cp_headers(request))
|
||||
|
||||
|
||||
@app.get("/api/admin/admins")
|
||||
def admin_list(request: Request) -> dict:
|
||||
return _cp_call("GET", "/api/admin/admins", headers=_cp_headers(request))
|
||||
|
||||
|
||||
@app.get("/api/admin/accounts")
|
||||
def admin_accounts(request: Request) -> dict:
|
||||
return _cp_call("GET", "/api/admin/accounts", headers=_cp_headers(request))
|
||||
|
||||
|
||||
@app.post("/api/admin/account")
|
||||
def admin_account_create(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account/update")
|
||||
def admin_account_update(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account/update",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account/reset_pwd")
|
||||
def admin_account_reset(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account/reset_pwd",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account/delete")
|
||||
def admin_account_delete(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account/delete",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/plugin/delete")
|
||||
def admin_plugin_delete(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/plugin/delete",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/account_plugins")
|
||||
def admin_grant(body: dict, request: Request) -> dict:
|
||||
return _cp_call("POST", "/api/admin/account_plugins",
|
||||
headers={**_cp_headers(request), "Content-Type": "application/json"},
|
||||
json=body)
|
||||
|
||||
|
||||
@app.post("/api/admin/pkg")
|
||||
async def admin_upload(plugin_id: str, version: str, name: str = "",
|
||||
upload: UploadFile = File(...), request: Request = None) -> dict:
|
||||
"""前端上传插件包:接收文件并转发给统一后端 multipart 发布。"""
|
||||
content = await upload.read()
|
||||
files = {"upload": (upload.filename or "pkg.zip", content,
|
||||
upload.content_type or "application/octet-stream")}
|
||||
params = {"plugin_id": plugin_id, "name": name or plugin_id, "version": version}
|
||||
return _cp_call("POST", "/api/admin/pkg", params=params,
|
||||
headers=_cp_headers(request), files=files)
|
||||
"""管理台一次性拉取:全部插件 + 账号 + 管理员。管理入口已在中心机控制面,底座侧置空兜底。"""
|
||||
return {"plugins": [], "accounts": [], "admins": []}
|
||||
|
||||
|
||||
def _plugin_schema(p) -> dict:
|
||||
@@ -291,16 +252,105 @@ def login(pid: str, request: Request) -> dict:
|
||||
|
||||
|
||||
def _run_target(plugin, fields: dict, run_id: str) -> None:
|
||||
ctx = RunContext(HUB, run_id=run_id, plugin_id=plugin.id, auth=platform_auth)
|
||||
"""进程级隔离执行插件:拉起独立 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:
|
||||
result = plugin.run(fields, ctx)
|
||||
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": "done", "result": result, "error": None}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": True})
|
||||
except Exception as e: # noqa: BLE001 全局兜底,推送失败给前端
|
||||
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": "error", "result": None, "error": str(e)}
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False, "error": str(e)})
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""插件执行子进程入口(进程级隔离)。
|
||||
|
||||
由底座 main 以 `python -m webhost.backend.plugin_runner --plugin <id>` 拉起,
|
||||
fields 经 stdin(单行 JSON) 传入,插件 `run()` 在本子进程执行:
|
||||
- 死循环 / sys.exit() / 内存爬升 不会拖垮底座(底座可超时 kill 本进程)
|
||||
- log / progress 经 stdout 输出 JSON 行,底座解析后转发 WebSocket
|
||||
- get_session / get_user_id 在本进程内直接读取共享 cookie 文件重建,不依赖主进程
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
|
||||
def _bootstrap_paths() -> str:
|
||||
"""把项目根插入 sys.path 并 chdir,保证 desktop/ 与 webhost/ 可被 import。"""
|
||||
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
if root not in sys.path:
|
||||
sys.path.insert(0, root)
|
||||
return root
|
||||
|
||||
|
||||
_ROOT = _bootstrap_paths()
|
||||
try:
|
||||
os.chdir(_ROOT)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def _emit(obj: dict) -> None:
|
||||
"""写一行 JSON 到协议通道(原始 stdout)。插件 print 已改道 stderr,不污染协议。"""
|
||||
try:
|
||||
_PROTO.write(json.dumps(obj, ensure_ascii=False) + "\n")
|
||||
_PROTO.flush()
|
||||
except Exception: # noqa: BLE001 通道已关则静默
|
||||
pass
|
||||
|
||||
|
||||
def _run() -> int:
|
||||
# 协议通道 = 原始 sys.stdout(fd1);把插件的 print 改道到 stderr,防止污染协议行
|
||||
global _PROTO
|
||||
_PROTO = sys.stdout
|
||||
sys.stdout = sys.stderr
|
||||
|
||||
from webhost.backend.plugins import PLUGINS, load_plugins # 延迟 import(需已就位 sys.path)
|
||||
from webhost.backend.plugins.base import RunContext
|
||||
from webhost.backend import auth as platform_auth
|
||||
|
||||
# 解析参数
|
||||
args = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
|
||||
plugin_id = args.get("--plugin") or (sys.argv[sys.argv.index("--plugin") + 1]
|
||||
if "--plugin" in sys.argv else "")
|
||||
if not plugin_id:
|
||||
_emit({"ev": "result", "ok": False, "error": "缺少 --plugin 参数"})
|
||||
return 2
|
||||
|
||||
# fields 经 stdin 传入(单行 JSON)
|
||||
fields: dict = {}
|
||||
try:
|
||||
_line = sys.stdin.readline().strip()
|
||||
if _line:
|
||||
fields = json.loads(_line) or {}
|
||||
except Exception as _e: # noqa: BLE001
|
||||
fields = {}
|
||||
|
||||
class _ChildContext(RunContext):
|
||||
"""子进程版上下文:log/progress 经 stdout 回传;登录态在本进程重建。"""
|
||||
|
||||
def __init__(self, run_id: str, plugin_id: str, auth):
|
||||
super().__init__(hub=None, run_id=run_id, plugin_id=plugin_id, auth=auth)
|
||||
|
||||
def log(self, msg: str, level: str = "INFO"):
|
||||
_emit({"ev": "log", "level": level, "msg": str(msg)})
|
||||
|
||||
def progress(self, pct: int):
|
||||
_emit({"ev": "progress", "pct": int(max(0, min(100, pct)))})
|
||||
|
||||
try:
|
||||
load_plugins()
|
||||
plugin = PLUGINS.find(plugin_id)
|
||||
ctx = _ChildContext(run_id=args.get("--run", ""), plugin_id=plugin_id,
|
||||
auth=platform_auth)
|
||||
result = plugin.run(fields, ctx)
|
||||
_emit({"ev": "result", "ok": True, "result": result})
|
||||
return 0
|
||||
except KeyError:
|
||||
_emit({"ev": "result", "ok": False, "error": f"插件未找到: {plugin_id}"})
|
||||
return 3
|
||||
except Exception as _e: # noqa: BLE001 插件顶层兜底
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
_emit({"ev": "result", "ok": False, "error": str(_e)})
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(_run())
|
||||
Reference in New Issue
Block a user