Files
mtusi2026lab5/scripts/stop-one.sh
T
2026-11-20 20:11:39 +03:00

50 lines
1.8 KiB
Bash

#!/bin/sh
# Stop exactly one API replica selected by TARGET_INSTANCE_ID.
#
# The public failover test sets TARGET_INSTANCE_ID to the X-Instance-Id that served
# the test request. In this stack X-Instance-Id is the container hostname, so the
# target task is found by inspecting every running task's container and stopped by
# container id. Swarm then creates a *new* task (new hostname) after its restart
# delay: the laboratory explicitly allows that, and the test checks that the old
# X-Instance-Id disappears from responses. Restore with scripts/restore.sh.
set -eu
stack=${STACK_NAME:-lab5}
service="${stack}_api"
target=${TARGET_INSTANCE_ID:-}
if [ -z "$target" ]; then
printf 'TARGET_INSTANCE_ID is required\n' >&2
exit 2
fi
if ! docker service inspect "$service" >/dev/null 2>&1; then
printf 'service %s not found\n' "$service" >&2
exit 3
fi
find_container() {
# Prints the container id whose hostname equals $target; empty if not found.
for task in $(docker service ps -q "$service" --filter desired-state=running); do
container=$(docker inspect -f '{{.Status.ContainerStatus.ContainerID}}' "$task" 2>/dev/null || true)
[ -n "$container" ] || continue
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
if [ "$hostname" = "$target" ]; then
printf '%s\n' "$container"
return 0
fi
done
return 0
}
container=$(find_container)
if [ -z "$container" ]; then
printf 'target instance %s not found among running tasks\n' "$target" >&2
exit 4
fi
printf 'stopping instance %s container %s\n' "$target" "$container"
docker stop --time 3 "$container" >/dev/null
# Swarm may already be creating a replacement task with a different hostname;
# the target container itself was stopped by id and is no longer served.
printf 'instance %s stopped\n' "$target"