monitor.sh 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env bash
  2. # LYNX SHARE health + resource check (lynx-monitor.timer, every 5 minutes, as root).
  3. # - restarts a service whose /health fails twice in a row (systemd's Restart=always covers crashes; this covers hangs)
  4. # - checks the public HTTPS path through Caddy (certificate, DNS, proxy) and reloads Caddy if only that fails
  5. # - logs one line per run to /var/log/lynx/monitor.log; warnings also go to the journal (journalctl -t lynx-monitor)
  6. set -uo pipefail
  7. LOG=/var/log/lynx/monitor.log
  8. STATE=/run/lynx-monitor; mkdir -p "$STATE"
  9. warn() { logger -t lynx-monitor -p user.warning "$*"; echo "$(date -u +%FT%TZ) WARN $*" >> "$LOG"; }
  10. check() { # name url unit
  11. if curl -sf -m 10 -o /dev/null "$2"; then rm -f "$STATE/$1.fail"; echo ok; return; fi
  12. if [ -e "$STATE/$1.fail" ]; then warn "$1 health failed twice: restarting $3"; systemctl restart "$3"; rm -f "$STATE/$1.fail"
  13. else touch "$STATE/$1.fail"; fi
  14. echo FAIL
  15. }
  16. api=$(check api http://127.0.0.1:8081/health lynx-api)
  17. relay=$(check relay http://127.0.0.1:8082/health lynx-relay)
  18. pub=ok
  19. for h in api relay; do
  20. if ! curl -sf -m 15 -o /dev/null "https://$h.lynx-share.com/health"; then pub=FAIL; fi
  21. done
  22. if [ "$pub" = FAIL ] && [ "$api" = ok ] && [ "$relay" = ok ]; then
  23. if [ -e "$STATE/public.fail" ]; then warn "public HTTPS failed twice: reloading caddy"; systemctl reload-or-restart caddy; rm -f "$STATE/public.fail"
  24. else touch "$STATE/public.fail"; fi
  25. else rm -f "$STATE/public.fail"; fi
  26. load=$(cut -d' ' -f1-3 /proc/loadavg)
  27. mem=$(free -m | awk '/^Mem:/ {printf "%d/%dMB", $3, $2}')
  28. disk=$(df -P / | awk 'NR==2 {print $5}')
  29. diskpct=${disk%\%}
  30. shares=$(du -sm /var/lib/lynx/shares 2>/dev/null | cut -f1)
  31. echo "$(date -u +%FT%TZ) api=$api relay=$relay https=$pub load=[$load] mem=$mem disk=$disk shares=${shares:-0}MB" >> "$LOG"
  32. [ "$diskpct" -ge 85 ] && warn "disk at $disk"
  33. avail=$(free -m | awk '/^Mem:/ {print $7}'); [ "$avail" -lt 500 ] && warn "low memory: ${avail}MB available"
  34. for u in lynx-api lynx-relay caddy; do systemctl is-active -q "$u" || warn "$u is not active"; done
  35. exit 0