← back to Ventura Corridor

scripts/hawk-local.sh

48 lines

#!/usr/bin/env bash
# Local PM2 watchdog for ventura-corridor.
# Runs every 30m via launchd com.steve.ventura-corridor-hawk.
# Daemon dead → pm2 resurrect. ventura-corridor not online → pm2 restart.
# Modeled on site-factory/scripts/hawk-local.sh.
#
# Why not curl-based: a naive `curl health || pm2 restart` mass-restarts on
# any transient timeout (slow DB query, brief CPU contention). pm2 already
# autorestarts genuinely-crashed processes; this hawk's only job is to catch
# the "process truly hung/missing" case, which means status != online.

set -uo pipefail

# launchd's env is minimal — pm2 internally calls `node` so we need it on PATH
export PATH="/Users/macstudio3/.npm-global/bin:/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin"

PM2=/Users/macstudio3/.npm-global/bin/pm2
LOG=/Users/macstudio3/Projects/ventura-corridor/logs/hawk.log
TS() { date -u +%FT%TZ; }
mkdir -p "$(dirname "$LOG")"

if ! JLIST=$("$PM2" jlist 2>/dev/null); then
  echo "[$(TS)] DAEMON DOWN — running pm2 resurrect" >> "$LOG"
  "$PM2" resurrect >> "$LOG" 2>&1
  exit 0
fi

STATUS=$(printf '%s' "$JLIST" \
  | /usr/bin/python3 -c '
import json, sys
try:
    procs = json.load(sys.stdin)
except Exception:
    sys.exit(0)
for p in procs:
    if p.get("name") == "ventura-corridor":
        print(p.get("pm2_env", {}).get("status", "missing"))
        sys.exit(0)
print("missing")
')

if [ "$STATUS" = "online" ]; then
  echo "[$(TS)] OK — ventura-corridor online" >> "$LOG"
else
  echo "[$(TS)] ventura-corridor status=$STATUS — restarting" >> "$LOG"
  "$PM2" restart ventura-corridor >> "$LOG" 2>&1
fi