#!/usr/bin/env python3 """Deploy relay-slot + UI fixes to 3 hosts; restart live-console and non-pushing youtube lanes.""" from __future__ import annotations import io import json import paramiko import tarfile import time from pathlib import Path ROOT = Path(__file__).resolve().parent.parent BACKEND_FILES = [ "src/youtube_relay_slot.py", "youtube.py", "douyin_youtube_ffplay.py", "src/hub_routes.py", ] HOSTS = [ ("192.168.2.237", "eric", "4669805", "/home/eric/d2ypp2-src"), ("10.88.0.3", "eric", "Xiao4669805", "/opt/live/d2ypp"), ("10.88.0.5", "eric", "4669805", "/opt/live/d2ypp"), ] CONSOLE_OUT = ROOT / "web-console" / "out" def put_lf(sftp, local: Path, remote: str) -> None: data = local.read_bytes().replace(b"\r\n", b"\n").replace(b"\r", b"\n") sftp.putfo(io.BytesIO(data), remote) def run(ssh, cmd, timeout=180): _, o, e = ssh.exec_command(cmd, timeout=timeout) return (o.read() + e.read()).decode("utf-8", "replace").strip() def youtube_lane_rows(ssh) -> list[dict]: try: dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) except json.JSONDecodeError: return [] rows = [] for p in dash.get("live", {}).get("processes", []): name = str(p.get("pm2") or "").strip() if not name.startswith("youtube"): continue rows.append(p) return rows def lane_is_pushing(row: dict) -> bool: if row.get("is_pushing") or row.get("ffmpeg_active"): return True business = str(row.get("business_status") or "").strip().lower() return business in {"streaming", "relay_starting", "relay_slow", "source_stalled"} def deploy_host(host: str, user: str, pw: str, base: str) -> None: print(f"\n{'='*72}\n{host} {base}\n{'='*72}") ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(host, username=user, password=pw, timeout=25) except Exception as exc: print(f"SSH FAIL: {exc}") return rtmps_before = run(ssh, "pgrep -af 'ffmpeg.*rtmps' 2>/dev/null | grep -v pgrep || true") print(f"rtmps before: {len(rtmps_before.splitlines()) if rtmps_before else 0} proc(s)") sftp = ssh.open_sftp() install_cmds = [] for rel in BACKEND_FILES: local = ROOT / rel tmp = f"/tmp/_relay_fix_{rel.replace('/', '_')}" dest = f"{base}/{rel.replace(chr(92), '/')}" put_lf(sftp, local, tmp) install_cmds.append(f"install -m 0644 {tmp} {dest}") print("staged", rel) if CONSOLE_OUT.is_dir(): buf = io.BytesIO() with tarfile.open(fileobj=buf, mode="w:gz") as tar: tar.add(CONSOLE_OUT, arcname="out") buf.seek(0) remote_tar = "/tmp/_relay_fix_console_out.tgz" sftp.putfo(buf, remote_tar) install_cmds.append( f"rm -rf {base}/web-console/out && mkdir -p {base}/web-console && " f"tar -xzf {remote_tar} -C {base}/web-console && rm -f {remote_tar}" ) print("staged web-console/out") sftp.close() print(run(ssh, f"echo '{pw}' | sudo -S -p '' bash -lc \"{' && '.join(install_cmds)}\"")) print("markers:") print(" prune_orphan:", run(ssh, f"grep -c prune_orphan_relay_recording {base}/youtube.py")) print(" old guard:", run(ssh, f"grep -c 'len(recording) > 0' {base}/youtube.py || echo 0")) print(" active_monitor:", run(ssh, f"grep -c active_monitor_urls {base}/youtube.py")) print(" hub fix:", run(ssh, f"grep -c 'url_file = Path' {base}/src/hub_routes.py")) print("\nrestart live-console ...") print(run(ssh, f"echo '{pw}' | sudo -S -p '' systemctl restart live-console.service", timeout=120)) time.sleep(4) lanes = youtube_lane_rows(ssh) print(f"\nrestart youtube lanes ({len(lanes)} found):") for row in lanes: proc = str(row.get("pm2") or "") if proc == "youtube": print(f" skip {proc}: legacy") continue if lane_is_pushing(row): print(f" skip {proc}: pushing (biz={row.get('business_status')})") continue out = run( ssh, f"curl -sS -m 120 -X POST 'http://127.0.0.1:8001/restart' " f"-H 'Content-Type: application/json' " f"-d '{{\"process\":\"{proc}\"}}'", timeout=150, ) print(f" restarted {proc}: {out[:180]}") time.sleep(8) rtmps_after = run(ssh, "pgrep -af 'ffmpeg.*rtmps' 2>/dev/null | grep -v pgrep || true") print(f"\nrtmps after: {len(rtmps_after.splitlines()) if rtmps_after else 0} proc(s)") for row in youtube_lane_rows(ssh): proc = str(row.get("pm2") or "") if "youtube" not in proc.lower(): continue note = str(row.get("business_note") or "") if "is_file" in note: print(f" WARN {proc}: {note[:80]}") else: print( f" {proc}: biz={row.get('business_status')} " f"pushing={row.get('is_pushing')} online={row.get('process_status')}" ) ssh.close() if __name__ == "__main__": for h, u, p, b in HOSTS: deploy_host(h, u, p, b) print("\nDONE")