douyinWEB/scripts/_finish_physical_neko.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

217 lines
6.8 KiB
Python

# -*- coding: utf-8 -*-
"""Finish remaining physical steps: FE build status, restart web, neko sync, Caddy."""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
VPS = "107.173.30.245"
PVE_WG = "10.8.0.2"
GUEST_PW = "4669805"
VPS_PW = "Xiao4669805"
def ssh(host, port, user, password, tries=8):
last = None
for i in range(tries):
try:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
host,
port,
user,
password,
timeout=60,
banner_timeout=90,
auth_timeout=60,
allow_agent=False,
look_for_keys=False,
)
return c
except Exception as ex:
last = ex
print(f"ssh {host}:{port} fail{i}: {type(ex).__name__}", flush=True)
time.sleep(2 + i)
raise last # type: ignore[misc]
def run(c, cmd, timeout=300):
_, o, e = c.exec_command(cmd, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def sudo(cmd: str) -> str:
return f"echo '{GUEST_PW}' | sudo -S -p '' bash -lc {repr(cmd)}"
def must_dylive(v, label):
code = run(v, "curl -sS -m 8 -o /dev/null -w '%{http_code}' https://dylive.nomadro.com/api/health", 15).strip()
print(f"[dylive {label}] {code}", flush=True)
if code != "200":
raise SystemExit(f"ABORT dylive {code}")
def main() -> int:
g = ssh(VPS, 4014, "eric", GUEST_PW)
print("=== FE build log ===", flush=True)
print(run(g, "tail -n 30 /tmp/fe-build.log 2>/dev/null || echo NO_LOG", 30), flush=True)
st = run(
g,
"grep -q '^EXIT:' /tmp/fe-build.log 2>/dev/null && grep '^EXIT:' /tmp/fe-build.log | tail -1 || "
"(pgrep -af 'npm run build|next build' || echo NO_BUILD_PROC)",
30,
)
print("build_state:", st.strip(), flush=True)
if "EXIT:0" not in st and "EXIT:" not in st:
# start or wait — if no proc, start
if "NO_BUILD_PROC" in st or "npm" not in st:
print("starting frontend build...", flush=True)
print(
run(
g,
sudo(
"cd /opt/douyinWEB/frontend; "
"export DY_INTERNAL_API_URL=http://127.0.0.1:8014 DY_PUBLIC_BASE_URL=https://dy.nomadro.com; "
"rm -f /tmp/fe-build.log; "
"nohup bash -c 'npm run build > /tmp/fe-build.log 2>&1; echo EXIT:$? >> /tmp/fe-build.log' >/dev/null 2>&1 & "
"echo STARTED"
),
30,
),
flush=True,
)
g.close()
for i in range(1, 50):
time.sleep(10)
g = ssh(VPS, 4014, "eric", GUEST_PW)
tail = run(g, "tail -n 3 /tmp/fe-build.log 2>/dev/null; grep '^EXIT:' /tmp/fe-build.log 2>/dev/null | tail -1", 20)
print(f"[build {i}] {tail.strip()[-250:]}", flush=True)
if "EXIT:0" in tail:
break
if "EXIT:" in tail and "EXIT:0" not in tail:
raise SystemExit("frontend build failed")
g.close()
else:
raise SystemExit("frontend build timeout")
elif "EXIT:0" not in st:
raise SystemExit(f"frontend build bad: {st}")
else:
print("frontend already built OK", flush=True)
print("=== restart web + neko sync ===", flush=True)
if g.get_transport() is None or not g.get_transport().is_active():
g = ssh(VPS, 4014, "eric", GUEST_PW)
print(run(g, sudo("systemctl restart douyinweb-web; sleep 2; systemctl is-active douyinweb-api douyinweb-web"), 40), flush=True)
print(
run(
g,
sudo(
"cd /opt/douyinWEB/backend; .venv/bin/python - <<'PY'\n"
"from app import youtube_neko, yt_assign_db, network_hub\n"
"groups = yt_assign_db.list_groups()\n"
"print('groups', len(groups))\n"
"print('sync', youtube_neko.sync_for_groups(groups))\n"
"print('caddy', youtube_neko.sync_caddy_neko_snippet(max(1, len(groups) or 4)))\n"
"print('neko_status', youtube_neko.status_summary())\n"
"print('network_keys', sorted((network_hub.snapshot() or {}).keys())[:20])\n"
"PY"
),
180,
),
flush=True,
)
g.close()
print("=== Caddy /neko routes ===", flush=True)
v = ssh(VPS, 22, "root", VPS_PW)
must_dylive(v, "before_caddy")
blocks = []
for i in range(1, 5):
port = 9200 + i - 1
blocks.append(
f"""
handle /neko/{i} {{
redir /neko/{i}/ 308
}}
handle_path /neko/{i}/* {{
reverse_proxy {PVE_WG}:{port} {{
header_up Host {{host}}
header_up X-Forwarded-Proto {{scheme}}
}}
}}"""
)
caddy = f"""# Physical app — dy.nomadro.com → WG {PVE_WG}
# Do not edit dylive.nomadro.com.caddy
dy.nomadro.com {{
encode gzip
request_body {{
max_size 200MB
}}
handle /api/* {{
reverse_proxy {PVE_WG}:8014 {{
header_up Host {{host}}
}}
}}
handle /covers/* {{
reverse_proxy {PVE_WG}:8014 {{
header_up Host {{host}}
}}
}}
{''.join(blocks)}
handle /_/* {{
reverse_proxy {PVE_WG}:8092 {{
header_up Host {{host}}
}}
}}
handle /douyin-covers/* {{
reverse_proxy {PVE_WG}:8333 {{
header_up Host {{host}}
}}
}}
handle {{
reverse_proxy {PVE_WG}:4015 {{
header_up Host {{host}}
}}
}}
}}
"""
sftp = v.open_sftp()
with sftp.file("/etc/caddy/sites/dy.nomadro.com.caddy", "w") as f:
f.write(caddy)
sftp.close()
val = run(v, "caddy validate --config /etc/caddy/Caddyfile 2>&1", 30)
print(val[-500:], flush=True)
if "Valid configuration" not in val and "valid" not in val.lower():
raise SystemExit("caddy validate failed")
print(run(v, "systemctl reload caddy; sleep 2; systemctl is-active caddy", 20), flush=True)
must_dylive(v, "after_caddy")
print("=== public probes ===", flush=True)
print(
run(
v,
"curl -sS -m 12 -o /dev/null -w 'dy_api:%{http_code}\\n' https://dy.nomadro.com/api/health; "
"curl -sS -m 12 -o /dev/null -w 'dy_network:%{http_code}\\n' https://dy.nomadro.com/network; "
"curl -sS -m 12 -o /dev/null -w 'dy_neko1:%{http_code}\\n' https://dy.nomadro.com/neko/1/; "
"curl -sS -m 12 http://10.8.0.2:8014/api/network | head -c 600; echo; "
"curl -sS -m 8 -o /dev/null -w 'dylive:%{http_code}\\n' https://dylive.nomadro.com/api/health",
40,
),
flush=True,
)
v.close()
print("DONE", flush=True)
return 0
if __name__ == "__main__":
raise SystemExit(main())