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

101 lines
2.8 KiB
Python

#!/usr/bin/env python3
"""Inspect + harden douyinweb-api memory cgroup on dylive."""
from __future__ import annotations
import sys
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
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,
)
def run(cmd: str, t: int = 120) -> str:
print("\n=====", cmd[:100].replace("\n", " "), flush=True)
_i, o, e = c.exec_command(cmd, timeout=t)
out = (o.read() + e.read()).decode("utf-8", "replace")
print(out[-12000:] if len(out) > 12000 else out, flush=True)
return out
run(
r"""
set +e
echo '=== unit files ==='
systemctl cat douyinweb-api.service | sed -n '1,120p'
echo
echo '=== drop-ins ==='
ls -la /etc/systemd/system/douyinweb-api.service.d/ 2>/dev/null || echo none
for f in /etc/systemd/system/douyinweb-api.service.d/*.conf; do
[ -f "$f" ] || continue
echo "--- $f ---"; cat "$f"
done
echo
echo '=== effective ==='
systemctl show douyinweb-api.service -p MemoryCurrent,MemoryHigh,MemoryMax,MemorySwapMax,MemoryAccounting,OOMPolicy,OOMScoreAdjust,FragmentPath,DropInPaths
echo
echo '=== cgroup v2 ==='
CG=$(systemctl show douyinweb-api.service -p ControlGroup --value)
echo CG=$CG
if [ -n "$CG" ]; then
for f in memory.max memory.high memory.current memory.swap.max memory.events; do
p="/sys/fs/cgroup${CG}/$f"
[ -f "$p" ] && echo "$f=$(cat $p)"
done
fi
echo
echo '=== api rss now ==='
ps -o pid,rss,cmd -C python | grep -E 'uvicorn|app.main' | head -5
free -h | head -3
"""
)
# Harden: MemoryHigh=700M MemoryMax=900M (leave room for neko+ffmpeg on 3.8G host)
# OOMScoreAdjust=400 so API dies before chrome if global OOM (chrome protected -800)
# Only change drop-in, don't touch unrelated units
run(
r"""
set -euo pipefail
mkdir -p /etc/systemd/system/douyinweb-api.service.d
cat > /etc/systemd/system/douyinweb-api.service.d/memory.conf <<'EOF'
[Service]
MemoryAccounting=yes
# Soft throttle early; hard kill if ballooning (was ~1.4G max / historically 2G RSS)
MemoryHigh=700M
MemoryMax=900M
MemorySwapMax=256M
OOMPolicy=kill
# Prefer kill API over Neko Chrome on global OOM (chrome uses oom_score_adj=-800)
OOMScoreAdjust=400
EOF
systemctl daemon-reload
systemctl restart douyinweb-api.service
sleep 4
systemctl is-active douyinweb-api.service
systemctl show douyinweb-api.service -p MemoryCurrent,MemoryHigh,MemoryMax,MemorySwapMax,OOMPolicy,OOMScoreAdjust
CG=$(systemctl show douyinweb-api.service -p ControlGroup --value)
echo CG=$CG
for f in memory.max memory.high memory.current memory.swap.max; do
p="/sys/fs/cgroup${CG}/$f"
[ -f "$p" ] && echo "$f=$(cat $p)"
done
# smoke
curl -sS -m 8 http://127.0.0.1:8014/api/health | head -c 200; echo
free -h | head -3
"""
)
c.close()
print("DONE")