feat(ops): Umami/ntfy/DNS 运维控制台页面与 API
This commit is contained in:
parent
744a35fbbd
commit
acbf167ebe
@ -2429,6 +2429,46 @@ async def notify_test() -> dict[str, Any]:
|
|||||||
return {"ok": True, "webhook": url}
|
return {"ok": True, "webhook": url}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/ops")
|
||||||
|
async def ops_snapshot() -> dict[str, Any]:
|
||||||
|
"""Umami / ntfy / DNS / systemd health snapshot for the ops control page."""
|
||||||
|
from . import ops_panel
|
||||||
|
|
||||||
|
return await asyncio.to_thread(ops_panel.snapshot)
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/ntfy")
|
||||||
|
async def ops_ntfy_send(body: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
from . import ops_panel
|
||||||
|
|
||||||
|
title = str(body.get("title") or "DouyinWEB").strip()[:120]
|
||||||
|
message = str(body.get("message") or "").strip()
|
||||||
|
if not message:
|
||||||
|
raise HTTPException(400, "message 不能为空")
|
||||||
|
priority = str(body.get("priority") or "default").strip() or "default"
|
||||||
|
tags = str(body.get("tags") or "bell").strip() or "bell"
|
||||||
|
topic = body.get("topic")
|
||||||
|
topic_s = str(topic).strip() if topic else None
|
||||||
|
try:
|
||||||
|
return await asyncio.to_thread(ops_panel.send_ntfy, title, message, priority, tags, topic_s)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(500, f"发送失败: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/api/ops/healthcheck")
|
||||||
|
async def ops_run_healthcheck() -> dict[str, Any]:
|
||||||
|
from . import ops_panel
|
||||||
|
|
||||||
|
try:
|
||||||
|
return await asyncio.to_thread(ops_panel.run_healthcheck_script)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise HTTPException(400, str(exc)) from exc
|
||||||
|
except Exception as exc:
|
||||||
|
raise HTTPException(500, f"健康检查失败: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/downloads")
|
@app.get("/api/downloads")
|
||||||
async def downloads_catalog() -> dict[str, Any]:
|
async def downloads_catalog() -> dict[str, Any]:
|
||||||
from . import downloads as downloads_mod
|
from . import downloads as downloads_mod
|
||||||
|
|||||||
@ -8,32 +8,81 @@ import httpx
|
|||||||
from . import db
|
from . import db
|
||||||
|
|
||||||
|
|
||||||
|
def _event_allowed(event: str, cfg: dict[str, Any]) -> bool:
|
||||||
|
if event == "ops":
|
||||||
|
return True
|
||||||
|
if event == "live" and not cfg.get("notify_on_live", True):
|
||||||
|
return False
|
||||||
|
if event == "offline" and not cfg.get("notify_on_offline", False):
|
||||||
|
return False
|
||||||
|
if event == "risk" and not cfg.get("notify_on_risk", True):
|
||||||
|
return False
|
||||||
|
if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True):
|
||||||
|
return False
|
||||||
|
if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False):
|
||||||
|
return False
|
||||||
|
if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True):
|
||||||
|
return False
|
||||||
|
if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True):
|
||||||
|
return False
|
||||||
|
if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False):
|
||||||
|
return False
|
||||||
|
if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True):
|
||||||
|
return False
|
||||||
|
if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def send_ntfy_best_effort(event: str, payload: dict[str, Any]) -> None:
|
||||||
|
"""Mirror events to self-hosted ntfy when /etc/nomadro/ntfy.env is present."""
|
||||||
|
try:
|
||||||
|
from . import ops_panel
|
||||||
|
except Exception:
|
||||||
|
return
|
||||||
|
|
||||||
|
title_map = {
|
||||||
|
"live": "开播",
|
||||||
|
"offline": "停播",
|
||||||
|
"risk": "风控",
|
||||||
|
"shorts_fail": "Shorts 失败",
|
||||||
|
"shorts_ok": "Shorts 成功",
|
||||||
|
"shorts_quota": "Shorts 配额",
|
||||||
|
"tiktok_fail": "TikTok 失败",
|
||||||
|
"tiktok_ok": "TikTok 成功",
|
||||||
|
"tiktok_limit": "TikTok 限额",
|
||||||
|
"watch_remind": "提醒",
|
||||||
|
"ops": "运维",
|
||||||
|
}
|
||||||
|
title = title_map.get(event, event)
|
||||||
|
message = str(payload.get("message") or event)
|
||||||
|
tags = "rotating_light" if event in {"risk", "shorts_fail", "tiktok_fail"} else "bell"
|
||||||
|
priority = "high" if event in {"risk", "shorts_fail", "tiktok_fail"} else "default"
|
||||||
|
|
||||||
|
def _send() -> None:
|
||||||
|
try:
|
||||||
|
ops_panel.send_ntfy(title, message, priority, tags)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.get_running_loop()
|
||||||
|
asyncio.create_task(asyncio.to_thread(_send))
|
||||||
|
except RuntimeError:
|
||||||
|
await asyncio.to_thread(_send)
|
||||||
|
|
||||||
|
|
||||||
async def send_webhook(event: str, payload: dict[str, Any]) -> None:
|
async def send_webhook(event: str, payload: dict[str, Any]) -> None:
|
||||||
cfg = db.get_settings_map()
|
cfg = db.get_settings_map()
|
||||||
|
if not _event_allowed(event, cfg):
|
||||||
|
return
|
||||||
|
|
||||||
|
# ntfy mirror (does not require webhook URL)
|
||||||
|
await send_ntfy_best_effort(event, payload)
|
||||||
|
|
||||||
url = str(cfg.get("notify_webhook_url") or "").strip()
|
url = str(cfg.get("notify_webhook_url") or "").strip()
|
||||||
if not url:
|
if not url:
|
||||||
return
|
return
|
||||||
if event == "live" and not cfg.get("notify_on_live", True):
|
|
||||||
return
|
|
||||||
if event == "offline" and not cfg.get("notify_on_offline", False):
|
|
||||||
return
|
|
||||||
if event == "risk" and not cfg.get("notify_on_risk", True):
|
|
||||||
return
|
|
||||||
if event == "shorts_fail" and not cfg.get("notify_on_shorts_fail", True):
|
|
||||||
return
|
|
||||||
if event == "shorts_ok" and not cfg.get("notify_on_shorts_ok", False):
|
|
||||||
return
|
|
||||||
if event == "shorts_quota" and not cfg.get("notify_on_shorts_quota", True):
|
|
||||||
return
|
|
||||||
if event == "tiktok_fail" and not cfg.get("notify_on_tiktok_fail", True):
|
|
||||||
return
|
|
||||||
if event == "tiktok_ok" and not cfg.get("notify_on_tiktok_ok", False):
|
|
||||||
return
|
|
||||||
if event == "tiktok_limit" and not cfg.get("notify_on_tiktok_limit", True):
|
|
||||||
return
|
|
||||||
if event == "watch_remind" and not cfg.get("notify_on_watch_remind", True):
|
|
||||||
return
|
|
||||||
# allow ops/test always when URL configured
|
|
||||||
|
|
||||||
body = {
|
body = {
|
||||||
"event": event,
|
"event": event,
|
||||||
|
|||||||
288
backend/app/ops_panel.py
Normal file
288
backend/app/ops_panel.py
Normal file
@ -0,0 +1,288 @@
|
|||||||
|
"""Ops panel: Umami / ntfy / DNS / site health for DouyinWEB control UI."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
|
||||||
|
SERVER_IP = "107.173.30.245"
|
||||||
|
NTFY_ENV = Path("/etc/nomadro/ntfy.env")
|
||||||
|
UMAMI_ENV = Path("/etc/nomadro/umami.env")
|
||||||
|
UMAMI_SITES = Path("/etc/nomadro/umami-sites.env")
|
||||||
|
|
||||||
|
# Public web surfaces managed on this host
|
||||||
|
SITES: list[dict[str, str]] = [
|
||||||
|
{
|
||||||
|
"domain": "nomadro.com",
|
||||||
|
"role": "Nomadro 英文 WP + 中文 Next(分流)",
|
||||||
|
"umami_key": "UMAMI_ID_NOMADRO_COM",
|
||||||
|
"health_url": "https://nomadro.com/",
|
||||||
|
"kind": "content",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "portal.nomadro.com",
|
||||||
|
"role": "Nomadro Next 直连",
|
||||||
|
"umami_key": "UMAMI_ID_PORTAL_NOMADRO_COM",
|
||||||
|
"health_url": "https://portal.nomadro.com/",
|
||||||
|
"kind": "content",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "dylive.nomadro.com",
|
||||||
|
"role": "DouyinWEB / LiveRadar",
|
||||||
|
"umami_key": "UMAMI_ID_DYLIVE_NOMADRO_COM",
|
||||||
|
"health_url": "https://dylive.nomadro.com/login",
|
||||||
|
"kind": "app",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "nomadro.live",
|
||||||
|
"role": "TikTok Promo",
|
||||||
|
"umami_key": "UMAMI_ID_NOMADRO_LIVE",
|
||||||
|
"health_url": "https://nomadro.live/",
|
||||||
|
"kind": "app",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "wx.nomadro.com",
|
||||||
|
"role": "HackRobot",
|
||||||
|
"umami_key": "UMAMI_ID_WX_NOMADRO_COM",
|
||||||
|
"health_url": "https://wx.nomadro.com/",
|
||||||
|
"kind": "app",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "x.nomadro.com",
|
||||||
|
"role": "XAuto",
|
||||||
|
"umami_key": "UMAMI_ID_X_NOMADRO_COM",
|
||||||
|
"health_url": "https://x.nomadro.com/",
|
||||||
|
"kind": "app",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "umami.nomadro.com",
|
||||||
|
"role": "Umami 分析后台",
|
||||||
|
"umami_key": "",
|
||||||
|
"health_url": "https://umami.nomadro.com/api/heartbeat",
|
||||||
|
"kind": "infra",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "ntfy.nomadro.com",
|
||||||
|
"role": "ntfy 通知服务",
|
||||||
|
"umami_key": "",
|
||||||
|
"health_url": "https://ntfy.nomadro.com/v1/health",
|
||||||
|
"kind": "infra",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "s3.nomadro.com",
|
||||||
|
"role": "SeaweedFS S3",
|
||||||
|
"umami_key": "",
|
||||||
|
"health_url": "",
|
||||||
|
"kind": "infra",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"domain": "feiniu.nomadro.com",
|
||||||
|
"role": "S3 别名",
|
||||||
|
"umami_key": "",
|
||||||
|
"health_url": "",
|
||||||
|
"kind": "infra",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
SERVICES = [
|
||||||
|
("caddy", "Caddy TLS / 反代"),
|
||||||
|
("docker", "Docker"),
|
||||||
|
("douyinweb-web", "DouyinWEB Next"),
|
||||||
|
("douyinweb-api", "DouyinWEB API"),
|
||||||
|
("nomadro", "Nomadro Next"),
|
||||||
|
("nomadro-router", "受众分流"),
|
||||||
|
("tiktok-promo-frontend", "TikTok Promo"),
|
||||||
|
("hackrobot-web", "HackRobot"),
|
||||||
|
("xauto-web", "XAuto"),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _read_env_file(path: Path) -> dict[str, str]:
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
if not path.is_file():
|
||||||
|
return out
|
||||||
|
try:
|
||||||
|
for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
k, v = line.split("=", 1)
|
||||||
|
out[k.strip()] = v.strip().strip('"').strip("'")
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _http_probe(url: str, timeout: float = 8.0) -> dict[str, Any]:
|
||||||
|
if not url:
|
||||||
|
return {"ok": None, "status": None, "ms": None, "error": "no url"}
|
||||||
|
t0 = time.monotonic()
|
||||||
|
try:
|
||||||
|
req = Request(url, headers={"User-Agent": "DouyinWEB-Ops/1.0"}, method="GET")
|
||||||
|
with urlopen(req, timeout=timeout) as resp:
|
||||||
|
body = resp.read(200)
|
||||||
|
ms = int((time.monotonic() - t0) * 1000)
|
||||||
|
return {"ok": 200 <= resp.status < 400, "status": resp.status, "ms": ms, "snippet": body[:80].decode("utf-8", "replace")}
|
||||||
|
except HTTPError as e:
|
||||||
|
ms = int((time.monotonic() - t0) * 1000)
|
||||||
|
return {"ok": False, "status": e.code, "ms": ms, "error": str(e.reason)}
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
ms = int((time.monotonic() - t0) * 1000)
|
||||||
|
return {"ok": False, "status": None, "ms": ms, "error": str(e)}
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_a(domain: str) -> list[str]:
|
||||||
|
try:
|
||||||
|
infos = socket.getaddrinfo(domain, 443, type=socket.SOCK_STREAM)
|
||||||
|
ips = sorted({i[4][0] for i in infos if ":" not in i[4][0]})
|
||||||
|
return ips
|
||||||
|
except OSError as e:
|
||||||
|
return [f"error:{e}"]
|
||||||
|
|
||||||
|
|
||||||
|
def _systemctl_active(unit: str) -> dict[str, Any]:
|
||||||
|
try:
|
||||||
|
r = subprocess.run(
|
||||||
|
["systemctl", "is-active", unit],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=5,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
state = (r.stdout or r.stderr or "").strip() or "unknown"
|
||||||
|
return {"unit": unit, "state": state, "ok": state == "active"}
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
return {"unit": unit, "state": "error", "ok": False, "error": str(e)}
|
||||||
|
|
||||||
|
|
||||||
|
def ntfy_config() -> dict[str, Any]:
|
||||||
|
env = _read_env_file(NTFY_ENV)
|
||||||
|
token = env.get("NTFY_TOKEN", "")
|
||||||
|
return {
|
||||||
|
"configured": bool(token),
|
||||||
|
"base_url": env.get("NTFY_BASE_URL", "https://ntfy.nomadro.com"),
|
||||||
|
"topic": env.get("NTFY_TOPIC", "server-alerts"),
|
||||||
|
"user": env.get("NTFY_USER", ""),
|
||||||
|
"has_token": bool(token),
|
||||||
|
# never expose full token to UI — only suffix
|
||||||
|
"token_suffix": token[-6:] if len(token) >= 6 else ("*" * len(token)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def umami_config() -> dict[str, Any]:
|
||||||
|
env = _read_env_file(UMAMI_ENV)
|
||||||
|
sites = _read_env_file(UMAMI_SITES)
|
||||||
|
return {
|
||||||
|
"url": env.get("UMAMI_URL", "https://umami.nomadro.com"),
|
||||||
|
"user": env.get("UMAMI_USER", "admin"),
|
||||||
|
"has_password": bool(env.get("UMAMI_PASSWORD")),
|
||||||
|
"script": sites.get("UMAMI_SCRIPT", "https://umami.nomadro.com/script.js"),
|
||||||
|
"sites": {k: v for k, v in sites.items() if k.startswith("UMAMI_ID_")},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def send_ntfy(title: str, message: str, priority: str = "default", tags: str = "bell", topic: str | None = None) -> dict[str, Any]:
|
||||||
|
cfg = ntfy_config()
|
||||||
|
env = _read_env_file(NTFY_ENV)
|
||||||
|
token = env.get("NTFY_TOKEN", "")
|
||||||
|
if not token:
|
||||||
|
raise ValueError("ntfy 未配置:缺少 /etc/nomadro/ntfy.env 中的 NTFY_TOKEN")
|
||||||
|
base = cfg["base_url"].rstrip("/")
|
||||||
|
use_topic = topic or cfg["topic"]
|
||||||
|
url = f"{base}/{use_topic}"
|
||||||
|
body = message.encode("utf-8")
|
||||||
|
req = Request(
|
||||||
|
url,
|
||||||
|
data=body,
|
||||||
|
method="POST",
|
||||||
|
headers={
|
||||||
|
"Authorization": f"Bearer {token}",
|
||||||
|
"Title": title,
|
||||||
|
"Priority": priority,
|
||||||
|
"Tags": tags,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urlopen(req, timeout=15) as resp:
|
||||||
|
raw = resp.read().decode("utf-8", "replace")
|
||||||
|
try:
|
||||||
|
parsed = json.loads(raw) if raw else {}
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
parsed = {"raw": raw}
|
||||||
|
return {"ok": True, "status": resp.status, "topic": use_topic, "response": parsed}
|
||||||
|
except HTTPError as e:
|
||||||
|
raise ValueError(f"ntfy 发送失败 HTTP {e.code}: {e.read().decode('utf-8', 'replace')[:200]}") from e
|
||||||
|
except URLError as e:
|
||||||
|
raise ValueError(f"ntfy 连接失败: {e}") from e
|
||||||
|
|
||||||
|
|
||||||
|
def run_healthcheck_script() -> dict[str, Any]:
|
||||||
|
script = Path("/usr/local/bin/nomadro-healthcheck")
|
||||||
|
if not script.is_file():
|
||||||
|
raise ValueError("未安装 /usr/local/bin/nomadro-healthcheck")
|
||||||
|
r = subprocess.run([str(script)], capture_output=True, text=True, timeout=120, check=False)
|
||||||
|
return {
|
||||||
|
"ok": r.returncode == 0,
|
||||||
|
"returncode": r.returncode,
|
||||||
|
"stdout": (r.stdout or "")[-2000:],
|
||||||
|
"stderr": (r.stderr or "")[-1000:],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot() -> dict[str, Any]:
|
||||||
|
umami = umami_config()
|
||||||
|
ntfy = ntfy_config()
|
||||||
|
site_rows = []
|
||||||
|
for s in SITES:
|
||||||
|
ips = _resolve_a(s["domain"])
|
||||||
|
dns_ok = SERVER_IP in ips
|
||||||
|
probe = _http_probe(s["health_url"]) if s.get("health_url") else {"ok": None, "status": None, "ms": None}
|
||||||
|
wid = umami["sites"].get(s["umami_key"], "") if s.get("umami_key") else ""
|
||||||
|
site_rows.append(
|
||||||
|
{
|
||||||
|
**s,
|
||||||
|
"ips": ips,
|
||||||
|
"dns_ok": dns_ok,
|
||||||
|
"expected_ip": SERVER_IP,
|
||||||
|
"umami_website_id": wid,
|
||||||
|
"health": probe,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
services = [_systemctl_active(u) for u, _label in SERVICES]
|
||||||
|
for svc, (_u, label) in zip(services, SERVICES):
|
||||||
|
svc["label"] = label
|
||||||
|
|
||||||
|
return {
|
||||||
|
"generated_at": time.time(),
|
||||||
|
"server_ip": SERVER_IP,
|
||||||
|
"umami": {
|
||||||
|
**umami,
|
||||||
|
"heartbeat": _http_probe("https://umami.nomadro.com/api/heartbeat"),
|
||||||
|
},
|
||||||
|
"ntfy": {
|
||||||
|
**ntfy,
|
||||||
|
"health": _http_probe("https://ntfy.nomadro.com/v1/health"),
|
||||||
|
},
|
||||||
|
"sites": site_rows,
|
||||||
|
"services": services,
|
||||||
|
"paths": {
|
||||||
|
"ntfy_env": str(NTFY_ENV),
|
||||||
|
"umami_env": str(UMAMI_ENV),
|
||||||
|
"umami_sites": str(UMAMI_SITES),
|
||||||
|
"healthcheck": "/usr/local/bin/nomadro-healthcheck",
|
||||||
|
"notify": "/usr/local/bin/notify-ntfy",
|
||||||
|
},
|
||||||
|
"host": socket.gethostname(),
|
||||||
|
"env_hint": {
|
||||||
|
"DY_API_HOST": os.environ.get("DY_API_HOST", ""),
|
||||||
|
"has_ntfy_env": NTFY_ENV.is_file(),
|
||||||
|
"has_umami_env": UMAMI_ENV.is_file(),
|
||||||
|
},
|
||||||
|
}
|
||||||
@ -48,6 +48,11 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|||||||
rel="stylesheet"
|
rel="stylesheet"
|
||||||
/>
|
/>
|
||||||
<meta name="mobile-web-app-capable" content="yes" />
|
<meta name="mobile-web-app-capable" content="yes" />
|
||||||
|
<script
|
||||||
|
defer
|
||||||
|
src="https://umami.nomadro.com/script.js"
|
||||||
|
data-website-id={process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID || "f18d3484-be2e-4344-8882-b80c5b53f9cf"}
|
||||||
|
/>
|
||||||
</head>
|
</head>
|
||||||
<body className="min-h-[100dvh] antialiased">
|
<body className="min-h-[100dvh] antialiased">
|
||||||
<Providers>{children}</Providers>
|
<Providers>{children}</Providers>
|
||||||
|
|||||||
420
frontend/src/app/ops/page.tsx
Normal file
420
frontend/src/app/ops/page.tsx
Normal file
@ -0,0 +1,420 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||||
|
import {
|
||||||
|
Activity,
|
||||||
|
Bell,
|
||||||
|
ExternalLink,
|
||||||
|
Globe2,
|
||||||
|
Loader2,
|
||||||
|
Radar,
|
||||||
|
RefreshCw,
|
||||||
|
Server,
|
||||||
|
ShieldCheck,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
|
import { Shell } from "@/components/Shell";
|
||||||
|
import { useToast } from "@/components/Toast";
|
||||||
|
import { fetchJson, fmtTs } from "@/lib/api";
|
||||||
|
|
||||||
|
type Probe = {
|
||||||
|
ok?: boolean | null;
|
||||||
|
status?: number | null;
|
||||||
|
ms?: number | null;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type SiteRow = {
|
||||||
|
domain: string;
|
||||||
|
role: string;
|
||||||
|
kind: string;
|
||||||
|
ips: string[];
|
||||||
|
dns_ok: boolean;
|
||||||
|
expected_ip: string;
|
||||||
|
umami_website_id?: string;
|
||||||
|
health: Probe;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ServiceRow = {
|
||||||
|
unit: string;
|
||||||
|
label: string;
|
||||||
|
state: string;
|
||||||
|
ok: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
type OpsSnapshot = {
|
||||||
|
generated_at?: number;
|
||||||
|
server_ip?: string;
|
||||||
|
host?: string;
|
||||||
|
umami?: {
|
||||||
|
url?: string;
|
||||||
|
user?: string;
|
||||||
|
script?: string;
|
||||||
|
sites?: Record<string, string>;
|
||||||
|
heartbeat?: Probe;
|
||||||
|
};
|
||||||
|
ntfy?: {
|
||||||
|
configured?: boolean;
|
||||||
|
base_url?: string;
|
||||||
|
topic?: string;
|
||||||
|
user?: string;
|
||||||
|
has_token?: boolean;
|
||||||
|
token_suffix?: string;
|
||||||
|
health?: Probe;
|
||||||
|
};
|
||||||
|
sites?: SiteRow[];
|
||||||
|
services?: ServiceRow[];
|
||||||
|
paths?: Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
function StatusDot({ ok }: { ok?: boolean | null }) {
|
||||||
|
const color =
|
||||||
|
ok === true ? "bg-teal-400 shadow-[0_0_10px_rgba(45,212,191,0.55)]" : ok === false ? "bg-rose-400" : "bg-slate-500";
|
||||||
|
return <span className={`inline-block h-2 w-2 rounded-full ${color}`} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProbeText({ p }: { p?: Probe }) {
|
||||||
|
if (!p) return <span className="text-slate-500">—</span>;
|
||||||
|
if (p.ok === true) return <span className="text-teal-300">{p.status ?? "ok"} · {p.ms ?? "?"}ms</span>;
|
||||||
|
if (p.ok === false)
|
||||||
|
return (
|
||||||
|
<span className="text-rose-300">
|
||||||
|
{p.status ?? "fail"} {p.error ? `· ${p.error}` : ""} {p.ms != null ? `· ${p.ms}ms` : ""}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
return <span className="text-slate-500">n/a</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function OpsPage() {
|
||||||
|
const toast = useToast();
|
||||||
|
const [data, setData] = useState<OpsSnapshot | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [busy, setBusy] = useState("");
|
||||||
|
const [title, setTitle] = useState("DouyinWEB 测试");
|
||||||
|
const [message, setMessage] = useState("来自 /ops 控制台的 ntfy 测试消息");
|
||||||
|
const [priority, setPriority] = useState("default");
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const r = await fetchJson("/api/ops");
|
||||||
|
setData(r);
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [toast]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load();
|
||||||
|
}, [load]);
|
||||||
|
|
||||||
|
const dnsOkCount = useMemo(() => (data?.sites || []).filter((s) => s.dns_ok).length, [data]);
|
||||||
|
const svcOkCount = useMemo(() => (data?.services || []).filter((s) => s.ok).length, [data]);
|
||||||
|
|
||||||
|
async function sendNtfy() {
|
||||||
|
setBusy("ntfy");
|
||||||
|
try {
|
||||||
|
await fetchJson("/api/ops/ntfy", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ title, message, priority, tags: "bell,desktop" }),
|
||||||
|
});
|
||||||
|
toast.push("已发送到 ntfy", "ok");
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runHealth() {
|
||||||
|
setBusy("health");
|
||||||
|
try {
|
||||||
|
const r = await fetchJson("/api/ops/healthcheck", { method: "POST" });
|
||||||
|
toast.push(r?.ok ? "健康检查已执行" : `健康检查结束 code=${r?.returncode}`, r?.ok ? "ok" : "err");
|
||||||
|
await load();
|
||||||
|
} catch (e) {
|
||||||
|
toast.push((e as Error).message, "err");
|
||||||
|
} finally {
|
||||||
|
setBusy("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Shell>
|
||||||
|
<div className="mx-auto max-w-6xl space-y-5 pb-8">
|
||||||
|
<div className="rounded-3xl border border-white/10 bg-black/30 p-5">
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-[11px] uppercase tracking-[0.18em] text-teal-200/70">Infrastructure</div>
|
||||||
|
<h1 className="font-display text-2xl font-semibold text-white">站点运维台</h1>
|
||||||
|
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
||||||
|
Umami 分析、ntfy 通知、DNS 解析与核心服务状态。数据来自本机探测与{" "}
|
||||||
|
<code className="text-slate-300">/etc/nomadro/*</code>。
|
||||||
|
</p>
|
||||||
|
<div className="mt-2 flex flex-wrap gap-3 text-xs text-slate-400">
|
||||||
|
<span>主机 {data?.host || "—"}</span>
|
||||||
|
<span>期望 IP {data?.server_ip || "—"}</span>
|
||||||
|
<span>{data?.generated_at ? fmtTs(data.generated_at) : ""}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!!busy}
|
||||||
|
onClick={() => void load()}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-200"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
|
||||||
|
刷新
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!!busy}
|
||||||
|
onClick={() => void runHealth()}
|
||||||
|
className="inline-flex items-center gap-1.5 rounded-xl bg-gradient-to-br from-teal-400 to-sky-500 px-3 py-2 text-xs font-semibold text-[#0b1220]"
|
||||||
|
>
|
||||||
|
{busy === "health" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Activity className="h-3.5 w-3.5" />}
|
||||||
|
跑健康检查
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 grid gap-3 sm:grid-cols-3">
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
|
||||||
|
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||||
|
<Radar className="h-3.5 w-3.5 text-teal-300" /> Umami
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 flex items-center gap-2 text-sm text-white">
|
||||||
|
<StatusDot ok={data?.umami?.heartbeat?.ok} />
|
||||||
|
<ProbeText p={data?.umami?.heartbeat} />
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href={data?.umami?.url || "https://umami.nomadro.com"}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="mt-2 inline-flex items-center gap-1 text-xs text-sky-300 hover:underline"
|
||||||
|
>
|
||||||
|
打开分析台 <ExternalLink className="h-3 w-3" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
|
||||||
|
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||||
|
<Bell className="h-3.5 w-3.5 text-amber-300" /> ntfy
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 flex items-center gap-2 text-sm text-white">
|
||||||
|
<StatusDot ok={data?.ntfy?.health?.ok} />
|
||||||
|
<ProbeText p={data?.ntfy?.health} />
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[11px] text-slate-500">
|
||||||
|
topic {data?.ntfy?.topic || "—"} · token …{data?.ntfy?.token_suffix || ""}
|
||||||
|
</div>
|
||||||
|
<a
|
||||||
|
href={data?.ntfy?.base_url || "https://ntfy.nomadro.com"}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="mt-2 inline-flex items-center gap-1 text-xs text-sky-300 hover:underline"
|
||||||
|
>
|
||||||
|
打开 ntfy <ExternalLink className="h-3 w-3" />
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
|
||||||
|
<div className="flex items-center gap-2 text-xs text-slate-400">
|
||||||
|
<ShieldCheck className="h-3.5 w-3.5 text-sky-300" /> DNS / 服务
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-sm text-white">
|
||||||
|
DNS {dnsOkCount}/{data?.sites?.length ?? 0} · 服务 {svcOkCount}/{data?.services?.length ?? 0}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-[11px] text-slate-500">期望 A 记录 → {data?.server_ip}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-5 lg:grid-cols-5">
|
||||||
|
<div className="space-y-5 lg:col-span-3">
|
||||||
|
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
|
||||||
|
<Globe2 className="h-4 w-4 text-sky-300" />
|
||||||
|
域名 · DNS · Umami · 探测
|
||||||
|
</div>
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full min-w-[640px] text-left text-xs">
|
||||||
|
<thead className="text-slate-500">
|
||||||
|
<tr className="border-b border-white/10">
|
||||||
|
<th className="py-2 pr-2 font-medium">域名</th>
|
||||||
|
<th className="py-2 pr-2 font-medium">DNS</th>
|
||||||
|
<th className="py-2 pr-2 font-medium">健康</th>
|
||||||
|
<th className="py-2 font-medium">Umami ID</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{(data?.sites || []).map((s) => (
|
||||||
|
<tr key={s.domain} className="border-b border-white/5 align-top">
|
||||||
|
<td className="py-2.5 pr-2">
|
||||||
|
<a
|
||||||
|
href={`https://${s.domain}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="font-medium text-sky-200 hover:underline"
|
||||||
|
>
|
||||||
|
{s.domain}
|
||||||
|
</a>
|
||||||
|
<div className="mt-0.5 text-[11px] text-slate-500">{s.role}</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-2.5 pr-2">
|
||||||
|
<div className="flex items-center gap-1.5">
|
||||||
|
<StatusDot ok={s.dns_ok} />
|
||||||
|
<span className={s.dns_ok ? "text-teal-300" : "text-rose-300"}>
|
||||||
|
{(s.ips || []).join(", ") || "—"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
<td className="py-2.5 pr-2">
|
||||||
|
<ProbeText p={s.health} />
|
||||||
|
</td>
|
||||||
|
<td className="py-2.5 font-mono text-[10px] text-slate-400">
|
||||||
|
{s.umami_website_id || "—"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
{!data?.sites?.length && (
|
||||||
|
<tr>
|
||||||
|
<td colSpan={4} className="py-6 text-center text-slate-500">
|
||||||
|
{loading ? "加载中…" : "暂无数据"}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
|
||||||
|
<Server className="h-4 w-4 text-amber-300" />
|
||||||
|
systemd 服务
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2 sm:grid-cols-2">
|
||||||
|
{(data?.services || []).map((s) => (
|
||||||
|
<div
|
||||||
|
key={s.unit}
|
||||||
|
className="flex items-center justify-between rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2"
|
||||||
|
>
|
||||||
|
<div>
|
||||||
|
<div className="text-sm text-slate-100">{s.label}</div>
|
||||||
|
<div className="font-mono text-[10px] text-slate-500">{s.unit}</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 text-xs">
|
||||||
|
<StatusDot ok={s.ok} />
|
||||||
|
<span className={s.ok ? "text-teal-300" : "text-rose-300"}>{s.state}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-5 lg:col-span-2">
|
||||||
|
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<div className="mb-3 flex items-center gap-2 text-sm font-medium text-white">
|
||||||
|
<Bell className="h-4 w-4 text-amber-300" />
|
||||||
|
发送 ntfy
|
||||||
|
</div>
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label className="block text-[11px] text-slate-500">标题</label>
|
||||||
|
<input
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none focus:border-teal-400/40"
|
||||||
|
/>
|
||||||
|
<label className="block text-[11px] text-slate-500">内容</label>
|
||||||
|
<textarea
|
||||||
|
value={message}
|
||||||
|
onChange={(e) => setMessage(e.target.value)}
|
||||||
|
rows={4}
|
||||||
|
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none focus:border-teal-400/40"
|
||||||
|
/>
|
||||||
|
<label className="block text-[11px] text-slate-500">优先级</label>
|
||||||
|
<select
|
||||||
|
value={priority}
|
||||||
|
onChange={(e) => setPriority(e.target.value)}
|
||||||
|
className="w-full rounded-xl border border-white/10 bg-black/40 px-3 py-2 text-sm text-white outline-none"
|
||||||
|
>
|
||||||
|
<option value="min">min</option>
|
||||||
|
<option value="low">low</option>
|
||||||
|
<option value="default">default</option>
|
||||||
|
<option value="high">high</option>
|
||||||
|
<option value="max">max</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={!!busy || !data?.ntfy?.configured}
|
||||||
|
onClick={() => void sendNtfy()}
|
||||||
|
className="mt-1 inline-flex w-full items-center justify-center gap-1.5 rounded-xl bg-gradient-to-br from-amber-300 to-orange-500 px-3 py-2.5 text-sm font-semibold text-[#1a1208] disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{busy === "ntfy" ? <Loader2 className="h-4 w-4 animate-spin" /> : <Bell className="h-4 w-4" />}
|
||||||
|
推送到 {data?.ntfy?.topic || "server-alerts"}
|
||||||
|
</button>
|
||||||
|
{!data?.ntfy?.configured && (
|
||||||
|
<p className="text-[11px] text-rose-300">服务器尚未配置 ntfy token(/etc/nomadro/ntfy.env)</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="rounded-3xl border border-white/10 bg-black/25 p-4">
|
||||||
|
<div className="mb-2 text-sm font-medium text-white">快速链接 / 路径</div>
|
||||||
|
<ul className="space-y-1.5 text-xs text-slate-400">
|
||||||
|
<li>
|
||||||
|
Umami 脚本:<code className="text-slate-300">{data?.umami?.script}</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
配置:
|
||||||
|
<code className="text-slate-300"> {data?.paths?.umami_env}</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
站点 ID:
|
||||||
|
<code className="text-slate-300"> {data?.paths?.umami_sites}</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
ntfy:
|
||||||
|
<code className="text-slate-300"> {data?.paths?.ntfy_env}</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
CLI:
|
||||||
|
<code className="text-slate-300"> notify-ntfy / nomadro-healthcheck</code>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
|
<a
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs text-sky-200 hover:bg-white/10"
|
||||||
|
href="https://umami.nomadro.com"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
Umami
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs text-sky-200 hover:bg-white/10"
|
||||||
|
href="https://ntfy.nomadro.com"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
ntfy
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
className="rounded-lg border border-white/10 bg-white/5 px-2.5 py-1.5 text-xs text-sky-200 hover:bg-white/10"
|
||||||
|
href="https://nomadro.com"
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
>
|
||||||
|
nomadro.com
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Shell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@ -30,6 +30,7 @@ const NAV = [
|
|||||||
{ href: "/tiktok", label: "TikTok", emoji: "🎵" },
|
{ href: "/tiktok", label: "TikTok", emoji: "🎵" },
|
||||||
{ href: "/x", label: "X", emoji: "𝕏" },
|
{ href: "/x", label: "X", emoji: "𝕏" },
|
||||||
{ href: "/clash", label: "Clash", emoji: "🧿" },
|
{ href: "/clash", label: "Clash", emoji: "🧿" },
|
||||||
|
{ href: "/ops", label: "运维", emoji: "🛰️" },
|
||||||
{ href: "/downloads", label: "下载", emoji: "⬇️" },
|
{ href: "/downloads", label: "下载", emoji: "⬇️" },
|
||||||
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
|
{ href: "/blacklist", label: "黑名单", emoji: "🚫" },
|
||||||
{ href: "/settings", label: "设置", emoji: "⚙️" },
|
{ href: "/settings", label: "设置", emoji: "⚙️" },
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user