Completed for a grade of four
This commit is contained in:
Executable
+40
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env bash
|
||||
# Replaces the API replicas one by one with a freshly built image while the balancer keeps serving.
|
||||
# 1. build the new image, 2. apply migrations once (they must be compatible with the running version),
|
||||
# 3. for every old replica: start one new replica, wait until HAProxy has it UP, then stop (drain) and remove the old.
|
||||
# The number of serving replicas never drops below the configured count.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
build_id=${BUILD_ID:-$(git rev-parse --short HEAD)-$(date +%s)}
|
||||
log() { echo "$(date -u +%H:%M:%S) $*"; }
|
||||
|
||||
up_in_lb() {
|
||||
docker compose exec -T lb wget -qO- 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1 == "api" && $2 != "BACKEND" && $18 == "UP"' | wc -l
|
||||
}
|
||||
|
||||
log "build image (BUILD_ID=$build_id)"
|
||||
docker compose build --quiet --build-arg BUILD_ID="$build_id" api
|
||||
|
||||
log "migrate"
|
||||
docker compose run --rm --no-deps migrate > /dev/null
|
||||
|
||||
old=$(docker compose ps -q api)
|
||||
count=$(echo "$old" | wc -l | tr -d ' ')
|
||||
|
||||
for container in $old; do
|
||||
before=$(docker compose ps -q api | sort)
|
||||
docker compose up -d --no-deps --no-recreate --scale api=$((count + 1)) api 2> /dev/null
|
||||
new=$(comm -13 <(echo "$before") <(docker compose ps -q api | sort))
|
||||
log "started $(docker inspect -f '{{.Name}}' "$new") ($(echo "$new" | cut -c1-12))"
|
||||
|
||||
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ]; do sleep 0.5; done
|
||||
until [ "$(up_in_lb)" -ge $((count + 1)) ]; do sleep 0.5; done
|
||||
log "new replica is UP in HAProxy"
|
||||
|
||||
docker stop --time 9 "$container" > /dev/null
|
||||
docker rm "$container" > /dev/null
|
||||
log "stopped and removed $(echo "$container" | cut -c1-12)"
|
||||
done
|
||||
|
||||
log "done: $(docker compose ps -q api | while read -r c; do docker inspect -f '{{.Name}} {{index .Config.Labels "org.opencontainers.image.revision"}}' "$c"; done | tr '\n' ' ')"
|
||||
Reference in New Issue
Block a user