1. 重构controlplane与webhost后端的包结构,按领域拆分模块到core/apis子包 2. 移动并整理工具脚本到tools子目录,统一管理运维脚本 3. 重构插件运行时、调度、作业管理等核心模块到core子包 4. 更新AGENTS.md文档,明确各代码形态的组织规范 5. 清理重复的旧文件与冗余代码
508 lines
27 KiB
Python
508 lines
27 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""管理侧路由(写操作,需正确 token):账号 CRUD / 插件上传与维护 / 授权 / 看板 / 审计 / 运行记录。
|
||
|
||
所有写操作均以 `_require_admin`(X-API-Token + X-Admin-Token 管理员票据)把关。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
from datetime import datetime, timedelta
|
||
|
||
from fastapi import APIRouter, File, Header, HTTPException, Query, UploadFile
|
||
|
||
from controlplane import config, schemas
|
||
from controlplane.core.auth import _require_admin
|
||
from controlplane.core.crypto import _hash_password
|
||
from controlplane.core.db import _audit, _db, _now
|
||
from controlplane.core.pkgutil import (
|
||
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
|
||
_validate_pkg_zip, _version_key,
|
||
)
|
||
|
||
router = APIRouter()
|
||
|
||
|
||
# ==================== 账号 CRUD(统一账户,含部门;仅管理员可操作) ====================
|
||
@router.get("/api/admin/accounts")
|
||
def admin_accounts(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""全部账号(含部门/管理员标记/已授权插件/可登录平台)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT account, is_admin, dept, nickname, dingtalk_uid, must_change_pwd "
|
||
"FROM accounts ORDER BY account")]
|
||
for a in rows:
|
||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||
a["grants"] = [dict(r) for r in conn.execute(
|
||
"SELECT plugin_id, can_download, can_run FROM plugin_grants WHERE account = ?",
|
||
(a["account"],))]
|
||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||
return {"accounts": rows}
|
||
|
||
|
||
@router.post("/api/admin/account")
|
||
def admin_account_create(a: schemas.AccountCreateIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""新建账号:密码必填,可指定部门/昵称/是否管理员。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = a.account.strip()
|
||
if not account or not a.password:
|
||
raise HTTPException(400, "account 与 password 必填")
|
||
with _db() as conn:
|
||
exists = conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone()
|
||
if exists:
|
||
raise HTTPException(400, f"账号 {account} 已存在")
|
||
_hex, _salt = _hash_password(a.password)
|
||
with _db() as conn:
|
||
conn.execute("INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname) "
|
||
"VALUES (?, ?, ?, ?, ?, ?)",
|
||
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
|
||
(a.nickname or "").strip()))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
|
||
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
|
||
|
||
|
||
@router.post("/api/admin/account/update")
|
||
def admin_account_update(a: schemas.AccountUpdateIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""更新账号:改部门 / 昵称 / 授予或撤销管理员。"""
|
||
login = _require_admin(x_admin_token, x_api_token)
|
||
account = a.account.strip()
|
||
if not account:
|
||
raise HTTPException(400, "account 必填")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
if a.dept is not None:
|
||
conn.execute("UPDATE accounts SET dept = ? WHERE account = ?",
|
||
((a.dept or "").strip(), account))
|
||
if a.nickname is not None:
|
||
conn.execute("UPDATE accounts SET nickname = ? WHERE account = ?",
|
||
((a.nickname or "").strip(), account))
|
||
if a.is_admin is not None:
|
||
# 禁止撤销自己的管理员身份,避免把自己锁在门外
|
||
if a.is_admin:
|
||
conn.execute("UPDATE accounts SET is_admin = 1 WHERE account = ?", (account,))
|
||
else:
|
||
conn.execute("UPDATE accounts SET is_admin = 0 WHERE account = ? AND account <> ?",
|
||
(account, login))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
@router.post("/api/admin/account/reset_pwd")
|
||
def admin_account_reset(r: schemas.AccountResetIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""管理员重置任意账号密码(无需原密码)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = r.account.strip()
|
||
if not account or not r.new_password:
|
||
raise HTTPException(400, "account 与新密码必填")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
_hex, _salt = _hash_password(r.new_password)
|
||
conn.execute("UPDATE accounts SET password_hash = ?, salt = ? WHERE account = ?",
|
||
(_hex, _salt, account))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
@router.post("/api/admin/account/delete")
|
||
def admin_account_delete(d: schemas.AccountDelIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""删除账号:不可删除自己;连带清除其插件授权。"""
|
||
login = _require_admin(x_admin_token, x_api_token)
|
||
account = d.account.strip()
|
||
if not account:
|
||
raise HTTPException(400, "account 必填")
|
||
if account == login:
|
||
raise HTTPException(400, "不能删除当前登录的账号")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在")
|
||
conn.execute("DELETE FROM accounts WHERE account = ?", (account,))
|
||
conn.execute("DELETE FROM account_plugins WHERE account = ?", (account,))
|
||
conn.commit()
|
||
return {"ok": True, "account": account}
|
||
|
||
|
||
# ==================== 授权 / 插件维护 ====================
|
||
@router.post("/api/admin/account_plugins")
|
||
def admin_grant(g: schemas.GrantIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""授予/撤销某账号对某插件的权限。granted=True 授,False 撤;同时维护插件级授权表。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = g.account.strip()
|
||
plugin_id = g.plugin_id.strip()
|
||
if not account or not plugin_id:
|
||
raise HTTPException(400, "account 与 plugin_id 不能为空")
|
||
with _db() as conn:
|
||
if g.granted:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO account_plugins(account, plugin_id) VALUES (?, ?)",
|
||
(account, plugin_id))
|
||
conn.execute(
|
||
"INSERT INTO plugin_grants(account, plugin_id, can_download, can_run) "
|
||
"VALUES (?, ?, ?, ?) "
|
||
"ON CONFLICT(account, plugin_id) DO UPDATE SET "
|
||
"can_download = excluded.can_download, can_run = excluded.can_run",
|
||
(account, plugin_id, int(g.can_download), int(g.can_run)))
|
||
else:
|
||
conn.execute("DELETE FROM account_plugins WHERE account = ? AND plugin_id = ?",
|
||
(account, plugin_id))
|
||
conn.execute("DELETE FROM plugin_grants WHERE account = ? AND plugin_id = ?",
|
||
(account, plugin_id))
|
||
conn.commit()
|
||
_audit(account, "grant" if g.granted else "revoke-grant", plugin_id,
|
||
f"can_download={g.can_download},can_run={g.can_run}")
|
||
return {"ok": True, "account": account, "plugin_id": plugin_id, "granted": g.granted}
|
||
|
||
|
||
@router.post("/api/admin/account_platforms")
|
||
def admin_platform_grant(g: schemas.PlatformGrantIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""授予或撤销某账号对某平台的登录权限。granted=True 授,False 撤。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
account = g.account.strip()
|
||
platform_id = g.platform_id.strip()
|
||
if not account or not platform_id:
|
||
raise HTTPException(400, "account 与 platform_id 不能为空")
|
||
with _db() as conn:
|
||
if g.granted:
|
||
if not conn.execute("SELECT 1 FROM accounts WHERE account = ?", (account,)).fetchone():
|
||
raise HTTPException(400, f"账号 {account} 不存在,请先建号")
|
||
conn.execute(
|
||
"INSERT OR IGNORE INTO account_platforms(account, platform_id) VALUES (?, ?)",
|
||
(account, platform_id))
|
||
else:
|
||
conn.execute("DELETE FROM account_platforms WHERE account = ? AND platform_id = ?",
|
||
(account, platform_id))
|
||
conn.commit()
|
||
return {"ok": True, "account": account, "platform_id": platform_id, "granted": g.granted}
|
||
|
||
|
||
@router.post("/api/admin/pkg")
|
||
async def admin_upload_plugin(upload: UploadFile = File(...),
|
||
plugin_id: str = Query(...), name: str = Query(...),
|
||
version: str = Query(...),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""上传并发布插件包:完整性校验 → 存盘 → 登记版本 → 更新最新版 → 仅保留最近 3 个版本。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
plugin_id = plugin_id.strip()
|
||
name = name.strip() or plugin_id
|
||
version = version.strip()
|
||
if not plugin_id or not version:
|
||
raise HTTPException(400, "plugin_id 与 version 不能为空")
|
||
# 只允许安全字符(防止拼进文件路径造成目录穿越)
|
||
if not _SAFE_NAME_RE.match(plugin_id) or not _SAFE_NAME_RE.match(version):
|
||
raise HTTPException(400, "plugin_id/version 仅允许字母数字及 . _ -")
|
||
filename = f"{plugin_id}_v{version}.zip"
|
||
target = config.PKG_DIR / filename
|
||
content = await upload.read()
|
||
if not content:
|
||
raise HTTPException(400, "上传内容为空")
|
||
_validate_pkg_zip(content)
|
||
|
||
# manifest 为插件契约权威来源:plugin.json 内 id 与路径 plugin_id 不一致时拒绝,
|
||
# 否则以 manifest.metadata 覆盖 name/category/icon/description 并整份入库。
|
||
manifest = _extract_manifest(content)
|
||
if manifest:
|
||
mid = str((manifest.get("id") or "")).strip()
|
||
if mid and mid != plugin_id:
|
||
raise HTTPException(400, f"plugin.json 内 id「{mid}」与路径 plugin_id「{plugin_id}」不一致")
|
||
name = str(manifest.get("name") or name).strip() or plugin_id
|
||
manifest_json = json.dumps(manifest, ensure_ascii=False) if manifest else "{}"
|
||
|
||
target.write_bytes(content)
|
||
pkg_sha256 = hashlib.sha256(content).hexdigest() # 供部署端装包后防篡改校验
|
||
|
||
with _db() as conn:
|
||
conn.execute(
|
||
"INSERT INTO plugins(id, name, latest_version, description, category, icon, manifest) "
|
||
"VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "
|
||
"name = excluded.name, manifest = excluded.manifest"
|
||
+ (", description = excluded.description" if manifest else "")
|
||
+ (", category = excluded.category" if manifest else "")
|
||
+ (", icon = excluded.icon" if manifest else ""),
|
||
(plugin_id, name, version,
|
||
(manifest or {}).get("description", ""),
|
||
(manifest or {}).get("category", ""),
|
||
(manifest or {}).get("icon", ""),
|
||
manifest_json))
|
||
conn.execute(
|
||
"INSERT INTO plugin_versions(plugin_id, version, filename, uploaded_at, sha256) "
|
||
"VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin_id, version) DO UPDATE SET "
|
||
"filename = excluded.filename, uploaded_at = excluded.uploaded_at, sha256 = excluded.sha256",
|
||
(plugin_id, version, filename, _now(), pkg_sha256))
|
||
cur = conn.execute("SELECT latest_version FROM plugins WHERE id = ?", (plugin_id,))
|
||
if _version_key(cur.fetchone()["latest_version"]) < _version_key(version):
|
||
conn.execute("UPDATE plugins SET latest_version = ? WHERE id = ?", (version, plugin_id))
|
||
stale_files = _prune_versions(conn, plugin_id)
|
||
conn.commit()
|
||
for fn in stale_files: # 超出保留数的旧版本:清 DB 记录 + 清磁盘包
|
||
try:
|
||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
return {"ok": True, "plugin_id": plugin_id, "version": version, "filename": filename}
|
||
|
||
|
||
@router.post("/api/admin/plugin/delete")
|
||
def admin_plugin_delete(d: schemas.PluginDelIn,
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""删除插件:连带删除其全部版本记录、授权,并清理磁盘包文件。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
plugin_id = d.plugin_id.strip()
|
||
if not plugin_id:
|
||
raise HTTPException(400, "plugin_id 必填")
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (plugin_id,)).fetchone():
|
||
raise HTTPException(400, f"插件 {plugin_id} 不存在")
|
||
files = [dict(r)["filename"] for r in conn.execute(
|
||
"SELECT filename FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))]
|
||
conn.execute("DELETE FROM plugin_versions WHERE plugin_id = ?", (plugin_id,))
|
||
conn.execute("DELETE FROM plugins WHERE id = ?", (plugin_id,))
|
||
conn.execute("DELETE FROM account_plugins WHERE plugin_id = ?", (plugin_id,))
|
||
conn.commit()
|
||
for fn in files:
|
||
try:
|
||
(config.PKG_DIR / fn).unlink(missing_ok=True)
|
||
except OSError:
|
||
pass
|
||
return {"ok": True, "plugin_id": plugin_id}
|
||
|
||
|
||
@router.post("/api/admin/plugin/patch")
|
||
def admin_plugin_patch(d: schemas.PluginPatchIn,
|
||
plugin_id: str = Query(...),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""更新插件元信息/状态/强制更新配置。
|
||
|
||
status: published=正常 / disabled=禁用(停止发布) / revoked=下架(拒绝运行)。
|
||
force_min_version + force_deadline 组合开启强制更新(deadline 已过联线拒启旧版);
|
||
clear_force=True 清除强制更新;仅给其一且未 clear 则报 400。
|
||
"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
pid = plugin_id.strip()
|
||
if not pid:
|
||
raise HTTPException(400, "plugin_id 必填")
|
||
fields = []
|
||
vals = []
|
||
if d.name is not None and d.name.strip():
|
||
fields.append("name = ?"); vals.append(d.name.strip())
|
||
if d.description:
|
||
fields.append("description = ?"); vals.append(d.description.strip())
|
||
if d.category:
|
||
fields.append("category = ?"); vals.append(d.category.strip())
|
||
if d.icon:
|
||
fields.append("icon = ?"); vals.append(d.icon.strip())
|
||
if d.status in ("published", "disabled", "revoked"):
|
||
fields.append("status = ?"); vals.append(d.status)
|
||
# 强制更新三态:成对开启 / clear_force 清除 / 仅给其一报错
|
||
if d.force_min_version and d.force_deadline:
|
||
fields.append("force_min_version = ?"); vals.append(d.force_min_version.strip())
|
||
fields.append("force_deadline = ?"); vals.append(d.force_deadline.strip())
|
||
elif (d.force_min_version or d.force_deadline) and not d.clear_force:
|
||
raise HTTPException(400, "强制更新需同时提供 force_min_version 与 force_deadline")
|
||
elif d.clear_force:
|
||
fields.append("force_min_version = NULL")
|
||
fields.append("force_deadline = NULL")
|
||
if not fields:
|
||
return {"ok": True} # 无更新项
|
||
vals.append(pid)
|
||
with _db() as conn:
|
||
if not conn.execute("SELECT 1 FROM plugins WHERE id = ?", (pid,)).fetchone():
|
||
raise HTTPException(400, f"插件 {pid} 不存在")
|
||
conn.execute(f"UPDATE plugins SET {', '.join(fields)} WHERE id = ?", vals)
|
||
conn.commit()
|
||
_audit("", "plugin-patch", pid, ", ".join(
|
||
f"{k.split(' ')[0]}={v}" for k, v in zip(fields, vals[:-1])))
|
||
return {"ok": True, "plugin_id": pid}
|
||
|
||
|
||
# ==================== 看板 / 审计 / 运行记录 ====================
|
||
@router.get("/api/admin/overview")
|
||
def admin_overview(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""管理台一次性拉取:全部插件(含元信息/状态/版本/被授权账号)+ 全部账号 + 管理员名单。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
plugins = [dict(r) for r in conn.execute(
|
||
"SELECT id, name, description, category, icon, status, latest_version, "
|
||
" force_min_version, force_deadline, manifest "
|
||
"FROM plugins ORDER BY id")]
|
||
for p in plugins:
|
||
m = _load_manifest(p.pop("manifest"))
|
||
p["manifest"] = m
|
||
p["capabilities"] = m.get("capabilities") or []
|
||
p["permissions"] = m.get("permissions") or {}
|
||
props = (m.get("fields") or {}).get("properties") or {}
|
||
p["field_count"] = len(props)
|
||
p["versions"] = [dict(r) for r in conn.execute(
|
||
"SELECT version, filename, sha256, uploaded_at FROM plugin_versions "
|
||
"WHERE plugin_id = ? ORDER BY version", (p["id"],))]
|
||
p["accounts"] = [dict(r)["account"] for r in conn.execute(
|
||
"SELECT account FROM account_plugins WHERE plugin_id = ?", (p["id"],))]
|
||
p["grants"] = {dict(r)["account"]: {"canDownload": bool(dict(r)["can_download"]),
|
||
"canRun": bool(dict(r)["can_run"])}
|
||
for r in conn.execute(
|
||
"SELECT account, can_download, can_run FROM plugin_grants "
|
||
"WHERE plugin_id = ?", (p["id"],))}
|
||
accounts = [dict(r) for r in conn.execute(
|
||
"SELECT account, is_admin, dept, nickname FROM accounts ORDER BY account")]
|
||
for a in accounts:
|
||
a["plugins"] = [dict(r)["plugin_id"] for r in conn.execute(
|
||
"SELECT plugin_id FROM account_plugins WHERE account = ?", (a["account"],))]
|
||
a["platforms"] = [dict(r)["platform_id"] for r in conn.execute(
|
||
"SELECT platform_id FROM account_platforms WHERE account = ?", (a["account"],))]
|
||
a["grants"] = {dict(r)["plugin_id"]: {"canDownload": bool(dict(r)["can_download"]),
|
||
"canRun": bool(dict(r)["can_run"])}
|
||
for r in conn.execute(
|
||
"SELECT plugin_id, can_download, can_run FROM plugin_grants "
|
||
"WHERE account = ?", (a["account"],))}
|
||
admins = [dict(r)["account"] for r in conn.execute(
|
||
"SELECT account FROM accounts WHERE is_admin = 1 ORDER BY account")]
|
||
return {"plugins": plugins, "accounts": accounts, "admins": admins}
|
||
|
||
|
||
@router.get("/api/admin/stats")
|
||
def admin_stats(x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""数据看板:账号/插件规模 + 运行统计(次数/时长/成败)+ 近 14 天趋势 + 排行。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
users = dict(conn.execute(
|
||
"SELECT (SELECT COUNT(*) FROM accounts) AS total, "
|
||
"(SELECT COUNT(*) FROM accounts WHERE is_admin = 1) AS admins, "
|
||
"(SELECT COUNT(DISTINCT account) FROM account_plugins) AS authorized").fetchone())
|
||
plugins = dict(conn.execute(
|
||
"SELECT (SELECT COUNT(*) FROM plugins) AS total, "
|
||
"(SELECT COUNT(*) FROM plugins WHERE status = 'published') AS published, "
|
||
"(SELECT COUNT(*) FROM plugins WHERE status = 'disabled') AS disabled, "
|
||
"(SELECT COUNT(*) FROM plugins WHERE status = 'revoked') AS revoked").fetchone())
|
||
runs = dict(conn.execute(
|
||
"SELECT (SELECT COUNT(*) FROM runtime_reports WHERE status = 'start') AS started, "
|
||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('done','success')) AS success, "
|
||
"(SELECT COUNT(*) FROM runtime_reports WHERE status IN ('error','failed')) AS failed, "
|
||
"(SELECT COALESCE(SUM(duration_sec),0) FROM runtime_reports) AS duration_sec, "
|
||
"(SELECT COUNT(DISTINCT account) FROM runtime_reports WHERE account <> '') AS active_users, "
|
||
"(SELECT COUNT(DISTINCT plugin_id) FROM runtime_reports WHERE plugin_id <> '') AS active_plugins").fetchone())
|
||
|
||
# 近 14 天运行趋势(按日:触发次数 / 成功 / 失败)
|
||
trend_rows = conn.execute(
|
||
"SELECT substr(at,1,10) AS day, "
|
||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS runs, "
|
||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed "
|
||
"FROM runtime_reports WHERE at >= date('now','-13 days') GROUP BY day ORDER BY day"
|
||
).fetchall()
|
||
trend_map = {r["day"]: r for r in trend_rows}
|
||
trend = []
|
||
day = datetime.now() - timedelta(days=13)
|
||
for _i in range(14):
|
||
key = day.strftime("%Y-%m-%d")
|
||
r = trend_map.get(key)
|
||
trend.append({"day": key[5:], "runs": int(r["runs"] or 0) if r else 0,
|
||
"success": int(r["success"] or 0) if r else 0,
|
||
"failed": int(r["failed"] or 0) if r else 0})
|
||
day = day + timedelta(days=1)
|
||
|
||
# 插件排行:按执行次数(以 status='start' 为一次完整触发)
|
||
top_plugins = [dict(r) for r in conn.execute(
|
||
"SELECT plugin_id AS pluginId, "
|
||
" COUNT(*) AS runs, "
|
||
" SUM(CASE WHEN status = 'start' THEN 1 ELSE 0 END) AS triggered, "
|
||
" SUM(CASE WHEN status IN ('done','success') THEN 1 ELSE 0 END) AS success, "
|
||
" SUM(CASE WHEN status IN ('error','failed') THEN 1 ELSE 0 END) AS failed, "
|
||
" COALESCE(SUM(duration_sec),0) AS durationSec "
|
||
"FROM runtime_reports GROUP BY plugin_id "
|
||
"ORDER BY triggered DESC LIMIT 8")]
|
||
pnames = {dict(r)["id"]: dict(r)["name"] for r in conn.execute(
|
||
"SELECT id, name FROM plugins")}
|
||
for tp in top_plugins:
|
||
tp["name"] = pnames.get(tp["pluginId"]) or tp["pluginId"]
|
||
tp["runs"] = int(tp["triggered"] or 0)
|
||
|
||
# 活跃用户排行
|
||
top_users = [{"account": r["account"], "runs": int(r["runs"])}
|
||
for r in conn.execute(
|
||
"SELECT account, COUNT(*) AS runs FROM runtime_reports "
|
||
"WHERE status = 'start' AND account <> '' GROUP BY account "
|
||
"ORDER BY runs DESC LIMIT 8")]
|
||
|
||
# 最近运行列表
|
||
recent = [dict(r) for r in conn.execute(
|
||
"SELECT at, account, plugin_id AS pluginId, version, status, msg, duration_sec AS durationSec "
|
||
"FROM runtime_reports WHERE status <> 'start' "
|
||
"ORDER BY id DESC LIMIT 20")]
|
||
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
for tu in top_users:
|
||
tu["nickname"] = nick.get(tu["account"], "")
|
||
for rc in recent:
|
||
rc["nickname"] = nick.get(rc.get("account", ""), "")
|
||
|
||
now_day = datetime.now().strftime("%Y-%m-%d")
|
||
return {
|
||
"users": {"total": int(users["total"] or 0), "admins": int(users["admins"] or 0),
|
||
"authorized": int(users["authorized"] or 0)},
|
||
"plugins": {"total": int(plugins["total"] or 0), "published": int(plugins["published"] or 0),
|
||
"disabled": int(plugins["disabled"] or 0), "revoked": int(plugins["revoked"] or 0)},
|
||
"runs": {"total": int(runs["started"] or 0), "success": int(runs["success"] or 0),
|
||
"failed": int(runs["failed"] or 0), "durationSec": int(runs["duration_sec"] or 0),
|
||
"activeUsers": int(runs["active_users"] or 0), "activePlugins": int(runs["active_plugins"] or 0)},
|
||
"trend": trend, "topPlugins": top_plugins, "topUsers": top_users,
|
||
"recent": recent, "today": now_day,
|
||
}
|
||
|
||
|
||
@router.get("/api/admin/audit")
|
||
def admin_audit(limit: int = Query(default=200, ge=1, le=1000),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""审计日志(最新在前,分页取 limit 条)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT id, account, action, target, detail, at FROM audit_logs "
|
||
"ORDER BY id DESC LIMIT ?", (limit,))]
|
||
for r in rows:
|
||
r["nickname"] = nick.get(r["account"], "")
|
||
return {"auditlogs": rows}
|
||
|
||
|
||
@router.get("/api/admin/reports")
|
||
def admin_reports(limit: int = Query(default=200, ge=1, le=1000),
|
||
x_admin_token: str = Header(default="", alias="X-Admin-Token"),
|
||
x_api_token: str = Header(default="", alias="X-API-Token")) -> dict:
|
||
"""运行上报记录(最新在前)。"""
|
||
_require_admin(x_admin_token, x_api_token)
|
||
with _db() as conn:
|
||
nick = {dict(r)["account"]: dict(r)["nickname"] for r in conn.execute(
|
||
"SELECT account, nickname FROM accounts")}
|
||
rows = [dict(r) for r in conn.execute(
|
||
"SELECT id, account, device_id, plugin_id, version, status, msg, duration_sec, at "
|
||
"FROM runtime_reports ORDER BY id DESC LIMIT ?", (limit,))]
|
||
for r in rows:
|
||
r["nickname"] = nick.get(r["account"], "")
|
||
return {"reports": rows} |