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

137 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""Harden dylive against Chrome OOM on 3.8G host (no login wipe, keep sing-box/frpp/wg)."""
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]
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=600):
print(f"\n$ {cmd[:240]}", 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[-20000:] if len(out) > 20000 else out, flush=True)
return code, out
c = ssh()
sftp = c.open_sftp()
sftp.put(str(ROOT / "backend/neko/browser-launch.sh"), "/tmp/browser-launch.sh")
sftp.put(str(ROOT / "backend/app/youtube_neko.py"), "/tmp/youtube_neko.py")
sftp.close()
code, _ = run(
c,
r"""
set -euo pipefail
echo ===1_SWAP===
# Keep existing /swapfile; add /swapfile2 (+3G) so host has 4G swap headroom.
if [ ! -f /swapfile2 ]; then
fallocate -l 3G /swapfile2 || dd if=/dev/zero of=/swapfile2 bs=1M count=3072 status=progress
chmod 600 /swapfile2
mkswap /swapfile2
fi
swapon /swapfile2 2>/dev/null || true
grep -q '/swapfile2' /etc/fstab || echo '/swapfile2 none swap sw 0 0' >> /etc/fstab
# Use swap before hard OOM (was thrashing at 100% of 1G).
sysctl -w vm.swappiness=60
grep -q '^vm.swappiness' /etc/sysctl.d/99-douyinweb-oom.conf 2>/dev/null \
|| printf 'vm.swappiness=60\nvm.vfs_cache_pressure=50\n' > /etc/sysctl.d/99-douyinweb-oom.conf
sysctl -p /etc/sysctl.d/99-douyinweb-oom.conf || true
swapon --show
free -h
echo ===2_API_OOM_PREF===
# Prefer reclaim/kill API before Neko/Chrome. Soft memory high-water.
mkdir -p /etc/systemd/system/douyinweb-api.service.d
cat > /etc/systemd/system/douyinweb-api.service.d/oom-protect-chrome.conf <<'EOF'
[Service]
# Positive = more likely chosen by host OOM killer than Neko/Chrome (-800).
OOMScoreAdjust=300
# Soft pressure: reclaim before hard OOM; hard cap leaves headroom for Chrome.
MemoryHigh=900M
MemoryMax=1400M
EOF
systemctl daemon-reload
systemctl restart douyinweb-api.service
sleep 3
systemctl is-active douyinweb-api.service
systemctl show douyinweb-api.service -p OOMScoreAdjust -p MemoryHigh -p MemoryMax -p MemoryCurrent
echo ===3_BROWSER_LAUNCH===
install -m 0755 /tmp/browser-launch.sh /opt/douyinWEB/backend/neko/browser-launch.sh
install -m 0644 /tmp/youtube_neko.py /opt/douyinWEB/backend/app/youtube_neko.py
# Bind-mount is live; soft-restart Chrome so new flags + oom_score apply (profile untouched).
if docker inspect douyinweb-neko-7 --format '{{.State.Running}}' 2>/dev/null | grep -q true; then
docker update --oom-score-adj=-800 douyinweb-neko-7 || true
docker exec douyinweb-neko-7 sh -c 'pkill -TERM -f /opt/google/chrome/chrome 2>/dev/null; true'
sleep 6
fi
echo ===4_VERIFY===
cd /opt/douyinWEB/backend
./.venv/bin/python - <<'PY'
import json, time
from app import youtube_neko as yn
nid=7
print("oom_inspect", yn._run(["docker","inspect",yn._container_name(nid),"--format","{{.HostConfig.OomScoreAdj}} {{.HostConfig.Memory}}"], timeout=15)[1].strip())
# wait CDP
for i in range(25):
tabs=yn._cdp_fetch_tabs(nid)
pages=[t for t in tabs if (t.get("type") or "page")=="page"]
print("wait", i, "pages", len(pages))
if pages:
break
time.sleep(2)
studio="https://studio.youtube.com/"
for t in yn._cdp_fetch_tabs(nid):
u=str(t.get("url") or "")
if "livestreaming" in u.lower():
studio=u
break
print("ensure", yn._cdp_ensure_live_studio_in_container(yn._container_name(nid), studio_url=studio))
time.sleep(6)
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","live_status","control_ready","on_air","url","text")}, ensure_ascii=False)[:500])
# chrome oom scores inside
code,out=yn._run(["docker","exec",yn._container_name(nid),"sh","-c",
"for p in /proc/[0-9]*; do cmd=$(tr '\\0' ' ' <$p/cmdline 2>/dev/null); case \"$cmd\" in *'/opt/google/chrome/chrome '*) echo ${p#/proc/} $(cat $p/oom_score_adj 2>/dev/null) $(echo $cmd|cut -c1-60);; esac; done | head -15"], timeout=20)
print("chrome_oom", out[:1500])
PY
free -h
swapon --show
docker stats --no-stream --format '{{.Name}} mem={{.MemUsage}}' douyinweb-neko-7
# Untouchable units still up
systemctl is-active sing-box.service frpp.service 'wg-quick@wg-dy.service' || true
""",
)
c.close()
print("exit", code, time.strftime("%H:%M:%S"))
raise SystemExit(code)