Permanently stabilize dy: orphan-watch timer, web cgroup kill, tighter defer.

Stop Next build usr/node orphans from pinning the 4-core VPS; Cap web CPU and defer clips earlier under load.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-09-16 22:50:07 -05:00
parent bc92cbdd2c
commit a8255d4bb2
4 changed files with 230 additions and 5 deletions

View File

@ -441,7 +441,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
#### API 防挂死 / 直播优先 CPU(双 VPS)
现网根因(尤其 **VPS-B dy.nomadro.live**):直播推流 ffmpeg 与 yt_long/shorts 转码叠在一起 → load 飙高 → uvicorn 事件循环饿死 → `/api/health` 超时 → 整站「宕机」。**dylive 同代码**不叠加重转码时即可稳住。对策:
现网根因(尤其 **VPS-B dy.nomadro.live**):直播推流 ffmpeg 与 yt_long/shorts 转码叠在一起 → load 飙高 → uvicorn 事件循环饿死 → `/api/health` 超时 → 整站「宕机」。另有一类反复复发:**前端 `npm run build` 留下孤儿 `usr`/`node` 进程**,可单独把 4 核打到 100%。**dylive 同代码**在未叠加重转码/无孤儿时即可稳住。对策:
| 层 | 机制 | 行为 |
|----|------|------|
@ -450,9 +450,11 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
| 剪辑让路 | `host_metrics.clip_encode_defer_reason()` | 有 YouTube **直播推流** 或 load/CPU 过高时,yt_long / shorts / tiktok / x_clips **不新开** 录制 ffmpeg |
| API 内存 | systemd drop-in(对齐 dylive 紧预算,按机内存微调) | 例:dylive ≈ High **700M** / Max **900M**;dy.live ≈ High **1100M** / Max **1500M**(ffmpeg 已外置) |
| ffmpeg CPU | `douyinweb-ffmpeg.slice` `CPUQuota` | dy.live 现网 **200%**(4 核机留给 API/Neko 余量) |
| Web 加固 | `douyinweb-web.service.d/harden.conf` | `KillMode=control-group` + `CPUQuota=150%`,部署后孤儿随 unit 杀掉 |
| 孤儿守护 | `scripts/linux/build_orphan_watch.sh` + timer(每分钟) | 清 Next SWC `usr` / 无参 `node` / `.r*` 临时目录 |
| 看门狗 | `scripts/linux/api_health_watch.sh` → `douyinweb-api-watch.service` | health 连续失败或 `:8014` Recv-Q 过高 → SIGKILL 重启 API |
对齐部署(代码 + systemd):`python scripts/_align_dy_to_dylive_harden.py`(经 VPS-A 跳到 VPS-B);仅 cgroup/watch 骨架也可用 `scripts/_deploy_api_hang_harden.py`。
对齐部署:`python scripts/_stabilize_dy_permanent.py`(孤儿 timer + web/api CPU);配额/代码对齐另用 `scripts/_align_dy_to_dylive_harden.py`。
#### 时段排除名单(timeslot exclude)

View File

@ -123,9 +123,9 @@ def clip_encode_defer_reason(*, respect_live_push: bool = True) -> str:
cores = max(1, int(snap.get("cpu_cores") or 1))
load1 = float(snap.get("load1") or 0.0)
cpu = float(snap.get("cpu_percent") or 0.0)
# Leave ~1 core free for API accept loop + Neko CDP.
if load1 >= max(1.5, cores * 1.15):
# Leave ~1+ core free for API accept loop + Neko CDP + live push.
if load1 >= max(1.2, cores * 0.85):
return f"load1={load1}"
if cpu >= 80.0:
if cpu >= 70.0:
return f"cpu={cpu}"
return ""

View File

