Files
mtusi2026lab4/scripts/rolling-restart.sh
2026-11-17 02:09:04 +03:00

40 lines
1.3 KiB
Bash
Executable File

#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
containers=$(docker compose ps -q api)
healthy_count=0
for container in $containers; do
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
if [ "$status" = healthy ]; then
healthy_count=$((healthy_count + 1))
fi
done
if [ "$healthy_count" -lt 2 ]; then
printf '%s\n' 'Rolling restart requires at least two healthy API replicas' >&2
exit 1
fi
for container in $containers; do
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
if [ "$status" != healthy ]; then
printf '%s\n' "Skipping unhealthy API replica: $container" >&2
continue
fi
docker restart --time 10 "$container" >/dev/null
deadline=$(( $(date +%s) + 60 ))
while :; do
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
if [ "$status" = healthy ]; then
break
fi
if [ "$status" = unhealthy ] || [ "$(date +%s)" -ge "$deadline" ]; then
printf '%s\n' "API replica did not become healthy: $container" >&2
exit 1
fi
sleep 1
done
done