Files
IdP/infra/nginx/99-idp-gateway-watch.sh
2026-06-30 17:01:19 +03:00

73 lines
1.8 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/sh
# После recreate edge-сервисов Docker выдаёт новый IP; без reload nginx шлёт на старый адрес → 502.
set -eu
WATCH_INTERVAL="${IDP_NGINX_WATCH_INTERVAL:-5}"
WATCH_HOSTS="${IDP_NGINX_WATCH_HOSTS:-lendry-id-api-gateway:3000/health lendry-id-frontend:3000/}"
log() {
echo "[idp-nginx-watch] $*"
}
probe_url() {
target="$1"
host="${target%%:*}"
rest="${target#*:}"
port="${rest%%/*}"
path="/${rest#*/}"
[ "$path" = "/${rest}" ] && path="/"
wget -qO- --timeout=3 "http://${host}:${port}${path}" 2>/dev/null | head -c 64 | grep -q .
}
wait_for_upstreams() {
attempt=0
while [ "$attempt" -lt 120 ]; do
ok=1
for target in $WATCH_HOSTS; do
if ! probe_url "$target"; then
ok=0
break
fi
done
if [ "$ok" -eq 1 ]; then
log "upstream-ы доступны"
return 0
fi
attempt=$((attempt + 1))
sleep 1
done
log "WARN: не все upstream-ы ответили за 120с — nginx стартует без ожидания"
return 0
}
watch_upstreams() {
last_ips=""
while true; do
sleep "$WATCH_INTERVAL"
reload=0
current_ips=""
for target in $WATCH_HOSTS; do
host="${target%%:*}"
ip="$(getent hosts "$host" 2>/dev/null | awk '{print $1}' | head -n1 || true)"
current_ips="${current_ips}${host}=${ip};"
if ! probe_url "$target"; then
log "${host} недоступен — reload nginx"
reload=1
break
fi
done
if [ "$reload" -eq 0 ] && [ -n "$last_ips" ] && [ "$current_ips" != "$last_ips" ]; then
log "IP upstream изменился — reload nginx"
reload=1
fi
if [ "$reload" -eq 1 ]; then
nginx -s reload 2>/dev/null || true
fi
last_ips="$current_ips"
done
}
wait_for_upstreams
watch_upstreams &