#!/usr/bin/env python3 """Deploy relay-slot fix to 3 hosts without restarting lanes that are actively pushing.""" from __future__ import annotations import io import json import paramiko import re import time from pathlib import Path ROOT = Path(__file__).resolve().parent.parent 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"), ] 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 active_rtmps_pids(ssh) -> list[str]: out = run(ssh, "pgrep -af 'ffmpeg.*rtmps' 2>/dev/null | grep -v pgrep || true") if not out: return [] return [line for line in out.splitlines() if "ffmpeg" in line.lower()] def youtube_procs(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( { "pm2": name, "status": p.get("process_status"), "pushing": p.get("is_pushing"), "ffmpeg_active": p.get("ffmpeg_active"), } ) return rows def lane_push_state(ssh, proc: str, rtmps_lines: list[str]) -> str: """Return: pushing | online | stopped""" if any(proc in line or "youtube.py" in line for line in rtmps_lines): # weak match: any rtmps while this host has one youtube lane pushing pass out = run(ssh, f"ps aux | grep -E '[p]ython.*youtube\\.py' | head -5") # If only one youtube.py and rtmps active, treat as pushing for all pro lanes on small hosts if rtmps_lines and "online" in str(youtube_procs(ssh)): for row in youtube_procs(ssh): if row["pm2"] == proc and (row.get("pushing") or row.get("ffmpeg_active")): return "pushing" try: dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) for p in dash.get("live", {}).get("processes", []): if p.get("pm2") == proc: if p.get("is_pushing") or p.get("ffmpeg_active"): return "pushing" st = str(p.get("process_status") or "").lower() if st in {"online", "running", "launching"}: return "online" return "stopped" except json.JSONDecodeError: pass return "unknown" for host, user, pw, base in HOSTS: 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}") continue rtmps_before = active_rtmps_pids(ssh) print(f"rtmps before ({len(rtmps_before)}):") for line in rtmps_before[:3]: print(" ", line[:160]) sftp = ssh.open_sftp() install_cmds = [] for rel in FILES: local = ROOT / rel tmp = f"/tmp/_relay_slot3_{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) sftp.close() print(run(ssh, f"echo '{pw}' | sudo -S -p '' bash -lc \"{' && '.join(install_cmds)}\"")) print("markers:") print(" relay_slot:", run(ssh, f"test -f {base}/src/youtube_relay_slot.py && echo present")) 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(" hub fix:", run(ssh, f"grep -c 'url_file = Path' {base}/src/hub_routes.py")) print("\nrestart live-console only (does not touch youtube.py workers)...") print(run(ssh, f"echo '{pw}' | sudo -S -p '' systemctl restart live-console.service", timeout=120)) time.sleep(3) procs = [r["pm2"] for r in youtube_procs(ssh)] print("\nlane restart policy:") for proc in procs: if proc == "youtube": print(f" skip {proc}: legacy single process") continue state = lane_push_state(ssh, proc, rtmps_before) if state == "pushing" or rtmps_before: print(f" skip {proc}: keep running (host has active rtmps or lane pushing)") else: print(f" skip {proc}: no restart (preserve monitoring loop; code loads on next restart)") rtmps_after = active_rtmps_pids(ssh) print(f"\nrtmps after ({len(rtmps_after)}):") for line in rtmps_after[:3]: print(" ", line[:160]) if rtmps_before and not rtmps_after: print(" WARNING: rtmps disappeared — investigate!") elif len(rtmps_before) <= len(rtmps_after): print(" OK: no push interruption detected") dash = json.loads(run(ssh, "curl -sS -m 15 http://127.0.0.1:8001/hub/dashboard")) for p in dash.get("live", {}).get("processes", []): if "youtube" in str(p.get("pm2", "")).lower(): note = str(p.get("business_note") or "") if "is_file" in note: print(f" WARN {p.get('pm2')}: {note[:80]}") else: print( f" {p.get('pm2')}: biz={p.get('business_status')} " f"pushing={p.get('is_pushing')}" ) ssh.close() print("\nDONE — youtube.py / ffplay changes on disk; active workers keep old code until next lane restart.")