Files
mtusi2026lab4/scripts/stop-one.sh
T

30 lines
1.3 KiB
Bash

#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
# Stop exactly ONE API replica and leave it stopped. DB, LB and volumes are untouched.
# X-Instance-Id is the container hostname, i.e. the short Docker container ID.
# Restore afterwards with: docker compose --env-file .env up -d --wait
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]*) valid=no ;;
*) valid=yes ;;
esac
if [ "$valid" = no ] || [ "${#TARGET_INSTANCE_ID}" -lt 12 ]; then
echo "TARGET_INSTANCE_ID is not a container ID" >&2
exit 2
fi
project="${COMPOSE_PROJECT_NAME:-messenger-lab4}"
matches=$(docker ps -q --no-trunc \
--filter "label=com.docker.compose.project=$project" \
--filter "label=com.docker.compose.service=api" | grep "^$TARGET_INSTANCE_ID" || true)
count=$(printf '%s' "$matches" | grep -c . || true)
if [ "$count" -ne 1 ]; then
echo "expected one running api container for $TARGET_INSTANCE_ID, found $count" >&2
exit 1
fi
name=$(docker inspect --format '{{.Name}}' "$matches")
# Graceful: SIGTERM -> 4 s drain (readiness 503, LB drops it) -> <= 3 s in-flight finish.
# SIGKILL only after 9 s, so the hook still returns before the test's 10 s limit.
docker stop --time 9 "$matches" >/dev/null
echo "stopped api replica ${name#/} ($TARGET_INSTANCE_ID)"