From 732d93e5d4df605e3324d9cae5af1056b31174cc Mon Sep 17 00:00:00 2001 From: eric Date: Sat, 5 Sep 2026 01:20:53 -0500 Subject: [PATCH] Add VPS/physical host profile switch and document nomadro topology. Header toggle stops app egress+Neko and enables exclusive live on VPS mode; README covers dylive/dy.com/dy.cn roles. Co-authored-by: Cursor --- README.md | 51 +++++- backend/app/db.py | 2 + backend/app/host_profile.py | 192 ++++++++++++++++++++ backend/app/main.py | 20 ++ frontend/src/components/HostResourceBar.tsx | 90 +++++++++ scripts/_deploy_git_pull_both.py | 147 +++++++++++++++ 6 files changed, 501 insertions(+), 1 deletion(-) create mode 100644 backend/app/host_profile.py create mode 100644 scripts/_deploy_git_pull_both.py diff --git a/README.md b/README.md index bcb8a36..5792b7c 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,56 @@ cd desktop && npm install && npm run electron:dev ## 部署与访问地址(多环境) -**文档不写死任何生产域名或公网 IP。** 每台机器 / 每个环境用你自己的变量;下面用占位符说明。 +### 当前生产拓扑(nomadro) + +同一套代码,**三处入口、两台业务机 + 一台国内辅助**: + +| 站点 | 业务跑在哪 | 公网入口 | 说明 | +|------|------------|----------|------| +| [https://dylive.nomadro.com/](https://dylive.nomadro.com/) | **海外 VPS** `107.173.30.245`(root) | 本机 Caddy → `127.0.0.1:4015/8014` | 应用 + TLS **同机**;美国公网 IP,业务**天然出海**,不依赖控制台「网络」模块 | +| [https://dy.nomadro.com/](https://dy.nomadro.com/) | **PVE Ubuntu 物理机**(SSH `107.173.30.245:4014` eric) | VPS Caddy → WireGuard `wg-dy` → `10.8.0.2:4015/8014` | 全部业务在物理机;域名 TLS 与边缘反代在 VPS | +| [https://dy.nomadro.cn/](https://dy.nomadro.cn/) | 同一台物理机 | **腾讯云** `129.204.21.129` TLS → `wg-dy-cn` → 物理机 | 国内访问 / Neko WebRTC 辅助;腾讯云 WG 控 Neko,缓解美国 IP 过慢 | + +```text +浏览器 ──HTTPS──► dylive.nomadro.com ──► VPS 本机 Next/API/PB/S3 + (Neko 默认全关;单路独占建议开) + +浏览器 ──HTTPS──► dy.nomadro.com ──► VPS Caddy + │ wg-dy (10.8.0.0/24) + ▼ + 物理机 Ubuntu Next/API/Neko/ShellCrash + ▲ +浏览器(国内) ──HTTPS──► dy.nomadro.cn ──► 腾讯云 Caddy/Nginx + │ wg-dy-cn + └──────────┘ + +VPS sing-box ──三种翻墙协议──► 物理机 ShellCrash(Google / YouTube / Neko 出海) +VPS frpp :4014 ──仅应急 SSH──► 物理机(业务 HTTPS 仍以 WG 为主) +``` + +#### 核心区别(运维心智) + +| | VPS(dylive) | 物理机(dy.com / dy.cn) | +|--|--|--| +| 算力 | 弱,**默认关全部 Neko** | 够用,**Neko 可全开预热** | +| 出海 | 本机公网直连,**无需** ShellCrash / 住宅 SOCKS / 应用层 WG | 依赖 ShellCrash `:7890`;上游节点来自 VPS **sing-box** 下发的协议 | +| 「网络」页 | 业务侧应保持关闭(见首页主机开关 → VPS) | 需要:ShellCrash、住宅链、与边缘协同的 WG 状态 | +| 单路独占 | **默认开**(一路 FFmpeg,省内存) | **建议关**(多 Neko 预热 Studio) | +| TLS | 本机 | **只在边缘**(海外 VPS + 可选腾讯云);物理机不接公网 443 | +| 边缘不可停 | — | VPS 上 `sing-box` / `frpp` / `wg-quick@wg-dy*` **禁止当「省内存」关掉** | + +控制台顶栏 **内存右侧** 有 **VPS / 物理机** 开关:切到 VPS 会停止业务「网络」出口、停全部 Neko、开单路独占;切到物理机会把出口切回 ShellCrash 并关单路独占(不自动拉起全部 Neko,也不动边缘 WG/FRP/sing-box)。 + +#### 技术方案建议(简) + +- **dylive(VPS)**:只跑监控 + 可选单路转播;首页切 **VPS**;Neko 镜像可保留但不要常驻;封面走本机 S3;勿在本机再装 ShellCrash。 +- **物理机**:首页切 **物理机**;Neko 走 `dy.nomadro.cn` ICE(`DY_NEKO_NAT1TO1`=腾讯云公网 IP);HTTPS 主站仍 `dy.nomadro.com`;抖音探测 DIRECT,其余走 `:7890`。 +- **边缘 VPS**:专职 Caddy + `wg-dy` + 给物理机用的 sing-box 入站 + frpp 应急 SSH;省内存时只停无关业务,**永不**停这三项。 +- **故障隔离**:WG 挂了可用 frpp/SSH 辅链路救急,但业务反代应尽快回到 WG;不要把 FRP 当成长期 HTTPS 主路径。 + +> 新机器仍用占位符安装;下面通用表不写死域名。生产 nomadro 以本节为准。 + +**通用安装文档不写死域名或公网 IP。** 每台机器 / 每个环境用你自己的变量;下面用占位符说明。 本仓库有两种 **Linux 生产形态**(另有 Windows 桌面端,见上节): diff --git a/backend/app/db.py b/backend/app/db.py index 7a984e7..296cf3e 100644 --- a/backend/app/db.py +++ b/backend/app/db.py @@ -502,6 +502,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None: "egress_cover_neko": True, "egress_cover_relay": True, "egress_cover_uploads": True, + # Host shape: vps (lean) | physical (ShellCrash + multi-Neko). Empty = infer. + "host_profile": "", # TikTok pipeline (fully isolated from Shorts) "tiktok_enabled": False, "tiktok_clip_sec": 75, diff --git a/backend/app/host_profile.py b/backend/app/host_profile.py new file mode 100644 index 0000000..57393e7 --- /dev/null +++ b/backend/app/host_profile.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- +"""Host profile: VPS (lean) vs physical (full Neko + ShellCrash). + +Does **not** stop VPS edge systemd units (sing-box / frpp / wg-quick@wg-dy*). +Those are infrastructure for the physical site, not app「网络」toggles. +""" +from __future__ import annotations + +import os +from typing import Any + +PROFILES = ("vps", "physical") +_KEY = "host_profile" + + +def _settings() -> dict[str, Any]: + from . import db + + return dict(db.get_settings_map()) + + +def infer_profile(cfg: dict[str, Any] | None = None) -> str: + s = dict(cfg) if cfg is not None else _settings() + raw = str(s.get(_KEY) or "").strip().lower() + if raw in PROFILES: + return raw + edge = str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip() + if edge and edge not in {"127.0.0.1", "localhost", "::1"}: + return "physical" + bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "").strip() + if bind in {"0.0.0.0", "*"}: + return "physical" + return "vps" + + +def status() -> dict[str, Any]: + s = _settings() + profile = infer_profile(s) + return { + "ok": True, + "profile": profile, + "stored": str(s.get(_KEY) or "").strip().lower() in PROFILES, + "profiles": list(PROFILES), + "effects": { + "vps": [ + "egress / ShellCrash / 业务 SOCKS 全部关闭", + "全部 Neko 停止并关闭 neko_enabled", + "单路独占默认开启", + ], + "physical": [ + "业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)", + "单路独占默认关闭(允许多 Neko 预热)", + "不自动拉起全部 Neko(由分配页按需开启)", + ], + }, + "never_touches": [ + "sing-box.service", + "frpp.service", + "wg-quick@wg-dy.service", + "wg-quick@wg-dy-cn.service", + ], + } + + +def _disable_all_neko() -> dict[str, Any]: + from . import yt_assign_db + from . import youtube_neko + from .db import _connect, _lock + + disabled = 0 + with _lock: + conn = _connect() + try: + yt_assign_db.ensure_yt_assign_tables(conn) + cur = conn.execute( + "UPDATE yt_assign_groups SET neko_enabled = 0 WHERE neko_enabled != 0" + ) + disabled = int(cur.rowcount or 0) + conn.commit() + finally: + conn.close() + stopped = youtube_neko.stop_instances_except(0) + try: + youtube_neko.sync_for_groups( + yt_assign_db.list_groups(include_urls=False), + reconcile_running=True, + ) + except Exception as exc: + return { + "ok": False, + "disabled_flags": disabled, + "stopped_containers": stopped, + "error": str(exc)[:300], + } + return {"ok": True, "disabled_flags": disabled, "stopped_containers": stopped} + + +def apply_profile(profile: str) -> dict[str, Any]: + from . import db + from . import egress_hub + from . import shellcrash_hub + from . import singbox_manager + + raw = str(profile or "").strip().lower() + if raw not in PROFILES: + raise ValueError("profile must be vps or physical") + + steps: dict[str, Any] = {} + + if raw == "vps": + try: + steps["egress"] = egress_hub.apply_mode( + "off", + chain=False, + cover_neko_flag=False, + cover_relay_flag=False, + cover_uploads_flag=False, + refresh_neko=False, + ) + except Exception as exc: + steps["egress"] = {"ok": False, "error": str(exc)[:300]} + + try: + steps["singbox_app"] = singbox_manager.stop() + except Exception as exc: + steps["singbox_app"] = {"ok": False, "error": str(exc)[:300]} + + try: + steps["shellcrash"] = shellcrash_hub.action("stop") + except Exception as exc: + steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]} + + steps["neko"] = _disable_all_neko() + + # Exclusive-live in-memory state is applied in apply_profile_async. + db.update_settings_map( + { + _KEY: "vps", + "youtube_relay_exclusive_live": True, + "global_socks_enabled": False, + "shorts_upload_socks_enabled": False, + "egress_chain_residential": False, + } + ) + steps["settings"] = {"host_profile": "vps", "youtube_relay_exclusive_live": True} + + else: + try: + steps["egress"] = egress_hub.apply_mode( + "shellcrash", + chain=False, + refresh_neko=False, + ) + except Exception as exc: + # ShellCrash may be absent on pure VPS — still store profile + exclusive off. + db.update_settings_map({"egress_mode": "shellcrash"}) + steps["egress"] = {"ok": False, "error": str(exc)[:300], "settings_only": True} + + db.update_settings_map( + { + _KEY: "physical", + "youtube_relay_exclusive_live": False, + } + ) + steps["settings"] = { + "host_profile": "physical", + "youtube_relay_exclusive_live": False, + "neko": "not_auto_started", + } + steps["neko"] = {"ok": True, "note": "physical: leave Neko as-is; enable per group in assign UI"} + + return {"ok": True, "profile": raw, "steps": steps, **status()} + + +async def apply_profile_async(profile: str) -> dict[str, Any]: + """Async wrapper so exclusive-live pipeline state stays consistent.""" + import asyncio + + from . import db + from . import youtube_relay_pipeline + + raw = str(profile or "").strip().lower() + result = await asyncio.to_thread(apply_profile, raw) + # Re-apply exclusive via pipeline so in-memory winner/pause state matches. + exclusive_on = raw == "vps" + try: + result["steps"]["exclusive_live"] = await youtube_relay_pipeline.set_exclusive_live(exclusive_on) + except Exception as exc: + db.update_settings_map({"youtube_relay_exclusive_live": exclusive_on}) + result["steps"]["exclusive_live"] = {"ok": False, "error": str(exc)[:300], "settings_written": True} + result["profile"] = raw + return result diff --git a/backend/app/main.py b/backend/app/main.py index 508f1f0..1858fbc 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -3626,6 +3626,26 @@ async def ops_host_metrics() -> dict[str, Any]: return await asyncio.to_thread(host_metrics.snapshot) +@app.get("/api/ops/host-profile") +async def ops_host_profile_get() -> dict[str, Any]: + """Current VPS vs physical host profile (header switch).""" + from . import host_profile + + return await asyncio.to_thread(host_profile.status) + + +@app.post("/api/ops/host-profile") +async def ops_host_profile_set(body: dict[str, Any]) -> dict[str, Any]: + """Apply VPS (stop network egress + all Neko, exclusive on) or physical defaults.""" + from . import host_profile + + profile = str(body.get("profile") or "").strip().lower() + try: + return await host_profile.apply_profile_async(profile) + except ValueError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc + + @app.get("/api/ops") async def ops_snapshot() -> dict[str, Any]: """Umami / ntfy / DNS / systemd health snapshot for the ops control page.""" diff --git a/frontend/src/components/HostResourceBar.tsx b/frontend/src/components/HostResourceBar.tsx index 754bd25..7c0b005 100644 --- a/frontend/src/components/HostResourceBar.tsx +++ b/frontend/src/components/HostResourceBar.tsx @@ -2,6 +2,8 @@ import { useEffect, useState } from "react"; +import { useConfirm } from "@/components/ConfirmDialog"; +import { useToast } from "@/components/Toast"; import { fetchJson } from "@/lib/api"; type HostMetrics = { @@ -13,6 +15,8 @@ type HostMetrics = { cpu_cores?: number; }; +type HostProfile = "vps" | "physical"; + function barColor(pct: number) { if (pct >= 90) return "from-rose-500 to-orange-500"; if (pct >= 75) return "from-amber-400 to-orange-400"; @@ -42,6 +46,10 @@ function MetricBar({ label, pct, hint }: { label: string; pct: number; hint: str export function HostResourceBar() { const [m, setM] = useState(null); const [err, setErr] = useState(false); + const [profile, setProfile] = useState("vps"); + const [profileBusy, setProfileBusy] = useState(false); + const toast = useToast(); + const confirm = useConfirm(); useEffect(() => { let cancelled = false; @@ -70,6 +78,49 @@ export function HostResourceBar() { }; }, []); + useEffect(() => { + let cancelled = false; + void fetchJson("/api/ops/host-profile") + .then((d) => { + if (cancelled) return; + const p = String(d.profile || "").toLowerCase(); + if (p === "vps" || p === "physical") setProfile(p); + }) + .catch(() => {}); + return () => { + cancelled = true; + }; + }, []); + + async function switchProfile(next: HostProfile) { + if (next === profile || profileBusy) return; + const ok = await confirm({ + title: next === "vps" ? "切换为 VPS 配置?" : "切换为物理机配置?", + message: + next === "vps" + ? "将关闭业务「网络」出口(ShellCrash / SOCKS / 住宅链)、停止全部 Neko,并开启「单路独占」。不会停 VPS 边缘的 sing-box / frpp / wg-dy。" + : "将业务出口切回 ShellCrash,并关闭「单路独占」(允许多 Neko 预热)。不会自动启动全部 Neko,也不会动边缘 WG/FRP。", + confirmLabel: "确认切换", + cancelLabel: "取消", + destructive: next === "vps", + }); + if (!ok) return; + setProfileBusy(true); + try { + const d = await fetchJson("/api/ops/host-profile", { + method: "POST", + body: JSON.stringify({ profile: next }), + }); + const p = String(d.profile || next).toLowerCase(); + setProfile(p === "physical" ? "physical" : "vps"); + toast.push(next === "vps" ? "已应用 VPS 省资源配置" : "已应用物理机配置", "ok"); + } catch (e) { + toast.push((e as Error).message || "切换失败", "err"); + } finally { + setProfileBusy(false); + } + } + if (err && !m) { return

