douyinWEB/scripts/_deploy_api_hang_harden.py
eric fbdc3fc0db Harden dual-VPS API against live+encode CPU storms; document and ship YPP revenue.
Keep /api/health instant, isolate ffmpeg cgroups, defer clip encodes while live push runs, and align dy.live systemd with dylive. README covers the hang root cause and /yt-revenue.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-16 20:50:45 -05:00

222 lines
8.2 KiB
Python

# -*- coding: utf-8 -*-
"""Deploy API hang harden: ffmpeg cgroup split + health watchdog + concurrency cap.
Physical dy (108.174.50.68) via VPS; also refresh dylive code for parity.
"""
from __future__ import annotations
import sys
import time
from pathlib import Path
import httpx
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
VPS = "107.173.30.245"
DY = "108.174.50.68"
PASS = "Xiao4669805"
FILES = [
("backend/app/procutil.py", "_hang_procutil.py"),
("backend/app/youtube_relay.py", "_hang_youtube_relay.py"),
("backend/app/yt_long_clip.py", "_hang_yt_long_clip.py"),
("backend/app/shorts_clip.py", "_hang_shorts_clip.py"),
("backend/app/clip_cascade.py", "_hang_clip_cascade.py"),
("scripts/linux/api_health_watch.sh", "_hang_api_health_watch.sh"),
]
SLICE_UNIT = """[Unit]
Description=douyinWEB ffmpeg memory slice (outside API cgroup)
Before=douyinweb-api.service
[Slice]
MemoryAccounting=yes
MemoryHigh=1800M
MemoryMax=2800M
MemorySwapMax=512M
CPUAccounting=yes
[Install]
WantedBy=multi-user.target
"""
API_WATCH_UNIT = """[Unit]
Description=douyinWEB API health hang watchdog
After=network-online.target douyinweb-api.service
Wants=network-online.target
[Service]
Type=simple
Environment=DY_API_WATCH_INTERVAL=20
Environment=DY_API_WATCH_FAILS=3
Environment=DY_API_WATCH_COOLDOWN=120
Environment=DY_API_WATCH_START_GRACE=120
Environment=DY_API_WATCH_RECVQ_LIMIT=120
ExecStart=/bin/bash /opt/douyinWEB/scripts/linux/api_health_watch.sh
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
"""
OOM_CONF = """[Service]
MemoryAccounting=yes
# Python-only budget after ffmpeg moved to douyinweb-ffmpeg.slice.
MemoryHigh=2200M
MemoryMax=3000M
MemorySwapMax=512M
OOMPolicy=kill
OOMScoreAdjust=400
"""
PHYS_SH = r'''
set -e
TS=$(date +%s)
install -d -m 755 /opt/douyinWEB/scripts/linux
install -d -m 755 /etc/systemd/system/douyinweb-api.service.d
for f in youtube_relay.py yt_long_clip.py shorts_clip.py clip_cascade.py; do
cp -a /opt/douyinWEB/backend/app/$f /opt/douyinWEB/backend/app/${f}.bak-hang-${TS} 2>/dev/null || true
done
cp -a /tmp/_hang_procutil.py /opt/douyinWEB/backend/app/procutil.py
cp -a /tmp/_hang_youtube_relay.py /opt/douyinWEB/backend/app/youtube_relay.py
cp -a /tmp/_hang_yt_long_clip.py /opt/douyinWEB/backend/app/yt_long_clip.py
cp -a /tmp/_hang_shorts_clip.py /opt/douyinWEB/backend/app/shorts_clip.py
cp -a /tmp/_hang_clip_cascade.py /opt/douyinWEB/backend/app/clip_cascade.py
install -m 755 /tmp/_hang_api_health_watch.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh
install -m 644 /tmp/_hang_ffmpeg.slice /etc/systemd/system/douyinweb-ffmpeg.slice
install -m 644 /tmp/_hang_api_watch.service /etc/systemd/system/douyinweb-api-watch.service
install -m 644 /tmp/_hang_oom.conf /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf
cd /opt/douyinWEB/backend
.venv/bin/python -m py_compile app/procutil.py app/youtube_relay.py app/yt_long_clip.py app/shorts_clip.py app/clip_cascade.py
echo COMPILE_OK
# Cap concurrent encode on this host (settings DB)
.venv/bin/python - <<'PY'
import sys
sys.path.insert(0, "/opt/douyinWEB/backend")
from app import db
patch = {
"yt_long_max_concurrent": 1,
"shorts_max_concurrent": 1,
"shorts_upload_max_concurrent": 1,
"tiktok_max_concurrent": 1,
"x_clips_max_concurrent": 1,
}
out = db.update_settings_map(patch, audit_actor="hang_harden")
print("settings_ok", {k: (out or {}).get(k) for k in patch})
PY
systemctl daemon-reload
systemctl enable douyinweb-ffmpeg.slice douyinweb-api-watch.service
systemctl start douyinweb-ffmpeg.slice
systemctl restart douyinweb-api
sleep 4
for i in $(seq 1 20); do
code=$(curl -sS -m 4 -o /dev/null -w "%{http_code}" http://127.0.0.1:8014/api/health || echo x)
echo health:$code
[ "$code" = "200" ] && break
sleep 2
done
systemctl restart douyinweb-api-watch
sleep 2
systemctl is-active douyinweb-api douyinweb-api-watch douyinweb-ffmpeg.slice
systemctl show douyinweb-api -p MemoryHigh,MemoryMax,MemoryCurrent --value | tr '\n' ' '; echo
ls -la /sys/fs/cgroup/system.slice/douyinweb-ffmpeg.slice/cgroup.procs 2>/dev/null || echo NO_CGROUP_PROCS
# if a relay ffmpeg is running, show its cgroup
ff=$(pgrep -n -f 'ffmpeg.*rtmps://' || true)
if [ -n "$ff" ]; then
echo ffmpeg_pid=$ff
cat /proc/$ff/cgroup 2>/dev/null | head -5
fi
echo PHYS_DONE
'''
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(VPS, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel, tmp in FILES:
data = (ROOT / rel).read_bytes().replace(b"\r\n", b"\n")
with sftp.file(f"/tmp/{tmp}", "wb") as f:
f.write(data)
print("staged", tmp, len(data), flush=True)
with sftp.file("/tmp/_hang_ffmpeg.slice", "w") as f:
f.write(SLICE_UNIT)
with sftp.file("/tmp/_hang_api_watch.service", "w") as f:
f.write(API_WATCH_UNIT)
with sftp.file("/tmp/_hang_oom.conf", "w") as f:
f.write(OOM_CONF)
with sftp.file("/tmp/_hang_phys.sh", "w") as f:
f.write(PHYS_SH)
sftp.close()
# Also refresh dylive code (no MemoryHigh change required there as much)
print("=== dylive code parity ===", flush=True)
_, o, e = c.exec_command(
"cp -a /tmp/_hang_procutil.py /opt/douyinWEB/backend/app/procutil.py; "
"cp -a /tmp/_hang_youtube_relay.py /opt/douyinWEB/backend/app/youtube_relay.py; "
"cp -a /tmp/_hang_yt_long_clip.py /opt/douyinWEB/backend/app/yt_long_clip.py; "
"cp -a /tmp/_hang_shorts_clip.py /opt/douyinWEB/backend/app/shorts_clip.py; "
"cp -a /tmp/_hang_clip_cascade.py /opt/douyinWEB/backend/app/clip_cascade.py; "
"install -D -m 755 /tmp/_hang_api_health_watch.sh /opt/douyinWEB/scripts/linux/api_health_watch.sh; "
"install -m 644 /tmp/_hang_ffmpeg.slice /etc/systemd/system/douyinweb-ffmpeg.slice; "
"install -m 644 /tmp/_hang_api_watch.service /etc/systemd/system/douyinweb-api-watch.service; "
"systemctl daemon-reload; systemctl enable --now douyinweb-ffmpeg.slice douyinweb-api-watch.service; "
"systemctl restart douyinweb-api; "
"for i in $(seq 1 15); do c=$(curl -sS -m 3 -o /dev/null -w %{http_code} http://127.0.0.1:8014/api/health || echo x); "
"echo dylive_health:$c; [ \"$c\" = 200 ] && break; sleep 2; done; "
"systemctl is-active douyinweb-api douyinweb-api-watch",
timeout=120,
)
print((o.read() + e.read()).decode("utf-8", "replace")[-4000:], flush=True)
print("=== physical deploy ===", flush=True)
chan = c.get_transport().open_session()
chan.exec_command(
f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no "
f"/tmp/_hang_procutil.py /tmp/_hang_youtube_relay.py /tmp/_hang_yt_long_clip.py "
f"/tmp/_hang_shorts_clip.py /tmp/_hang_clip_cascade.py /tmp/_hang_api_health_watch.sh "
f"/tmp/_hang_ffmpeg.slice /tmp/_hang_api_watch.service /tmp/_hang_oom.conf /tmp/_hang_phys.sh "
f"root@{DY}:/tmp/ && "
f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} "
f"'bash /tmp/_hang_phys.sh' > /tmp/_hang_phys.out 2>&1; echo EXIT:$? >> /tmp/_hang_phys.out"
)
out = ""
for i in range(90):
time.sleep(2)
_, o2, _ = c.exec_command("tail -c 25000 /tmp/_hang_phys.out 2>/dev/null", timeout=20)
out = o2.read().decode("utf-8", "replace")
if "EXIT:" in out:
print(out[-14000:], flush=True)
break
if i % 5 == 0:
print("poll", i, out[-180:].replace("\n", " | "), flush=True)
else:
print("TIMEOUT", out[-5000:], flush=True)
c.close()
return 1
print("=== public ===", flush=True)
for url in ("https://dy.nomadro.live/api/health", "https://dylive.nomadro.com/api/health"):
try:
with httpx.Client(timeout=20, verify=False) as h:
r = h.get(url)
print(url, r.status_code, r.text[:120], flush=True)
except Exception as ex:
print(url, "ERR", ex, flush=True)
c.close()
return 0 if "PHYS_DONE" in out and "EXIT:0" in out else 1
if __name__ == "__main__":
raise SystemExit(main())