← back to Professional Directory
scripts/hawk-local.sh
44 lines
#!/usr/bin/env bash
# Local PM2 watchdog for Mac Studio 2.
# Runs every 30m via launchd (~/Library/LaunchAgents/com.steve.pd-hawk.plist).
# Daemon-level: if `pm2 jlist` fails the daemon is dead → `pm2 resurrect`.
# Agent-level: any pd-* not "online" → `pm2 restart`.
set -uo pipefail
PM2=/Users/macstudio3/.npm-global/bin/pm2
LOG=/Users/macstudio3/Projects/professional-directory/logs/hawk.log
TS() { date +%FT%T%z; }
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
DOWN=$(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:
name = p.get("name", "")
status = p.get("pm2_env", {}).get("status", "")
if name.startswith("pd-") and status != "online":
print(f"{name} {status}")
')
if [ -n "$DOWN" ]; then
echo "[$(TS)] pd-* not online:" >> "$LOG"
printf '%s\n' "$DOWN" >> "$LOG"
while IFS= read -r line; do
name="${line%% *}"
"$PM2" restart "$name" >> "$LOG" 2>&1
done <<< "$DOWN"
else
echo "[$(TS)] OK — all pd-* online" >> "$LOG"
fi