# -*- coding: utf-8 -*- """ Deploy douyinWEB onto PVE Ubuntu guest (10.8.0.2) and add dy.nomadro.com Caddy site. VPS live-traffic rules: - Never restart caddy/docker/sing-box/wordpress/umami/ntfy - Never edit existing Caddy site files (especially dylive.nomadro.com) - After Caddy change: validate then `systemctl reload caddy` only - Verify dylive health before and after reload """ from __future__ import annotations import os import sys import tarfile import tempfile import time from pathlib import Path import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") VPS = "107.173.30.245" ROOT_PASS = "Xiao4669805" ERIC_PASS = "4669805" DOMAIN = "dy.nomadro.com" PUBLIC_BASE = f"https://{DOMAIN}" ADMIN_USER = "hackrobot" ADMIN_PASS = "Xiao4669805@" APP_DIR = "/opt/douyinWEB" LOCAL_ROOT = Path(__file__).resolve().parents[1] PVE_WG = "10.8.0.2" WEB_PORT, API_PORT, PB_PORT, YT_PORT, S3_PORT = 4015, 8014, 8092, 8020, 8333 PB_VER, WEED_VER = "0.25.8", "3.80" SKIP_DIR_NAMES = { ".git", "node_modules", ".next", "__pycache__", ".venv", "venv", # Keep backend/neko/tampermonkey-seed in pack — Neko Studio auth needs it on physical. ".cursor", "pb_data", "_audit", } # Runtime data only — do NOT skip frontend/src/app/covers (the Next.js page) SKIP_PATH_PREFIXES = ( "backend/data/covers/", "backend/data/clips/", ) SKIP_FILES = {"monitor.db", "monitor.db-shm", "monitor.db-wal"} def should_skip(rel: str) -> bool: parts = Path(rel).parts posix = rel.replace("\\", "/") if any(posix == p.rstrip("/") or posix.startswith(p) for p in SKIP_PATH_PREFIXES): return True if any(p in SKIP_DIR_NAMES for p in parts): return True name = Path(rel).name if name in SKIP_FILES or name.endswith((".pyc", ".pyo")): return True if rel.replace("\\", "/").startswith("scripts/_") and rel.endswith(".txt"): return True return False def make_tarball() -> Path: tmp = tempfile.NamedTemporaryFile(suffix=".tar.gz", delete=False) tmp.close() tar_path = Path(tmp.name) print(f"[pack] {LOCAL_ROOT} -> {tar_path}", flush=True) n = 0 with tarfile.open(tar_path, "w:gz") as tar: for root, dirs, files in os.walk(LOCAL_ROOT): dirs[:] = [d for d in dirs if d not in SKIP_DIR_NAMES and not d.startswith(".git")] for name in files: full = Path(root) / name rel = full.relative_to(LOCAL_ROOT).as_posix() if should_skip(rel): continue tar.add(full, arcname=rel) n += 1 print(f"[pack] {n} files, {tar_path.stat().st_size / 1024 / 1024:.1f} MB", flush=True) return tar_path def ssh(host, port, user, password): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(host, port, user, password, timeout=40, allow_agent=False, look_for_keys=False, banner_timeout=30) return c def run(c, cmd, timeout=120): _, o, e = c.exec_command(cmd, timeout=timeout) return (o.read() + e.read()).decode("utf-8", "replace") def must_dylive(v, label): out = run( v, "curl -sS -m 8 -o /dev/null -w '%{http_code}' https://dylive.nomadro.com/api/health", 15, ).strip() print(f"[dylive {label}] {out}", flush=True) if out != "200": raise SystemExit(f"ABORT: dylive health {out} after {label}") BOOTSTRAP = r"""#!/usr/bin/env bash set -euo pipefail exec > >(tee -a /tmp/dy_pve_bootstrap.log) 2>&1 DOMAIN="dy.nomadro.com" ADMIN_USER="hackrobot" ADMIN_PASS="Xiao4669805@" APP_DIR="/opt/douyinWEB" PUBLIC_BASE="https://dy.nomadro.com" PVE_WG="10.8.0.2" VPS_PUBLIC_IP="107.173.30.245" WEB_PORT=4015 API_PORT=8014 PB_PORT=8092 YT_PORT=8020 S3_PORT=8333 SW_MASTER_PORT=19333 SW_VOLUME_PORT=18080 SW_FILER_PORT=18888 S3_ACCESS=douyin S3_BUCKET=douyin-covers PB_ADMIN_EMAIL="${ADMIN_USER}@${DOMAIN}" ENV_FILE=/etc/douyinweb.env log() { printf '\n[%s] %s\n' "$(date '+%F %T')" "$*"; } [[ "$(id -u)" -eq 0 ]] [[ ! -d /etc/pve ]] || { echo REFUSE_PVE_HOST; exit 2; } log "extract $APP_DIR" mkdir -p "$APP_DIR" find "$APP_DIR" -mindepth 1 -maxdepth 1 -exec rm -rf {} + tar -xzf /tmp/douyinweb_deploy.tar.gz -C "$APP_DIR" rm -f "$APP_DIR/backend/data/monitor.db" \ "$APP_DIR/backend/data/monitor.db-shm" \ "$APP_DIR/backend/data/monitor.db-wal" mkdir -p "$APP_DIR/backend/data/covers" "$APP_DIR/backend/data/clips" "$APP_DIR/pb/pb_data" if [ ! -f "$ENV_FILE" ]; then SESSION_SECRET=$(openssl rand -hex 24) S3_SECRET=$(openssl rand -hex 18) cat >"$ENV_FILE" </etc/seaweedfs/douyinweb-s3.json </etc/systemd/system/douyinweb-pb.service </etc/systemd/system/douyinweb-yt.service </etc/systemd/system/douyinweb-api.service </etc/systemd/system/douyinweb-web.service </etc/systemd/system/wg-quick@wg-dy.service.d/override.conf <<'WGEOF' [Service] ExecStart= ExecStart=/usr/bin/bash -c 'if ip link show wg-dy >/dev/null 2>&1; then exit 0; else exec /usr/bin/wg-quick up wg-dy; fi' ExecStop= ExecStop=/usr/bin/bash -c 'if ip link show wg-dy >/dev/null 2>&1; then exec /usr/bin/wg-quick down wg-dy; else exit 0; fi' WGEOF cat >/etc/systemd/system/douyinweb-sw-master.service </etc/systemd/system/douyinweb-sw-volume.service </etc/systemd/system/douyinweb-sw-filer.service </etc/systemd/system/douyinweb-s3.service < {remote}", flush=True) sftp = client.open_sftp() sftp.put(str(local), remote) sftp.close() def main() -> int: v = ssh(VPS, 22, "root", ROOT_PASS) must_dylive(v, "start") print("=== VPS download pb+weed (US) ===", flush=True) print( run( v, f"set -e; " f"if [ ! -s /tmp/pocketbase.zip ]; then curl -fsSL -o /tmp/pocketbase.zip " f"'https://github.com/pocketbase/pocketbase/releases/download/v{PB_VER}/pocketbase_{PB_VER}_linux_amd64.zip'; fi; " f"if [ ! -s /tmp/weed.tgz ]; then curl -fsSL -o /tmp/weed.tgz " f"'https://github.com/seaweedfs/seaweedfs/releases/download/{WEED_VER}/linux_amd64.tar.gz'; fi; " f"ls -lh /tmp/pocketbase.zip /tmp/weed.tgz", 180, ), flush=True, ) must_dylive(v, "after github downloads") print("=== ssh key VPS -> PVE over wg-dy (no VPS service restart) ===", flush=True) print( run( v, "mkdir -p /root/.ssh; chmod 700 /root/.ssh; " "if [ ! -f /root/.ssh/pve_wg_deploy ]; then " "ssh-keygen -t ed25519 -f /root/.ssh/pve_wg_deploy -N '' -C pve-wg-deploy; fi; " "cat /root/.ssh/pve_wg_deploy.pub", 20, ), flush=True, ) pubkey = run(v, "cat /root/.ssh/pve_wg_deploy.pub", 10).strip() p = ssh(VPS, 4014, "eric", ERIC_PASS) run( p, f"mkdir -p ~/.ssh; chmod 700 ~/.ssh; touch ~/.ssh/authorized_keys; chmod 600 ~/.ssh/authorized_keys; " f"grep -qxF '{pubkey}' ~/.ssh/authorized_keys || echo '{pubkey}' >> ~/.ssh/authorized_keys", 15, ) p.close() print( run( v, f"ssh -i /root/.ssh/pve_wg_deploy -o StrictHostKeyChecking=accept-new " f"-o UserKnownHostsFile=/root/.ssh/known_hosts_pve " f"eric@{PVE_WG} 'echo pve_ssh_ok'", 20, ), flush=True, ) tar_path = make_tarball() print("=== upload tarball to VPS then PVE ===", flush=True) sftp_put(v, tar_path, "/tmp/douyinweb_deploy.tar.gz", "tarball") os.unlink(tar_path) print( run( v, f"scp -i /root/.ssh/pve_wg_deploy -o StrictHostKeyChecking=accept-new " f"-o UserKnownHostsFile=/root/.ssh/known_hosts_pve " f"/tmp/douyinweb_deploy.tar.gz /tmp/pocketbase.zip /tmp/weed.tgz " f"eric@{PVE_WG}:/tmp/ && echo SCP_OK && ls -lh /tmp/douyinweb_deploy.tar.gz", 300, ), flush=True, ) must_dylive(v, "after scp to pve") print("=== write bootstrap on PVE and nohup ===", flush=True) p = ssh(VPS, 4014, "eric", ERIC_PASS) sftp = p.open_sftp() with sftp.file("/tmp/bootstrap_pve_dy.sh", "w") as f: f.write(BOOTSTRAP) sftp.chmod("/tmp/bootstrap_pve_dy.sh", 0o755) sftp.close() print( run( p, "echo '4669805' | sudo -S -p '' bash -c '" "systemctl reset-failed dy-pve-bootstrap 2>/dev/null || true; " "systemctl stop dy-pve-bootstrap 2>/dev/null || true; " ": > /tmp/dy_pve_bootstrap.log; " "systemd-run --unit=dy-pve-bootstrap --collect --property=StandardOutput=append:/tmp/dy_pve_bootstrap.log " "--property=StandardError=append:/tmp/dy_pve_bootstrap.log bash /tmp/bootstrap_pve_dy.sh; " "echo LAUNCHED; systemctl is-active dy-pve-bootstrap || true" "'", 20, ), flush=True, ) p.close() print("=== poll bootstrap log ===", flush=True) done = False last_len = 0 for i in range(90): time.sleep(20) try: p = ssh(VPS, 4014, "eric", ERIC_PASS) log = run(p, "tail -c 4000 /tmp/dy_pve_bootstrap.log 2>/dev/null || echo WAITING", 20) p.close() except Exception as ex: print(f"[poll {i}] ssh retry {ex}", flush=True) continue if len(log) != last_len: print(f"\n----- poll {i} -----\n{log[-1800:]}", flush=True) last_len = len(log) if "BOOTSTRAP_DONE" in log: done = True break if "REFUSE_PVE_HOST" in log or "Error:" in log and "npm ERR" in log: # keep polling npm errors until timeout pass print(".", end="", flush=True) if not done: raise SystemExit("bootstrap did not finish in time — check /tmp/dy_pve_bootstrap.log") must_dylive(v, "after pve bootstrap") print("=== VPS reach PVE app over wg-dy ===", flush=True) print( run( v, "curl -sS -m 10 -o /dev/null -w 'api:%{http_code}\\n' http://10.8.0.2:8014/api/health; " "curl -sS -m 10 http://10.8.0.2:8014/api/health | head -c 300; echo; " "curl -sS -m 10 -o /dev/null -w 'web:%{http_code}\\n' http://10.8.0.2:4015/login", 25, ), flush=True, ) print("=== add NEW caddy site only, validate, reload (not restart) ===", flush=True) must_dylive(v, "before caddy write") sftp = v.open_sftp() with sftp.file("/etc/caddy/sites/dy.nomadro.com.caddy", "w") as f: f.write(CADDY_SITE) sftp.close() val = run(v, "caddy validate --config /etc/caddy/Caddyfile 2>&1", 30) print(val, flush=True) if "Valid configuration" not in val and "valid" not in val.lower(): run(v, "rm -f /etc/caddy/sites/dy.nomadro.com.caddy", 10) raise SystemExit("caddy validate failed — new site removed, dylive untouched") print(run(v, "systemctl reload caddy; sleep 2; systemctl is-active caddy", 20), flush=True) time.sleep(8) must_dylive(v, "after caddy reload") print( run( v, "curl -sS -m 25 -o /dev/null -w 'dy_login:%{http_code}\\n' https://dy.nomadro.com/login; " "curl -sS -m 25 -o /dev/null -w 'dy_api:%{http_code}\\n' https://dy.nomadro.com/api/health; " "curl -sS -m 12 https://dy.nomadro.com/api/health | head -c 300; echo; " "curl -sS -m 8 -o /dev/null -w 'dylive:%{http_code}\\n' https://dylive.nomadro.com/api/health; " "systemctl is-active caddy sing-box docker", 50, ), flush=True, ) v.close() print(f"URL {PUBLIC_BASE}/ login {ADMIN_USER}", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())