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)
|
||||
|
||||
Reference in New Issue
Block a user