#!/usr/bin/env python3 """Deploy stream-key registry to dy + dylive. SAFETY: - Copy only listed app/frontend files - Restart douyinweb-api + douyinweb-web only - NEVER docker stop/rm/recreate any neko* - NEVER wipe profiles / monitor.db / assign tables """ from __future__ import annotations import json import sys import time from pathlib import Path import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") ROOT = Path(__file__).resolve().parents[1] HOSTS = [ ("dy", "108.174.50.68", "https://dy.nomadro.live"), ("dylive", "107.173.30.245", "https://dylive.nomadro.com"), ] PASS = "Xiao4669805" FILES = [ "backend/app/yt_stream_key_db.py", "backend/app/models.py", "backend/app/main.py", "frontend/src/app/youtube/keys/page.tsx", "frontend/src/components/YtAssignPanel.tsx", ] def connect(host: str): last = None for i in range(8): try: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( host, 22, "root", PASS, timeout=45, allow_agent=False, look_for_keys=False, banner_timeout=180, ) return c except Exception as e: last = e print(f" ssh_retry {i} {host}: {e}", flush=True) time.sleep(2 + i) raise SystemExit(f"ssh fail {host}: {last}") def run(c, cmd: str, t: int = 600) -> tuple[int, str]: _i, o, e = c.exec_command(cmd, timeout=t) out = (o.read() + e.read()).decode("utf-8", "replace") code = o.channel.recv_exit_status() return code, out def upload_files(c, label: str) -> None: sftp = c.open_sftp() for rel in FILES: local = ROOT / rel assert local.is_file(), local remote = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}" # ensure dir parts = remote.split("/")[:-1] cur = "" for p in parts: if not p: continue cur += "/" + p try: sftp.stat(cur) except OSError: try: sftp.mkdir(cur) except OSError: pass print(f" put {rel} -> {remote}", flush=True) sftp.put(str(local), remote) sftp.close() def deploy_one(label: str, host: str, public: str) -> None: print(f"\n======== {label} {host} ========", flush=True) c = connect(host) # snapshot neko before code, before = run( c, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " "systemctl is-active douyinweb-api douyinweb-web", ) print("BEFORE:\n" + before, flush=True) upload_files(c, label) # rebuild web + restart api ONLY — no neko touch code, out = run( c, r""" set -euo pipefail # guard: refuse if any command would touch neko (sanity) cd /opt/douyinWEB/backend # syntax check new module ./.venv/bin/python -c 'from app import yt_stream_key_db, models; print("py_ok", yt_stream_key_db)' systemctl restart douyinweb-api sleep 4 systemctl is-active douyinweb-api # frontend rebuild (Next) without docker if [ -d /opt/douyinWEB/frontend ]; then cd /opt/douyinWEB/frontend if [ -f package.json ]; then # prefer existing next build flow used on host if systemctl list-unit-files | grep -q '^douyinweb-web'; then # build then restart web export NODE_ENV=production if [ -d node_modules ]; then npm run build else echo 'WARN no node_modules — skip build, restart web only' fi systemctl restart douyinweb-web sleep 3 systemctl is-active douyinweb-web fi fi fi # seed registry from assign (safe: only new table) cd /opt/douyinWEB/backend ./.venv/bin/python - <<'PY' from app import yt_stream_key_db print(yt_stream_key_db.import_from_assign_groups(replace=False)) print(yt_stream_key_db.list_entries(include_secret=False)) PY curl -sS -m 10 http://127.0.0.1:8014/api/health | head -c 180; echo curl -sS -m 10 -o /dev/null -w 'keys_api:%{http_code}\n' http://127.0.0.1:8014/api/youtube/stream-keys || true """, t=900, ) print(out[-8000:] if len(out) > 8000 else out, flush=True) if code != 0: print(f"WARN deploy cmd exit {code}", flush=True) code2, after = run( c, "docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort; " "systemctl is-active douyinweb-api douyinweb-web; " f"curl -sk -m 15 -o /dev/null -w 'pub_keys:%{{http_code}}\\n' {public}/youtube/keys; " f"curl -sk -m 15 -o /dev/null -w 'pub_yt:%{{http_code}}\\n' {public}/youtube", ) print("AFTER:\n" + after, flush=True) # assert same neko names still running (set compare of Up lines) before_up = {ln.split()[0] for ln in before.splitlines() if " Up " in ln and "neko" in ln} after_up = {ln.split()[0] for ln in after.splitlines() if " Up " in ln and "neko" in ln} lost = before_up - after_up if lost: print(f"CRITICAL neko lost on {label}: {lost}", flush=True) raise SystemExit(2) print(f"neko_ok {label} still_up={sorted(after_up)}", flush=True) c.close() def sync_registry_dy_to_dylive() -> None: """Copy key registry secrets dy → dylive (table only).""" print("\n======== sync registry dy → dylive ========", flush=True) dy = connect("108.174.50.68") code, out = run( dy, r""" cd /opt/douyinWEB/backend ./.venv/bin/python - <<'PY' import json from app import yt_stream_key_db print('EXPORT_JSON_START') print(json.dumps(yt_stream_key_db.export_all(), ensure_ascii=False)) print('EXPORT_JSON_END') PY """, ) dy.close() start = out.find("EXPORT_JSON_START") end = out.find("EXPORT_JSON_END") if start < 0 or end < 0: print("no export", out[-2000:]) return payload = json.loads(out[start + len("EXPORT_JSON_START") : end].strip()) items = payload.get("items") or [] print(f"export items={len(items)}", flush=True) dl = connect("107.173.30.245") sftp = dl.open_sftp() with sftp.file("/tmp/yt_stream_keys_import.json", "w") as f: f.write(json.dumps({"items": items, "replace": False}, ensure_ascii=False)) sftp.close() code2, out2 = run( dl, r""" cd /opt/douyinWEB/backend ./.venv/bin/python - <<'PY' import json from app import yt_stream_key_db data=json.load(open('/tmp/yt_stream_keys_import.json',encoding='utf-8')) print(yt_stream_key_db.import_payload(data.get('items') or [], replace=False)) print('total', yt_stream_key_db.list_entries()['total']) PY # ensure neko untouched docker ps --filter name=douyinweb-neko --format '{{.Names}} {{.Status}}' | sort """, ) print(out2, flush=True) dl.close() def main() -> None: for rel in FILES: assert (ROOT / rel).is_file(), rel # dy first (where user added keys), then dylive for label, host, public in HOSTS: deploy_one(label, host, public) sync_registry_dy_to_dylive() print("\nALL_DONE", flush=True) if __name__ == "__main__": main()