douyinWEB/scripts/_apply_neko_oom_protect.py
2026-09-13 22:10:49 -05:00

149 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Apply host-level OOM protection to neko-7 processes + hard-restart Chrome with new flags."""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
def ssh():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(
"107.173.30.245",
22,
"root",
"Xiao4669805",
timeout=45,
allow_agent=False,
look_for_keys=False,
banner_timeout=120,
)
return c
def run(c, cmd, t=180):
print(f"\n$ {cmd[:220]}", flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
code = o.channel.recv_exit_status()
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out[-16000:] if len(out) > 16000 else out, flush=True)
return code, out
c = ssh()
run(
c,
r"""
set -euo pipefail
# Persist helper: protect all PIDs in neko container cgroup (works without docker recreate).
install -m 0755 /dev/stdin /usr/local/sbin/douyinweb-protect-neko-oom <<'EOF'
#!/bin/bash
set -euo pipefail
ADJ="${1:--800}"
for name in $(docker ps --format '{{.Names}}' | grep -E '^douyinweb-neko-[0-9]+$' || true); do
cid=$(docker inspect -f '{{.Id}}' "$name")
# cgroup v2 path used by docker on this host
for base in \
"/sys/fs/cgroup/system.slice/docker-${cid}.scope" \
"/sys/fs/cgroup/docker/${cid}" \
"/sys/fs/cgroup/system.slice/docker-${cid}.scope"
do
if [ -f "$base/cgroup.procs" ]; then
while read -r p; do
[ -n "$p" ] || continue
echo "$ADJ" > "/proc/$p/oom_score_adj" 2>/dev/null || true
done < "$base/cgroup.procs"
echo "protected $name via $base adj=$ADJ"
fi
done
# Also main pid
main=$(docker inspect -f '{{.State.Pid}}' "$name")
if [ -n "$main" ] && [ "$main" != "0" ]; then
echo "$ADJ" > "/proc/$main/oom_score_adj" 2>/dev/null || true
fi
done
EOF
/usr/local/sbin/douyinweb-protect-neko-oom -800
# systemd timer every minute — re-apply after chrome spawn
cat > /etc/systemd/system/douyinweb-neko-oom-protect.service <<'EOF'
[Unit]
Description=Protect douyinweb Neko/Chrome from host OOM killer
After=docker.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/douyinweb-protect-neko-oom -800
EOF
cat > /etc/systemd/system/douyinweb-neko-oom-protect.timer <<'EOF'
[Unit]
Description=Re-apply Neko OOM protection every minute
[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
AccuracySec=15s
Unit=douyinweb-neko-oom-protect.service
[Install]
WantedBy=timers.target
EOF
systemctl daemon-reload
systemctl enable --now douyinweb-neko-oom-protect.timer
systemctl start douyinweb-neko-oom-protect.service
echo ===HARD_RESTART_CHROME===
# Kill entire chrome tree; browser-launch.sh loop relaunches with new memory flags.
docker exec douyinweb-neko-7 sh -c 'pkill -9 -f /opt/google/chrome/chrome 2>/dev/null; pkill -9 chrome 2>/dev/null; true' || true
sleep 8
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json, time, subprocess
from app import youtube_neko as yn
nid=7
for i in range(30):
tabs=yn._cdp_fetch_tabs(nid)
pages=[t for t in tabs if (t.get("type") or "page")=="page"]
print("wait", i, len(pages))
if pages:
break
time.sleep(2)
else:
raise SystemExit("chrome_did_not_return")
# re-protect after spawn
subprocess.check_call(["/usr/local/sbin/douyinweb-protect-neko-oom", "-800"])
studio="https://studio.youtube.com/video/xmwiN6n4d9Q/livestreaming"
print(yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio))
time.sleep(8)
sig=yn._cdp_studio_page_signals(nid, force=True, max_age_sec=0.0)
print("sig", json.dumps({k:sig.get(k) for k in ("ok","control_ready","live_status","on_air","url")}, ensure_ascii=False))
print("text_head", str(sig.get("text") or "")[:200].replace("\n"," | "))
# verify cmdline has renderer-process-limit
code,out=yn._run(["docker","exec",yn._container_name(nid),"sh","-c",
"tr '\\0' '\\n' </proc/1/cmdline 2>/dev/null; for p in /proc/[0-9]*; do c=$(tr '\\0' ' ' <$p/cmdline 2>/dev/null); case \"$c\" in *chrome*--type=zygote*|*chrome*--user-data-dir*) echo OOM=$(cat $p/oom_score_adj 2>/dev/null) $c | head -c 220; echo;; esac; done | head -20"], timeout=20)
print(out[:2500])
# host view of container main oom
import os
main=int(subprocess.check_output(["docker","inspect","-f","{{.State.Pid}}","douyinweb-neko-7"], text=True).strip() or 0)
print("main_pid", main, "oom", open(f"/proc/{main}/oom_score_adj").read().strip() if main else None)
PY
free -h
swapon --show
systemctl is-active sing-box frpp 'wg-quick@wg-dy' douyinweb-neko-oom-protect.timer
""",
)
c.close()
print("DONE", time.strftime("%H:%M:%S"))