"""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(), }, }