douyinWEB/backend/app/network_hub.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

266 lines
9.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""Network hub — WireGuard primary + FRP auxiliary (SH2-adapted).
Physical dual-path policy:
- Primary: WireGuard (wg-dy) carries app traffic VPS Caddy → 10.8.0.2 and preferred SSH.
- Auxiliary: FRP (frpp :4014) is emergency SSH / ops only — never the app data path.
"""
from __future__ import annotations
import os
import re
import shutil
import time
from pathlib import Path
from typing import Any
from . import global_socks
from . import shellcrash_hub
from . import wireguard_hub
def _run(cmd: list[str], timeout: int = 12) -> tuple[int, str]:
import subprocess
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
return int(p.returncode), ((p.stdout or "") + (p.stderr or "")).strip()
except Exception as exc:
return 1, str(exc)
def _unit_active(name: str) -> str:
code, out = _run(["systemctl", "is-active", name], timeout=5)
return (out.splitlines()[0] if out else ("inactive" if code else "unknown")).strip()
def path_roles() -> dict[str, Any]:
"""Declare which transport is primary vs auxiliary."""
cn_up = Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False
wg_target = "10.9.0.2(wg-dy-cn 国内优先)" if cn_up else "10.8.0.2(wg-dy 海外)"
return {
"app_https": {
"primary": "wireguard",
"detail": f"VPS Caddy → WG {wg_target}:4015/8014;wg-dy 海外链路保留作备份",
},
"ops_ssh": {
"primary": "wireguard",
"auxiliary": "frp",
"detail": "优先 WG(wg-dy-cn → 10.9.0.1 或 wg-dy → 10.8.0.1);FRP :4014 仅应急",
},
"policy": "wg_cn_primary_wg_us_backup_frp_aux",
}
def frp_status() -> dict[str, Any]:
"""FRP is auxiliary — SSH/ops fallback only; do not carry app reverse_proxy."""
unit = None
for name in ("frpp", "frpc", "frp-panel"):
st = _unit_active(name)
if st in {"active", "activating"}:
unit = {"name": name, "state": st}
break
if unit is None and st not in {"inactive", "unknown", ""}:
unit = {"name": name, "state": st}
code, ps = _run(["bash", "-lc", "ps aux | grep -E '[f]rpc|[f]rpp|[f]rp-panel' | head -5"], timeout=8)
procs = [ln.strip() for ln in (ps or "").splitlines() if ln.strip()]
# Detect common SSH tunnel port hint
ports: list[int] = []
for ln in procs:
for m in re.finditer(r":(\d{2,5})\b", ln):
try:
ports.append(int(m.group(1)))
except ValueError:
pass
return {
"ok": True,
"role": "auxiliary",
"purpose": "ops_ssh_emergency",
"unit": unit,
"processes": procs[:5],
"hint_ports": sorted(set(ports))[:8],
"detail": "辅路径:仅应急 SSH/运维(如 VPS:4014→guest:22)。应用 HTTPS 必须走 WireGuard,勿把业务反代挂到 FRP。",
}
def socks_status() -> dict[str, Any]:
from . import db
cfg = db.get_settings_map()
enabled = global_socks.is_global_socks_enabled(cfg)
profiles = global_socks.list_socks_profiles(cfg, public=True)
active_id = global_socks.active_profile_id(cfg)
from . import singbox_manager
return {
"ok": True,
"enabled": enabled,
"active_profile_id": active_id,
"profiles": profiles,
"local_mixed": global_socks.local_mixed_url() if enabled else "",
"singbox_running": bool(singbox_manager.is_running()) if enabled else False,
"hint": "新装默认无住宅节点;自行添加 SOCKS5",
}
def _deploy_shape_hint() -> str:
if Path("/etc/wireguard/wg-dy.conf").is_file() or any(
p.name == "wg-dy" for p in Path("/sys/class/net").iterdir() if Path("/sys/class/net").is_dir()
):
return "physical_or_wg"
return "colocated_or_unknown"
def _wg_handshake_age_sec() -> int | None:
"""Seconds since latest handshake on primary WG iface (wg-dy-cn preferred)."""
for iface in ("wg-dy-cn", "wg-dy"):
code, out = _run(["wg", "show", iface, "latest-handshakes"], timeout=5)
if code != 0 or not out.strip():
continue
parts = out.split()
if len(parts) < 2:
continue
try:
ts = int(parts[-1])
except ValueError:
continue
if ts <= 0:
continue
return max(0, int(time.time()) - ts)
return None
def _ping_wg_peer() -> dict[str, Any]:
if Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False:
peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1"
else:
peer = str(os.environ.get("DY_WG_PEER_IP") or "10.8.0.1").strip() or "10.8.0.1"
code, out = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6)
ok = code == 0 and "1 received" in out.replace("packets ", "")
if not ok:
ok = code == 0 and ("bytes from" in out or "ttl=" in out.lower())
rtt = ""
m = re.search(r"time[=<]([0-9.]+)\s*ms", out)
if m:
rtt = m.group(1) + "ms"
return {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]}
def wireguard_watch_status() -> dict[str, Any]:
unit = _unit_active("douyinweb-wireguard-watch")
path = Path("/opt/douyinWEB/scripts/linux/wireguard_watch.sh")
return {
"unit": unit,
"installed": path.is_file(),
"path": str(path) if path.is_file() else "",
"hint": "stale handshake 自动重启 wg-dy-cn / wg-dy(主路径保活)",
}
def network_overview() -> dict[str, Any]:
wg = wireguard_hub.runtime_status()
age = _wg_handshake_age_sec()
ping = _ping_wg_peer()
wg["role"] = "primary"
wg["purpose"] = "app_https_and_ops_ssh"
wg["handshake_age_sec"] = age
wg["handshake_fresh"] = age is not None and age < 180
wg["peer_ping"] = ping
wg["watch"] = wireguard_watch_status()
if age is not None and age >= 300:
wg.setdefault("recommendations", []).append(
f"握手已 {age}s 未刷新 — watch 应重启 wg-dy;勿改用 FRP 扛业务"
)
frp = frp_status()
from . import egress_hub
return {
"ok": True,
"path_roles": path_roles(),
"wireguard": wg,
"frp": frp,
"shellcrash": shellcrash_hub.status(),
"socks": socks_status(),
"egress": egress_hub.status(),
"deploy_shape": _deploy_shape_hint(),
"physical_checklist": physical_checklist(wg=wg, frp=frp),
}
def physical_checklist(
*,
wg: dict[str, Any] | None = None,
frp: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Operator checklist — WireGuard primary, FRP auxiliary."""
checks: list[dict[str, Any]] = []
def add(name: str, ok: bool, detail: str = "") -> None:
checks.append({"name": name, "ok": bool(ok), "detail": detail})
pub = str(os.environ.get("DY_PUBLIC_BASE_URL") or "").strip()
add(
"public_base_url",
pub.startswith("https://") and "127.0.0.1" not in pub and not pub.startswith("http://10."),
pub or "missing DY_PUBLIC_BASE_URL",
)
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "127.0.0.1").strip()
shape = _deploy_shape_hint()
if shape.startswith("physical"):
add("neko_http_bind", bind in {"0.0.0.0", "*"}, f"DY_NEKO_HTTP_BIND={bind} (physical needs 0.0.0.0)")
else:
add("neko_http_bind", True, f"DY_NEKO_HTTP_BIND={bind}")
docker_ok = bool(shutil.which("docker"))
add("docker", docker_ok, "docker binary" if docker_ok else "missing")
seed = Path(__file__).resolve().parent.parent / "neko" / "tampermonkey-seed" / "Default" / "Extensions"
add("neko_seed", seed.is_dir(), str(seed))
wg_up = Path("/sys/class/net/wg-dy").exists() if Path("/sys/class/net").is_dir() else False
add("wg_primary_link", wg_up or shape != "physical_or_wg", "wg-dy iface (主路径)" if wg_up else "no wg-dy")
wg = wg or {}
age = wg.get("handshake_age_sec")
if isinstance(age, int):
add("wg_handshake", age < 300, f"age={age}s (主路径保活)")
elif wg_up:
add("wg_handshake", False, "无法读取 handshake")
ping = wg.get("peer_ping") if isinstance(wg.get("peer_ping"), dict) else {}
if ping:
add("wg_peer_ping", bool(ping.get("ok")), f"{ping.get('peer')} {ping.get('rtt') or ''}".strip())
watch = wg.get("watch") if isinstance(wg.get("watch"), dict) else {}
if shape.startswith("physical"):
add(
"wg_watch",
watch.get("unit") == "active",
f"unit={watch.get('unit') or 'missing'} — douyinweb-wireguard-watch 保活主路径",
)
frp = frp or {}
frp_unit = (frp.get("unit") or {}) if isinstance(frp.get("unit"), dict) else {}
add(
"frp_aux_ssh",
True,
f"role=auxiliary state={frp_unit.get('state') or 'n/a'} — 仅应急 SSH,不扛业务",
)
sc = shellcrash_hub.status()
if shape.startswith("physical"):
add(
"shellcrash",
bool(sc.get("installed")) and bool(sc.get("running")),
f"installed={sc.get('installed')} unit={sc.get('unit')} mixed=:{sc.get('mixed_port') or '?'}",
)
failed = sum(1 for c in checks if not c["ok"])
return {
"ok": failed == 0,
"failed": failed,
"checks": checks,
"deploy_shape": shape,
"policy": "wg_primary_frp_aux",
}