# -*- coding: utf-8 -*- """Resume physical Neko + network tab setup after SSH drop. Reconnects SSH between long steps. Does not touch dylive / sing-box. """ from __future__ import annotations import sys import time from pathlib import Path import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") ROOT = Path(__file__).resolve().parents[1] VPS = "107.173.30.245" PVE_WG = "10.8.0.2" GUEST_PW = "4669805" VPS_PW = "Xiao4669805" def ssh(host, port, user, password, tries: int = 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__}: {ex}", flush=True) time.sleep(2 + i * 2) 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 guest(): return ssh(VPS, 4014, "eric", GUEST_PW) def vps(): return ssh(VPS, 22, "root", VPS_PW) 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 sudo(cmd: str) -> str: return f"echo '{GUEST_PW}' | sudo -S -p '' bash -lc {repr(cmd)}" def main() -> int: v = vps() must_dylive(v, "start") print("=== guest probe ===", flush=True) p = guest() print( run( p, sudo( "docker --version; " "docker images ghcr.io/m1k1o/neko/google-chrome:3.0.0 --format '{{.ID}} {{.Repository}}:{{.Tag}}' || true; " "ls -la /opt/douyinWEB/backend/neko/tampermonkey-seed 2>/dev/null | head -5 || echo NO_SEED; " "test -f /opt/douyinWEB/backend/app/network_hub.py && echo HAS_NETWORK_HUB || echo NO_NETWORK_HUB; " "test -f /opt/douyinWEB/frontend/src/app/network/page.tsx && echo HAS_NETWORK_PAGE || echo NO_NETWORK_PAGE; " "ip -br a show wg-dy 2>/dev/null || echo NO_WG; " "systemctl is-active douyinweb-api douyinweb-web docker 2>/dev/null; " "grep -E 'DY_NEKO_' /etc/systemd/system/douyinweb-api.service || echo NO_NEKO_ENV" ), 60, ), flush=True, ) p.close() # Re-upload files in case install assets aborted mid-way print("=== re-upload code ===", flush=True) p = guest() sftp = p.open_sftp() for rel in ( "backend/app/youtube_neko.py", "backend/app/network_hub.py", "backend/app/global_socks.py", "backend/app/main.py", "frontend/src/lib/shellNav.ts", "frontend/src/app/network/page.tsx", ): local = ROOT / rel if local.is_file(): sftp.put(str(local), f"/tmp/_up_{local.name}") print(f" put {rel}", flush=True) sftp.close() print( run( p, sudo( "set -e; " "install -m 644 /tmp/_up_youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py; " "install -m 644 /tmp/_up_network_hub.py /opt/douyinWEB/backend/app/network_hub.py; " "install -m 644 /tmp/_up_global_socks.py /opt/douyinWEB/backend/app/global_socks.py; " "install -m 644 /tmp/_up_main.py /opt/douyinWEB/backend/app/main.py; " "mkdir -p /opt/douyinWEB/frontend/src/app/network; " "install -m 644 /tmp/_up_shellNav.ts /opt/douyinWEB/frontend/src/lib/shellNav.ts; " "install -m 644 /tmp/_up_page.tsx /opt/douyinWEB/frontend/src/app/network/page.tsx; " "mkdir -p /opt/douyinWEB/backend/neko /opt/douyinWEB/backend/data/neko; " "if [ ! -d /opt/douyinWEB/backend/neko/tampermonkey-seed ] && [ -f /tmp/tampermonkey-seed.tar.gz ]; then " " tar -xzf /tmp/tampermonkey-seed.tar.gz -C /opt/douyinWEB/backend/neko; " "fi; " "grep -q DY_NEKO_EDGE_UPSTREAM /etc/systemd/system/douyinweb-api.service || " " sed -i '/DY_SESSION_SECRET=/a Environment=DY_NEKO_EDGE_UPSTREAM=10.8.0.2' /etc/systemd/system/douyinweb-api.service; " "grep -q DY_NEKO_NAT1TO1 /etc/systemd/system/douyinweb-api.service || " " sed -i '/DY_NEKO_EDGE_UPSTREAM=/a Environment=DY_NEKO_NAT1TO1=107.173.30.245' /etc/systemd/system/douyinweb-api.service; " "systemctl daemon-reload; " "systemctl restart douyinweb-api; sleep 3; systemctl is-active douyinweb-api; " "ls /opt/douyinWEB/backend/neko/tampermonkey-seed 2>/dev/null | head -3 || echo SEED_MISSING" ), 120, ), flush=True, ) p.close() print("=== docker pull (reconnect-safe) ===", flush=True) p = guest() # Run pull in background via nohup so FRP idle can't strand us mid-stream as badly print( run( p, sudo( "if docker image inspect ghcr.io/m1k1o/neko/google-chrome:3.0.0 >/dev/null 2>&1; then " " echo IMAGE_OK; " "else " " nohup docker pull ghcr.io/m1k1o/neko/google-chrome:3.0.0 " " >/tmp/neko-pull.log 2>&1 & echo PULL_PID=$!; " "fi" ), 30, ), flush=True, ) p.close() for i in range(60): time.sleep(15) p = guest() st = run( p, sudo( "if docker image inspect ghcr.io/m1k1o/neko/google-chrome:3.0.0 >/dev/null 2>&1; then " " echo READY; " "elif pgrep -f 'docker pull.*neko/google-chrome' >/dev/null; then " " echo PULLING; tail -n 2 /tmp/neko-pull.log 2>/dev/null; " "else " " echo FAILED; tail -n 20 /tmp/neko-pull.log 2>/dev/null; " "fi" ), 30, ) p.close() print(f"[{i}] {st.strip()[:200]}", flush=True) if "READY" in st: break if "FAILED" in st: raise SystemExit("docker pull failed") else: raise SystemExit("docker pull timeout") print("=== frontend build ===", flush=True) p = guest() # Start build in background; poll print( run( p, sudo( "cd /opt/douyinWEB/frontend; " "export DY_INTERNAL_API_URL=http://127.0.0.1:8014 DY_PUBLIC_BASE_URL=https://dy.nomadro.com; " "nohup bash -c 'npm run build > /tmp/fe-build.log 2>&1; echo EXIT:$? >> /tmp/fe-build.log' & " "echo BUILD_PID=$!" ), 30, ), flush=True, ) p.close() for i in range(40): time.sleep(15) p = guest() st = run( p, "tail -n 5 /tmp/fe-build.log 2>/dev/null; " "grep -q '^EXIT:' /tmp/fe-build.log 2>/dev/null && echo BUILD_DONE || echo BUILD_RUNNING", 30, ) p.close() print(f"[build {i}] {st.strip()[-300:]}", flush=True) if "BUILD_DONE" in st: if "EXIT:0" not in st and "EXIT:0" not in run(guest(), "grep '^EXIT:' /tmp/fe-build.log", 15): # re-check exit ex = run(guest(), "grep '^EXIT:' /tmp/fe-build.log | tail -1", 15) print("exit line:", ex, flush=True) if "EXIT:0" not in ex: raise SystemExit("frontend build failed") break else: raise SystemExit("frontend build timeout") p = guest() print( run( p, sudo("systemctl restart douyinweb-web; sleep 2; systemctl is-active douyinweb-web"), 30, ), flush=True, ) print( run( p, sudo( "cd /opt/douyinWEB/backend; .venv/bin/python - <<'PY'\n" "from app import youtube_neko, yt_assign_db\n" "groups = yt_assign_db.list_groups()\n" "print('groups', len(groups))\n" "r = youtube_neko.sync_for_groups(groups)\n" "print('sync', r)\n" "print('caddy', youtube_neko.sync_caddy_neko_snippet(max(1, len(groups) or 1)))\n" "print('status', youtube_neko.status_summary())\n" "PY" ), 180, ), flush=True, ) p.close() print("=== caddy neko routes ===", flush=True) must_dylive(v, "before caddy") neko_blocks = [] for i in range(1, 5): port = 9200 + i - 1 neko_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(neko_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[-600:], 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( 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 500; echo; " "curl -sS -m 12 -H 'Cookie: ' http://10.8.0.2:8014/api/youtube/neko/status 2>/dev/null | head -c 400; echo", 40, ), flush=True, ) v.close() print("DONE", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())