sh2/d2ypp2/tools/deploy_test_host04.py
2026-06-14 10:41:48 -05:00

171 lines
6.9 KiB
Python

#!/usr/bin/env python3
"""Deploy current repo source to 10.88.0.4 for integration test, then verify clean regression."""
from __future__ import annotations
import io
import json
import posixpath
import time
from pathlib import Path
import paramiko
HOST, USER, PASS = "10.88.0.4", "eric", "4669805"
BASE = "/home/eric/d2ypp2-src"
REPO = Path(__file__).resolve().parent.parent
OUT = REPO / "web-console" / "out"
# Core files changed in this fix cycle — sync from local repo as source of truth.
SYNC_FILES = [
"douyin_youtube_ffplay.py",
"youtube.py",
"web.py",
"scripts/hardware_probe.py",
"src/youtube_runtime.py",
"src/youtube_quality_guard.py",
"src/process_runtime_status.py",
"src/douyin_source_display.py",
"src/web_process_backend.py",
"src/spider.py",
"web-console/lib/ffmpegMetrics.ts",
"web-console/lib/youtubeConfigUtils.ts",
"web-console/components/live-product/LiveYoutubeUnmannedView.tsx",
"web-console/components/live-product/LiveProcessLiveLogCard.tsx",
]
def run(ssh: paramiko.SSHClient, cmd: str, timeout: int = 180) -> str:
_, stdout, stderr = ssh.exec_command(f"export LC_ALL=C.UTF-8; {cmd}", timeout=timeout, get_pty=True)
return (stdout.read() + stderr.read()).decode("utf-8", "replace").strip()
def mkdir_p(sftp: paramiko.SFTPClient, remote_dir: str) -> None:
remote_dir = remote_dir.replace("\\", "/").rstrip("/")
parts = [p for p in remote_dir.split("/") if p]
cur = ""
for part in parts:
cur = f"{cur}/{part}" if cur else f"/{part}"
try:
sftp.stat(cur)
except OSError:
sftp.mkdir(cur)
def put_file(sftp: paramiko.SFTPClient, local: Path, remote: str) -> None:
mkdir_p(sftp, posixpath.dirname(remote))
if local.suffix.lower() in {".py", ".ts", ".tsx", ".sh"}:
sftp.putfo(io.BytesIO(local.read_bytes().replace(b"\r\n", b"\n")), remote)
else:
sftp.put(str(local), remote)
def put_tree(sftp: paramiko.SFTPClient, local_dir: Path, remote_dir: str) -> int:
count = 0
for path in sorted(local_dir.rglob("*")):
if not path.is_file():
continue
rel = path.relative_to(local_dir).as_posix()
remote = posixpath.join(remote_dir, rel)
mkdir_p(sftp, posixpath.dirname(remote))
sftp.put(str(path), remote)
count += 1
return count
def lane_names(ssh: paramiko.SSHClient) -> list[str]:
raw = run(ssh, f"ls {BASE}/config/youtube.youtube2__*.ini 2>/dev/null")
names: list[str] = []
for line in raw.splitlines():
name = line.rsplit("/", 1)[-1]
if name.startswith("youtube.") and name.endswith(".ini"):
names.append(name[len("youtube.") : -len(".ini")])
return sorted(names)
def main() -> int:
if not (OUT / "index.html").is_file():
raise SystemExit("missing web-console/out — run: cd web-console && npm run build")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HOST, username=USER, password=PASS, timeout=25)
sftp = ssh.open_sftp()
print("=== [1/5] upload repo source files ===")
for rel in SYNC_FILES:
local = REPO / rel
if not local.is_file():
print(f"[skip] missing {rel}")
continue
remote = f"{BASE}/{rel.replace(chr(92), '/')}"
put_file(sftp, local, remote)
print(f"[ok] {rel}")
print("\n=== [2/5] upload web-console/out ===")
uploaded = put_tree(sftp, OUT, f"{BASE}/web-console/out")
print(f"[ok] uploaded {uploaded} static files")
cleanup_py = (REPO / "tools" / "_remote_cleanup_relay.py").read_text(encoding="utf-8")
with sftp.open("/tmp/_remote_cleanup_relay.py", "w") as fh:
fh.write(cleanup_py)
sftp.close()
print("\n=== [3/5] cleanup relay/copy artifacts on remote ===")
print(run(ssh, f"python3 /tmp/_remote_cleanup_relay.py {BASE}"))
print("\n=== [4/5] restart live-console + youtube lanes ===")
print(run(ssh, f"echo '{PASS}' | sudo -S -p '' systemctl restart live-console.service", timeout=90))
print(run(ssh, "sleep 5; curl -sf -m 8 http://127.0.0.1:8001/health && echo health_ok"))
for proc in lane_names(ssh):
out = run(
ssh,
"curl -sS -m 60 -X POST 'http://127.0.0.1:8001/restart' "
"-H 'Content-Type: application/json' "
f"-d '{json.dumps({'process': proc})}'",
)
print(f"restart {proc}: {out[:220]}")
time.sleep(12)
print("\n=== [5/5] regression verify (remote == repo source) ===")
checks = [
("no_stream_copy_fn", f"grep -c _resolve_stream_copy_plan {BASE}/douyin_youtube_ffplay.py || echo 0"),
("has_key_reject_guard", f"grep -c _looks_like_youtube_output_rejected {BASE}/douyin_youtube_ffplay.py"),
("force_youtube_push", f"grep -A2 'force_youtube_push' {BASE}/src/youtube_runtime.py | head -4"),
("no_relay_strategy", f"grep relay_strategy {BASE}/config/hardware-profile.json 2>/dev/null || echo clean"),
("no_video_mode_ini", f"grep -H video_mode {BASE}/config/youtube.youtube2__*.ini 2>/dev/null | head -3 || echo clean"),
("ffmpeg_cmd", "pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -2"),
("push_profile_log", f"grep -hE 'YouTube Live profile|stream copy|libx264' {BASE}/.pm2/logs/youtube2__*-out.log 2>/dev/null | tail -6"),
("quality_guard_profile", "curl -sS -m 12 http://127.0.0.1:8001/hub/youtube/quality_guard | python3 -c \"import sys,json;d=json.load(sys.stdin);print(d.get('ffmpeg_profile',{}).get('target','?'))\""),
("process_monitor", "curl -sS -m 12 'http://127.0.0.1:8001/process_monitor?family=youtube'"),
]
monitor_rows: list[dict] = []
for label, cmd in checks:
out = run(ssh, cmd)
print(f"\n--- {label} ---\n{out[:1200]}")
if label == "process_monitor":
try:
monitor_rows = json.loads(out).get("entries") or []
except json.JSONDecodeError:
pass
print("\n=== summary ===")
copy_fn = run(ssh, f"grep -c _resolve_stream_copy_plan {BASE}/douyin_youtube_ffplay.py || true").strip()
relay = run(ssh, f"grep -c relay_strategy {BASE}/config/hardware-profile.json 2>/dev/null || echo 0").strip()
ffmpeg = run(ssh, "pgrep -af 'ffmpeg.*rtmps' | grep -v pgrep | head -1")
ok = copy_fn in {"0", ""} and relay in {"0", ""} and "libx264" in ffmpeg
print(f"stream_copy_removed={copy_fn in {'0', ''}}")
print(f"relay_strategy_removed={relay in {'0', ''}}")
print(f"libx264_push={'libx264' in ffmpeg}")
for row in monitor_rows[:8]:
print(
f" {row.get('pm2')}: {row.get('business_status')} pushing={row.get('is_pushing')} "
f"speed={row.get('ffmpeg_speed')}"
)
print(f"\n回归源码: {'PASS' if ok else 'CHECK LOGS'} — remote {BASE} synced from local repo")
ssh.close()
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())