主机指标暂不可用

; } @@ -91,6 +142,45 @@ export function HostResourceBar() {
+
+ 主机 +
+ + +
+
); } diff --git a/scripts/_deploy_git_pull_both.py b/scripts/_deploy_git_pull_both.py new file mode 100644 index 0000000..7400712 --- /dev/null +++ b/scripts/_deploy_git_pull_both.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""Push-synced deploy: git reset to origin/test1 on dylive VPS + physical guest. + +Preserves monitor.db. Restarts api/web only — does NOT recreate Neko/Chrome. +""" +from __future__ import annotations + +import sys +import time +from pathlib import Path + +sys.stdout.reconfigure(encoding="utf-8", errors="replace") + +import paramiko + +REMOTE = "https://eric:Xiao4669805@gitea.dsx2020.com/eric/douyinWEB.git" +BRANCH = "test1" +REPO = "/opt/douyinWEB" + +# dylive colocated on overseas VPS +DYLIVE = ("107.173.30.245", 22, "root", "Xiao4669805") +# physical app guest via FRP +PHYSICAL = ("107.173.30.245", 4014, "eric", "4669805") +GUEST_SUDO = "4669805" + + +def connect(host: str, port: int, user: str, password: str) -> paramiko.SSHClient: + c = paramiko.SSHClient() + c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + c.connect(host, port, user, password, timeout=60, banner_timeout=120, allow_agent=False, look_for_keys=False) + return c + + +def run(c: paramiko.SSHClient, cmd: str, timeout: int = 600, label: str = "") -> tuple[int, str]: + tag = f"[{label}] " if label else "" + print(f"\n{tag}$ {cmd[:200]}{'…' if len(cmd) > 200 else ''}", flush=True) + _i, o, e = c.exec_command(cmd, timeout=timeout) + code = o.channel.recv_exit_status() + out = (o.read() + e.read()).decode("utf-8", "replace") + if out.strip(): + print(out[-6000:] if len(out) > 6000 else out, flush=True) + print(f"{tag}→ exit={code}", flush=True) + return code, out + + +def git_sync(c: paramiko.SSHClient, *, sudo_prefix: str, label: str) -> int: + ts = time.strftime("%Y%m%d_%H%M%S") + # backup db + run( + c, + f"{sudo_prefix}bash -lc 'cd {REPO} && cp -a backend/data/monitor.db backend/data/monitor.db.bak.{ts} 2>/dev/null || true && ls -la backend/data/monitor.db | head -1'", + timeout=60, + label=label, + ) + code, _ = run( + c, + f"{sudo_prefix}bash -lc 'set -e; cd {REPO}; " + f"git remote set-url origin \"{REMOTE}\"; " + f"git fetch origin {BRANCH}; " + f"git reset --hard HEAD; " + f"git clean -fd -e backend/data -e frontend/.next -e node_modules -e frontend/node_modules " + f"-e backend/.venv -e .venv -e \"*.db\" -e \"*.db-*\"; " + f"git checkout -f -B {BRANCH} origin/{BRANCH}; " + f"git reset --hard origin/{BRANCH}; " + f"git log -1 --oneline; git status -sb'", + timeout=300, + label=label, + ) + return code + + +def deps_and_restart(c: paramiko.SSHClient, *, sudo_prefix: str, label: str, public_health: str) -> int: + run( + c, + f"{sudo_prefix}bash -lc 'cd {REPO}/backend; " + f"if [ -f requirements.txt ]; then " + f" (test -x .venv/bin/pip && .venv/bin/pip install -r requirements.txt -q) || " + f" (test -x ../.venv/bin/pip && ../.venv/bin/pip install -r requirements.txt -q) || true; " + f"fi; echo deps_ok'", + timeout=300, + label=label, + ) + run( + c, + f"{sudo_prefix}bash -lc 'systemctl restart douyinweb-api douyinweb-pb douyinweb-yt 2>/dev/null || systemctl restart douyinweb-api; sleep 2; systemctl is-active douyinweb-api || true'", + timeout=90, + label=label, + ) + code, _ = run( + c, + f"{sudo_prefix}bash -lc 'set -e; cd {REPO}/frontend; npm ci --prefer-offline 2>/dev/null || npm install; npm run build'", + timeout=900, + label=label, + ) + if code != 0: + return code + run( + c, + f"{sudo_prefix}bash -lc 'systemctl restart douyinweb-web; sleep 2; systemctl is-active douyinweb-api douyinweb-web'", + timeout=90, + label=label, + ) + run( + c, + f"bash -lc 'curl -sS -m 15 http://127.0.0.1:8014/api/health | head -c 400; echo; " + f"curl -sS -m 20 -o /dev/null -w \"public=%{{http_code}}\\n\" {public_health}; " + f"cd {REPO}; git rev-parse --short HEAD; " + f"test -f backend/data/monitor.db && echo monitor_db=ok'", + timeout=60, + label=label, + ) + return 0 + + +def deploy_host(spec: tuple, *, label: str, public_health: str, use_sudo: bool) -> int: + host, port, user, pw = spec + print(f"\n======== {label} {host}:{port} ========", flush=True) + c = connect(host, port, user, pw) + try: + if use_sudo: + sudo_prefix = f"echo '{GUEST_SUDO}' | sudo -S -p '' " + else: + sudo_prefix = "" + if git_sync(c, sudo_prefix=sudo_prefix, label=label) != 0: + print(f"FATAL: {label} git sync failed", flush=True) + return 1 + if deps_and_restart(c, sudo_prefix=sudo_prefix, label=label, public_health=public_health) != 0: + print(f"FATAL: {label} build/restart failed", flush=True) + return 1 + print(f"OK {label}", flush=True) + return 0 + finally: + c.close() + + +def main() -> int: + rc = 0 + if deploy_host(DYLIVE, label="dylive", public_health="https://dylive.nomadro.com/api/health", use_sudo=False) != 0: + rc = 1 + if deploy_host(PHYSICAL, label="physical", public_health="https://dy.nomadro.com/api/health", use_sudo=True) != 0: + rc = 1 + print(f"\nDONE rc={rc}", flush=True) + return rc + + +if __name__ == "__main__": + raise SystemExit(main())