Files
mtusi2026lab3/scripts/api-instances.sh
T

35 lines
1.3 KiB
Bash
Executable File

#!/bin/sh
# Lists the API containers of this compose project, one per line:
# <container id> <name> <state> <alias> <image id>
# The alias is what the process sends as X-Instance-Id. It is random per
# process, so it is asked from the process itself, over the same wget the
# Docker healthcheck uses, from inside the container. A container that is not
# running has no alias and shows "-". The replicas are asked in parallel: the
# failover hook that relies on this list must return within 10 seconds.
set -eu
cd "$(dirname "$0")/.."
ids=$(docker compose ps -aq api)
[ -n "$ids" ] || exit 0
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
docker inspect --format '{{.Id}} {{.Name}} {{.State.Status}} {{.Image}}' $ids >"$tmp/containers"
while read -r id name state image; do
if [ "$state" = running ]; then
# wget prints the response headers on stderr; the body is dropped.
(docker exec "$id" wget -S -q -O - http://127.0.0.1:8080/health/live 2>&1 >/dev/null |
sed -n 's/^ *[Xx]-[Ii]nstance-[Ii]d: *//p' | tr -d '\r' | head -n 1 >"$tmp/$id") &
fi
done <"$tmp/containers"
wait
while read -r id name state image; do
alias=-
if [ -s "$tmp/$id" ]; then
alias=$(cat "$tmp/$id")
fi
image=${image#sha256:}
printf '%s %s %s %s %s\n' "$(printf '%s' "$id" | cut -c1-12)" "${name#/}" "$state" "$alias" "$(printf '%s' "$image" | cut -c1-12)"
done <"$tmp/containers"