Files
health-check/entrypoint.sh
T

74 lines
1.6 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/bin/bash
set -u
timestamp() {
date -u +"%Y-%m-%dT%H:%M:%SZ"
}
log() {
printf '[%s] %s\n' "$(timestamp)" "$1"
}
section() {
printf '\n==================================================\n'
printf '%s\n' "$1"
printf '%s\n' '--------------------------------------------------'
}
fail() {
log "[ERROR] $1"
exit 1
}
# 當 workflow 被取消時,立即結束,避免健康檢查持續重試。
on_terminate() {
log "[WARN] 收到取消訊號,停止健康檢查。"
exit 130
}
trap on_terminate TERM INT
HEALTH_CODE="${HEALTH_CODE:-200}"
section "參數檢查"
if [ -z "${CHECK_URL:-}" ] || [ "$CHECK_URL" = "null" ]; then
fail "CHECK_URL 不可為空。"
fi
if [ -z "$HEALTH_CODE" ] || [ "$HEALTH_CODE" = "null" ]; then
fail "HEALTH_CODE 不可為空。"
fi
log "[INFO] CHECK_URL=$CHECK_URL"
log "[INFO] HEALTH_CODE=$HEALTH_CODE"
section "取得狀態碼"
log "[INFO] 開始檢查:$CHECK_URL"
while true; do
printf '[%s] [INFO] GET %s ... ' "$(timestamp)" "$CHECK_URL"
status_code="$(curl -sS --max-time 60 -o /dev/null -w '%{http_code}' "$CHECK_URL" || true)"
if [ -z "$status_code" ]; then
status_code="000"
fi
printf '%s\n' "$status_code"
if [ "$status_code" = "$HEALTH_CODE" ]; then
log "[OK] 狀態碼符合預期:$status_code"
break
fi
log "[WARN] 目前狀態碼 $status_code,預期 $HEALTH_CODE60 秒後重試。"
sleep 60
done
section "完成"
log "[INFO] 輸出 status_code=$status_code"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
echo "status_code=$status_code" >> "$GITHUB_OUTPUT"
else
log "[WARN] GITHUB_OUTPUT 未設定,略過寫入輸出檔。"
fi