@ -0,0 +1,172 @@
# -*- coding: utf-8 -*-
"""Permanent dy VPS stabilize: orphan watch + web cgroup kill + CPU caps."""
from __future__ import annotations
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
PASS = "Xiao4669805"
JUMP = "107.173.30.245"
DY = "108.174.50.68"
WATCH_SH = (ROOT / "scripts/linux/build_orphan_watch.sh").read_text(encoding="utf-8")
WATCH_SERVICE = """[Unit]
Description=douyinWEB kill Next/npm build CPU orphans
After=network-online.target
[Service]
Type=oneshot
ExecStart=/bin/bash /opt/douyinWEB/scripts/linux/build_orphan_watch.sh
Nice=10
"""
WATCH_TIMER = """[Unit]
Description=Run build orphan watch every minute
[Timer]
OnBootSec=1min
OnUnitActiveSec=1min
AccuracySec=15s
Unit=douyinweb-build-orphan-watch.service
[Install]
WantedBy=timers.target
"""
WEB_HARDEN = """[Service]
# Orphans from npm/next must die with the unit (PPID 1 still in this cgroup).
KillMode=control-group
KillSignal=SIGTERM
TimeoutStopSec=20
# Cap web so a runaway next/node cannot pin the whole 4-core box.
CPUAccounting=yes
CPUQuota=150%
CPUWeight=40
Nice=5
MemoryAccounting=yes
MemoryHigh=900M
MemoryMax=1200M
"""
# Also tighten API background when possible — keep existing MemoryHigh from align.
API_CPU = """[Service]
Nice=0
CPUWeight=120
# Leave headroom for live ffmpeg + Neko; API itself should not take all cores.
CPUQuota=200%
"""
REMOTE = r'''
set -e
install -d -m 755 /opt/douyinWEB/scripts/linux
install -d -m 755 /etc/systemd/system/douyinweb-web.service.d
install -d -m 755 /etc/systemd/system/douyinweb-api.service.d
install -m 755 /tmp/_stab_orphan.sh /opt/douyinWEB/scripts/linux/build_orphan_watch.sh
install -m 644 /tmp/_stab_orphan.service /etc/systemd/system/douyinweb-build-orphan-watch.service
install -m 644 /tmp/_stab_orphan.timer /etc/systemd/system/douyinweb-build-orphan-watch.timer
install -m 644 /tmp/_stab_web.conf /etc/systemd/system/douyinweb-web.service.d/harden.conf
install -m 644 /tmp/_stab_api_cpu.conf /etc/systemd/system/douyinweb-api.service.d/cpu.conf
# tighter clip defer under load
if [ -f /tmp/_stab_host_metrics.py ]; then
cp -a /tmp/_stab_host_metrics.py /opt/douyinWEB/backend/app/host_metrics.py
fi
# Immediate orphan sweep
bash /opt/douyinWEB/scripts/linux/build_orphan_watch.sh || true
pkill -9 -x usr 2>/dev/null || true
systemctl daemon-reload
systemctl enable --now douyinweb-build-orphan-watch.timer
systemctl restart douyinweb-web
systemctl try-restart douyinweb-api || systemctl restart douyinweb-api
sleep 4
# Ensure ffmpeg slice CPUQuota still 200%
systemctl cat douyinweb-ffmpeg.slice | grep -E 'CPUQuota|Memory' || true
systemctl is-active douyinweb-api douyinweb-web douyinweb-api-watch douyinweb-build-orphan-watch.timer
systemctl list-timers 'douyinweb-build-orphan-watch*' --no-pager | head -5
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 health:$c
[ "$c" = "200" ] && break
sleep 2
done
uptime
ps -eo pid,pcpu,etime,cmd --sort=-pcpu | head -10
echo STAB_DONE
'''
def wait_out(c: paramiko.SSHClient, path: str, token: str = "STAB_DONE", rounds: int = 60) -> str:
out = ""
for i in range(rounds):
time.sleep(2)
_, o, _ = c.exec_command(f"tail -c 20000 {path} 2>/dev/null", timeout=15)
out = o.read().decode("utf-8", "replace")
if token in out and "EXIT:" in out:
return out
if i % 5 == 0:
print("poll", i, out[-100:].replace("\n", " | "), flush=True)
return out
def stage(sftp: paramiko.SFTPClient) -> None:
with sftp.file("/tmp/_stab_orphan.sh", "w") as f:
f.write(WATCH_SH.replace("\r\n", "\n"))
with sftp.file("/tmp/_stab_orphan.service", "w") as f:
f.write(WATCH_SERVICE)
with sftp.file("/tmp/_stab_orphan.timer", "w") as f:
f.write(WATCH_TIMER)
with sftp.file("/tmp/_stab_web.conf", "w") as f:
f.write(WEB_HARDEN)
with sftp.file("/tmp/_stab_api_cpu.conf", "w") as f:
f.write(API_CPU)
hm = (ROOT / "backend/app/host_metrics.py").read_bytes().replace(b"\r\n", b"\n")
with sftp.file("/tmp/_stab_host_metrics.py", "wb") as f:
f.write(hm)
with sftp.file("/tmp/_stab_remote.sh", "w") as f:
f.write(REMOTE)
def main() -> int:
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(JUMP, 22, "root", PASS, timeout=40, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
stage(sftp)
sftp.close()
print("===== dylive =====", flush=True)
c.exec_command(
"bash /tmp/_stab_remote.sh > /tmp/_stab_dylive.out 2>&1; echo EXIT:$? >> /tmp/_stab_dylive.out",
timeout=1,
)
print(wait_out(c, "/tmp/_stab_dylive.out")[-9000:], flush=True)
print("===== dy (priority) =====", flush=True)
files = (
"/tmp/_stab_orphan.sh /tmp/_stab_orphan.service /tmp/_stab_orphan.timer "
"/tmp/_stab_web.conf /tmp/_stab_api_cpu.conf /tmp/_stab_host_metrics.py /tmp/_stab_remote.sh"
)
c.exec_command(
f"SSHPASS={PASS} sshpass -e scp -o StrictHostKeyChecking=no {files} root@{DY}:/tmp/ && "
f"SSHPASS={PASS} sshpass -e ssh -o StrictHostKeyChecking=no root@{DY} "
f"'bash /tmp/_stab_remote.sh' > /tmp/_stab_dy.out 2>&1; echo EXIT:$? >> /tmp/_stab_dy.out",
timeout=1,
)
print(wait_out(c, "/tmp/_stab_dy.out")[-9000:], flush=True)
c.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@ -0,0 +1,51 @@
#!/usr/bin/env bash
# Kill leftover Next.js / npm build orphans that pin VPS CPU after frontend deploys.
# Safe to run every minute via systemd timer.
set +e
FRONTEND_DIR="${DY_FRONTEND_DIR:-/opt/douyinWEB/frontend}"
LOG_TAG="[build-orphan-watch]"
log() { printf '%s %s\n' "$LOG_TAG" "$*"; }
# 1) SWC/native binary named "usr" (Next turbopack/swc temp)
killed=0
for p in $(pgrep -x usr 2>/dev/null || true); do
exe=$(readlink /proc/$p/exe 2>/dev/null || true)
cwd=$(readlink /proc/$p/cwd 2>/dev/null || true)
case "$exe$cwd" in
*douyinWEB*|*frontend*|*deleted*)
kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed usr pid=$p"
;;
esac
done
# 2) Bare "node" with no args (orphaned build helper) — never touch youtube-svc / next-server
for p in $(pgrep -x node 2>/dev/null || true); do
cmd=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null)
# exact "node" or "node " only
if [ "$cmd" = "node" ] || [ "$cmd" = "node " ]; then
kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed bare node pid=$p"
fi
done
# 3) Stale Next temp dirs under frontend
if [ -d "$FRONTEND_DIR" ]; then
find "$FRONTEND_DIR" -maxdepth 1 -type d -name '.r*' -mmin +5 -print0 2>/dev/null \
| xargs -0 -r rm -rf
fi
# 4) If load is insane and Recv-Q on API is climbing, poke api-watch by failing health? No —
# just log load for journal.
load1=$(awk '{print $1}' /proc/loadavg 2>/dev/null)
cores=$(nproc 2>/dev/null || echo 1)
if [ -n "$load1" ]; then
# bash float compare via awk
hot=$(awk -v l="$load1" -v c="$cores" 'BEGIN{print (l+0 >= c*1.5) ? 1 : 0}')
if [ "$hot" = "1" ]; then
log "high_load load1=$load1 cores=$cores killed=$killed"
fi
fi
[ "$killed" -gt 0 ] && log "total_killed=$killed"
exit 0