#!/bin/sh set -eu # Fault-injection hook: stop exactly ONE api replica of the lab3 stand. # # TARGET_INSTANCE_ID= scripts/stop-one.sh # # The task value is the instance alias the API reports in X-Instance-Id, i.e. # the container hostname (docker's default = short container id). Container # names of the api service are matched too. The container is only stopped # (docker stop); databases, the load balancer and volumes are left untouched, # and the replica stays down until it is started again explicitly, e.g. # docker compose --env-file .env up -d --no-deps api # No credentials are printed. : "${TARGET_INSTANCE_ID:?test provides target API instance alias}" PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab3} candidates=$(docker ps -q \ --filter "label=com.docker.compose.project=${PROJECT}" \ --filter "label=com.docker.compose.service=api") if [ -z "$candidates" ]; then printf 'stop-one.sh: no api containers of project %s are running\n' "$PROJECT" >&2 exit 1 fi # Matches the requested alias against every reasonable identifier of a replica: # container hostname (= X-Instance-Id), full/short container id, full container # name (mtusi-messenger-lab3-api-1) and the service-local suffix (api-1). match_replica() { target=$1 full_id=$2 short_id=$3 name=$4 hostname=$5 suffix=${name#${PROJECT}-} [ "$target" = "$hostname" ] && return 0 [ "$target" = "$full_id" ] && return 0 [ "$target" = "$short_id" ] && return 0 [ "$target" = "$name" ] && return 0 [ "$target" = "$suffix" ] && return 0 return 1 } matched="" matched_names="" for id in $candidates; do info=$(docker inspect --format '{{.Id}} {{.Name}} {{.Config.Hostname}}' "$id") full_id=$(printf '%s' "$info" | cut -d' ' -f1) name=$(printf '%s' "$info" | cut -d' ' -f2 | sed 's|^/||') hostname=$(printf '%s' "$info" | cut -d' ' -f3) short_id=$(printf '%s' "$full_id" | cut -c1-12) if match_replica "$TARGET_INSTANCE_ID" "$full_id" "$short_id" "$name" "$hostname"; then matched="$matched $id" matched_names="$matched_names $name" fi done if [ -z "$matched" ]; then printf 'stop-one.sh: no api replica matches TARGET_INSTANCE_ID=%s\n' "$TARGET_INSTANCE_ID" >&2 exit 1 fi # Shut down cleanly (SIGTERM) but never hang the caller for long. for id in $matched; do docker stop --time 5 "$id" >/dev/null done printf 'stop-one.sh: stopped api replica(s):%s\n' "$matched_names" exit 0