#!/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