douyinWEB/scripts/linux/build_orphan_watch.sh
hackrobot 1e8eb0130a Sync dylive production working tree to test3.
Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
2026-10-14 07:04:18 +00:00

84 lines
2.8 KiB
Bash

#!/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" "$*"; }
_kill_if_frontend() {
# $1=pid $2=label
local p="$1" label="$2"
local exe cwd
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 $label pid=$p"
;;
esac
}
# 1) SWC/native binary named "usr" (Next turbopack/swc temp)
killed=0
for p in $(pgrep -x usr 2>/dev/null || true); do
_kill_if_frontend "$p" usr
done
# 1b) Fake "pm2" left in Next build cache (.d* / .r*) — not real PM2 daemon
for p in $(pgrep -x pm2 2>/dev/null || true); do
_kill_if_frontend "$p" pm2
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
# 2b) Any process whose CWD is a Next temp dir under frontend (.d* / .r*)
if [ -d "$FRONTEND_DIR" ]; then
for p in $(ls -1 /proc 2>/dev/null | grep -E '^[0-9]+$' || true); do
cwd=$(readlink /proc/$p/cwd 2>/dev/null || true)
case "$cwd" in
"$FRONTEND_DIR"/.d*|"$FRONTEND_DIR"/.r*)
# Keep next-server / node server.mjs alone if they somehow land here (shouldn't)
cmd=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null)
case "$cmd" in
*next-server*|*server.mjs*|*/.next/standalone*)
;;
*)
kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed tempdir pid=$p cwd=$cwd"
;;
esac
;;
esac
done
fi
# 3) Stale Next temp dirs under frontend (.r* and .d* build caches)
if [ -d "$FRONTEND_DIR" ]; then
find "$FRONTEND_DIR" -maxdepth 1 -type d \( -name '.r*' -o -name '.d*' \) -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