الملفات
ghaymah-exam-OmarHussein-SRE/q1-deploy-monitor/health-check.sh

43 أسطر
1.3 KiB
Bash

#!/usr/bin/env bash
#
# Simple bash health monitor - polls /health every 30s.
# Usage: ./health-check.sh https://q1-deploy-monitor-cad54f6feeb3.hosted.ghaymah.systems/ [interval_seconds]
set -euo pipefail
BASE_URL="${1:?Usage: $0 <base_url> [interval_seconds]}"
INTERVAL="${2:-30}"
HEALTH_URL="${BASE_URL%/}/health"
LOG_FILE="monitor.log"
FAILURE_THRESHOLD=3
failures=0
log() {
echo "$(date -u +"%Y-%m-%dT%H:%M:%SZ") [$1] $2" | tee -a "$LOG_FILE"
}
log "INFO" "Starting monitor for $HEALTH_URL every ${INTERVAL}s"
while true; do
start_ns=$(date +%s%N)
http_code=$(curl -o /tmp/health_resp.json -s -w "%{http_code}" --max-time 5 "$HEALTH_URL" || echo "000")
end_ns=$(date +%s%N)
elapsed_ms=$(( (end_ns - start_ns) / 1000000 ))
if [ "$http_code" == "200" ]; then
if [ "$failures" -gt 0 ]; then
log "INFO" "Service RECOVERED after $failures failed check(s)."
fi
failures=0
log "INFO" "OK status=$http_code response_time=${elapsed_ms}ms"
else
failures=$((failures + 1))
log "WARN" "FAIL attempt=$failures status=$http_code"
if [ "$failures" -ge "$FAILURE_THRESHOLD" ]; then
log "ERROR" "ALERT: $BASE_URL has failed $failures consecutive health checks!"
fi
fi
sleep "$INTERVAL"
done