This commit is contained in:
2026-11-20 20:11:39 +03:00
parent 276dbdad8a
commit b4d667532f
116 changed files with 11777 additions and 40 deletions
+55
View File
@@ -0,0 +1,55 @@
#!/bin/sh
# Create local Swarm secret files under secrets/ (gitignored, never printed).
# Existing files are never overwritten, so rerunning the script is safe.
# Usage: sh scripts/bootstrap-secrets.sh
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
dir="$root/secrets"
# Files are created with mode 600: group and other have no access.
umask 077
mkdir -p "$dir"
random_hex() {
head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'
}
# 10 bytes = 20 hex chars: MinIO access keys are limited to 20 characters.
random_access_key() {
head -c 10 /dev/urandom | od -An -tx1 | tr -d ' \n'
}
# write <name> <value>: keeps the current file if it already has content.
write() {
name=$1
value=$2
if [ -s "$dir/$name" ]; then
printf 'keep secrets/%s\n' "$name"
return 0
fi
printf '%s\n' "$value" > "$dir/$name"
printf 'create secrets/%s\n' "$name"
}
write postgres_password "$(random_hex)"
write cursor_secret "$(random_hex)"
write cache_url 'redis://valkey:6379/0'
# The password is hex, so the URL needs no percent-encoding.
write database_url "postgresql+asyncpg://messenger:$(cat "$dir/postgres_password")@postgres:5432/messenger"
# MinIO: root credentials only for minio-init; API uses a separate restricted
# pair. The access key is 20 hex chars (MinIO limit), the secret is 64 hex chars.
write s3_root_user 'messenger-root'
write s3_root_password "$(random_hex)"
write s3_access_key_id "$(random_access_key)"
write s3_secret_access_key "$(random_hex)"
# RabbitMQ: default user создаётся при первом старте из этих файлов; URL
# использует URL-safe hex-пароль (percent-encoding не нужен).
write rabbitmq_user 'messenger'
write rabbitmq_password "$(random_hex)"
write broker_url "amqp://messenger:$(cat "$dir/rabbitmq_password")@rabbitmq:5672/%2F"
printf 'done: %s\n' "$dir"
printf 'next: sh scripts/deploy.sh\n'
+48
View File
@@ -0,0 +1,48 @@
#!/bin/sh
# Проверка приватности bucket и ограниченности API-пользователя.
#
# Запускается в образе MinIO (в нём есть mc и curl) на backend-сети стенда:
# docker run --rm --network lab5_backend --user 0 \
# -v "$PWD/scripts:/scripts:ro" -v "$PWD/secrets:/run/secrets:ro" \
# -e S3_ENDPOINT=http://minio:9000 -e S3_BUCKET=messenger-attachments \
# --entrypoint /bin/sh minio/minio:... /scripts/check-bucket-private.sh
#
# Root нужен только для чтения local secrets в этом проверочном контейнере;
# API-пользователь проверяется отдельным alias и не имеет прав на bucket.
set -eu
endpoint=${S3_ENDPOINT:-http://minio:9000}
bucket=${S3_BUCKET:-messenger-attachments}
export MC_CONFIG_DIR=${MC_CONFIG_DIR:-/tmp/.mc}
mkdir -p "$MC_CONFIG_DIR"
root_user=$(cat "${MINIO_ROOT_USER_FILE:?}")
root_password=$(cat "${MINIO_ROOT_PASSWORD_FILE:?}")
access_key=$(cat "${S3_ACCESS_KEY_ID_FILE:?}")
secret_key=$(cat "${S3_SECRET_ACCESS_KEY_FILE:?}")
mc alias set root "$endpoint" "$root_user" "$root_password" >/dev/null
mc alias set api "$endpoint" "$access_key" "$secret_key" >/dev/null
printf 'anonymous-policy: '
mc anonymous get "root/$bucket" 2>&1 || true
printf 'anonymous-http-get: '
curl -s -o /dev/null -w '%{http_code}\n' "$endpoint/$bucket/attachments/does-not-exist"
printf 'api-list-attachments: '
mc ls "api/$bucket/attachments/" >/tmp/list.txt 2>&1 && head -1 /tmp/list.txt || cat /tmp/list.txt
printf 'api-create-bucket: '
if mc mb "api/should-not-exist" >/dev/null 2>&1; then
printf 'ALLOWED (unexpected)\n'
mc rb "api/should-not-exist" >/dev/null 2>&1 || true
else
printf 'denied (expected)\n'
fi
printf 'api-put-other-bucket: '
echo test >/tmp/probe
if mc cp /tmp/probe "api/other-bucket/" >/dev/null 2>&1; then
printf 'ALLOWED (unexpected)\n'
else
printf 'denied (expected)\n'
fi
printf 'root-bucket-list: '
mc ls "root/$bucket/" >/dev/null 2>&1 && printf 'ok\n' || printf 'failed\n'
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (deploy).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode deploy %*
exit /b %ERRORLEVEL%
+54
View File
@@ -0,0 +1,54 @@
#!/bin/sh
# Build the application image, create local Swarm secrets once, deploy the stack.
#
# Prerequisites: Docker Engine with Swarm mode (docker swarm init is done here if
# needed) and the files created by scripts/bootstrap-secrets.sh. No secret value
# is printed. This is the one documented bootstrap sequence for stack.yaml.
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
# The public failover test invokes the action script without a shell; it must be
# executable on POSIX. Git may not preserve the mode on a Windows checkout.
chmod +x scripts/stop-one.sh scripts/restore.sh scripts/restart.sh scripts/rolling-update.sh scripts/deploy.sh 2>/dev/null || true
stack=${STACK_NAME:-lab5}
image=${API_IMAGE:-mtusi-messenger-lab5:5.0.0}
state=$(docker info --format '{{.Swarm.LocalNodeState}}')
if [ "$state" != "active" ]; then
docker swarm init >/dev/null
fi
sh scripts/bootstrap-secrets.sh
for name in database_url cache_url broker_url postgres_password cursor_secret \
rabbitmq_user rabbitmq_password \
s3_root_user s3_root_password s3_access_key_id s3_secret_access_key; do
if ! docker secret inspect "${stack}_${name}" >/dev/null 2>&1; then
docker secret create "${stack}_${name}" "secrets/${name}" >/dev/null
fi
done
docker build -t "$image" .
# Swarm configs неизменяемы. Перед повторным deploy убираем завершившийся
# minio-init и его config, иначе stack deploy попытается обновить config и
# получит "only updates to Labels are allowed". На первом deploy это no-op.
docker service rm "${stack}_minio-init" >/dev/null 2>&1 || true
docker config rm "${stack}_lab5_minio_init" >/dev/null 2>&1 || true
API_IMAGE="$image" docker stack deploy --resolve-image never -c stack.yaml "$stack"
i=0
while [ "$i" -lt 90 ]; do
if curl -fsS http://127.0.0.1:8080/health/ready >/dev/null 2>&1; then
printf 'deployed: http://127.0.0.1:8080 (image %s)\n' "$image"
docker stack services "$stack"
exit 0
fi
i=$((i + 1))
sleep 2
done
printf 'stack did not become ready within 180s\n' >&2
docker stack services "$stack" >&2 || true
exit 1
+188
View File
@@ -0,0 +1,188 @@
# Windows twin of scripts/deploy.sh, stop-one.sh, restore.sh, restart.sh and
# rolling-update.sh. The public resilience test launches an action script with
# Popen([script]) without a shell; on native Windows a .cmd wrapper is required.
#
# X-Instance-Id is the Swarm task container hostname, so a target is resolved by
# inspecting running task containers, not by trusting the header alone.
param(
[Parameter(Mandatory = $true)]
[ValidateSet('deploy', 'stop-one', 'restore', 'restart', 'rollout', 'stop-worker', 'start-worker', 'restart-broker')]
[string]$Mode,
[string]$Image = ''
)
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
Set-Location $root
$stack = if ($env:STACK_NAME) { $env:STACK_NAME } else { 'lab5' }
$service = "$stack" + '_api'
if (-not $Image) {
$Image = if ($env:API_IMAGE) { $env:API_IMAGE } else { 'mtusi-messenger-lab5:5.0.0' }
}
function Invoke-Docker {
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)
& docker @Arguments
if ($LASTEXITCODE -ne 0) {
throw "docker $($Arguments -join ' ') failed with exit code $LASTEXITCODE"
}
}
function Test-Ready {
try {
$response = Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:8080/health/ready' -TimeoutSec 3
return $response.StatusCode -eq 200
} catch {
return $false
}
}
function Wait-Ready {
param([int]$Seconds = 180)
$deadline = (Get-Date).AddSeconds($Seconds)
while ((Get-Date) -lt $deadline) {
if (Test-Ready) { return }
Start-Sleep -Seconds 2
}
throw "stack did not become ready within $Seconds seconds"
}
function Get-RunningTasks {
return @(& docker service ps -q $service --filter desired-state=running)
}
function Find-TargetContainer {
param([string]$Target)
foreach ($task in (Get-RunningTasks)) {
$container = (& docker inspect -f '{{.Status.ContainerStatus.ContainerID}}' $task 2>$null)
if (-not $container) { continue }
$hostname = (& docker inspect -f '{{.Config.Hostname}}' $container 2>$null)
if ($hostname -eq $Target) { return $container }
}
return $null
}
function New-HexSecret {
param([int]$Bytes = 32)
$buffer = New-Object byte[] $Bytes
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($buffer)
return (-join ($buffer | ForEach-Object { $_.ToString('x2') }))
}
function Ensure-SecretFiles {
New-Item -ItemType Directory -Force -Path 'secrets' | Out-Null
$passwordPath = Join-Path 'secrets' 'postgres_password'
$password = if ((Test-Path $passwordPath) -and (Get-Item $passwordPath).Length -gt 0) {
(Get-Content $passwordPath -Raw).Trim()
} else {
New-HexSecret
}
$rabbitPassword = if ((Test-Path (Join-Path 'secrets' 'rabbitmq_password')) -and (Get-Item (Join-Path 'secrets' 'rabbitmq_password')).Length -gt 0) {
(Get-Content (Join-Path 'secrets' 'rabbitmq_password') -Raw).Trim()
} else {
New-HexSecret
}
$defaults = [ordered]@{
postgres_password = $password
cursor_secret = (New-HexSecret)
cache_url = 'redis://valkey:6379/0'
database_url = "postgresql+asyncpg://messenger:$password@postgres:5432/messenger"
rabbitmq_user = 'messenger'
rabbitmq_password = $rabbitPassword
broker_url = "amqp://messenger:$rabbitPassword@rabbitmq:5672/%2F"
s3_root_user = 'messenger-root'
s3_root_password = (New-HexSecret)
s3_access_key_id = (New-HexSecret -Bytes 10)
s3_secret_access_key = (New-HexSecret)
}
foreach ($name in $defaults.Keys) {
$path = Join-Path 'secrets' $name
if (-not (Test-Path $path) -or (Get-Item $path).Length -eq 0) {
Set-Content -NoNewline -Encoding ascii -Path $path -Value $defaults[$name]
}
}
}
function Ensure-Secrets {
$names = @('database_url', 'cache_url', 'broker_url', 'postgres_password', 'cursor_secret',
'rabbitmq_user', 'rabbitmq_password',
's3_root_user', 's3_root_password', 's3_access_key_id', 's3_secret_access_key')
$existing = @(& docker secret ls --format '{{.Name}}')
foreach ($name in $names) {
$secret = "$stack" + '_' + $name
if ($existing -notcontains $secret) {
Invoke-Docker secret create $secret (Join-Path 'secrets' $name) | Out-Null
}
}
}
switch ($Mode) {
'deploy' {
$state = (& docker info --format '{{.Swarm.LocalNodeState}}').Trim()
if ($state -ne 'active') { Invoke-Docker swarm init | Out-Null }
Ensure-SecretFiles
Ensure-Secrets
Invoke-Docker build -t $Image . | Out-Null
$env:API_IMAGE = $Image
# Swarm configs неизменяемы: перед повторным deploy убираем завершившийся
# minio-init и его config; на первом deploy это no-op.
& cmd /c "docker service rm ${stack}_minio-init >nul 2>&1"
& cmd /c "docker config rm ${stack}_lab5_minio_init >nul 2>&1"
Invoke-Docker stack deploy --resolve-image never -c stack.yaml $stack | Out-Null
Wait-Ready
& docker stack services $stack
}
'stop-one' {
$target = $env:TARGET_INSTANCE_ID
if (-not $target) { throw 'TARGET_INSTANCE_ID is required' }
$container = Find-TargetContainer $target
if (-not $container) { throw "target instance $target not found among running tasks" }
Write-Output "stopping instance $target container $container"
Invoke-Docker stop --time 3 $container | Out-Null
# Swarm may already be creating a replacement task; the target container
# itself was stopped by id and its X-Instance-Id will not be served again.
Write-Output "instance $target stopped"
}
'restore' {
Invoke-Docker service update --restart-condition any --replicas 2 $service | Out-Null
$running = @(Get-RunningTasks).Count
if ($running -lt 2) { Invoke-Docker service update --force $service | Out-Null }
$deadline = (Get-Date).AddSeconds(120)
while ((Get-Date) -lt $deadline) {
$running = @(Get-RunningTasks).Count
if ($running -ge 2 -and (Test-Ready)) {
Write-Output "api restored: $running running tasks and readiness OK"
exit 0
}
Start-Sleep -Seconds 2
}
throw 'api did not recover within 120s'
}
'restart' {
foreach ($name in @('postgres', 'valkey', 'minio', 'rabbitmq', 'relay', 'worker', 'api', 'traefik')) {
$svc = $stack + '_' + $name
Write-Output "restarting $svc"
Invoke-Docker service update --detach=true --force $svc | Out-Null
}
Wait-Ready
Write-Output 'stack ready after restart'
}
'stop-worker' {
Invoke-Docker service scale "${stack}_worker=0" | Out-Null
Write-Output 'worker scaled to 0'
}
'start-worker' {
Invoke-Docker service scale "${stack}_worker=1" | Out-Null
Write-Output 'worker scaled to 1'
}
'restart-broker' {
Invoke-Docker service update --force "${stack}_rabbitmq" | Out-Null
Start-Sleep -Seconds 10
Write-Output 'rabbitmq restart requested'
}
'rollout' {
Invoke-Docker build --build-arg APP_REVISION=$Image -t $Image . | Out-Null
Invoke-Docker service update --image $Image --update-order start-first --update-parallelism 1 --update-delay 5s --update-failure-action rollback $service | Out-Null
& docker service ps $service --no-trunc
}
}
+86
View File
@@ -0,0 +1,86 @@
#!/bin/sh
# Идемпотентный bootstrap приватного bucket и ограниченного S3-пользователя.
#
# Запускается один раз сервисом minio-init (образ MinIO уже содержит mc).
# Повторный запуск не удаляет данные: bucket создаётся с --ignore-existing,
# пользователь переиспользуется, политика пересоздаётся и привязывается заново.
# Root-credentials используются только здесь; API получает отдельную пару.
set -eu
endpoint=${S3_ENDPOINT:-http://minio:9000}
bucket=${S3_BUCKET:-messenger-attachments}
policy_name=${S3_POLICY_NAME:-messenger-attachments-rw}
read_secret() {
# $1 — путь к Docker secret; секрет не печатается.
cat "$1"
}
root_user=$(read_secret "${MINIO_ROOT_USER_FILE:?MINIO_ROOT_USER_FILE is required}")
root_password=$(read_secret "${MINIO_ROOT_PASSWORD_FILE:?MINIO_ROOT_PASSWORD_FILE is required}")
access_key=$(read_secret "${S3_ACCESS_KEY_ID_FILE:?S3_ACCESS_KEY_ID_FILE is required}")
secret_key=$(read_secret "${S3_SECRET_ACCESS_KEY_FILE:?S3_SECRET_ACCESS_KEY_FILE is required}")
export MC_CONFIG_DIR=${MC_CONFIG_DIR:-/tmp/.mc}
mkdir -p "$MC_CONFIG_DIR"
i=0
until mc alias set local "$endpoint" "$root_user" "$root_password" --api S3v4 >/dev/null 2>&1; do
i=$((i + 1))
if [ "$i" -ge 60 ]; then
printf 'minio is not reachable at %s\n' "$endpoint" >&2
exit 1
fi
sleep 2
done
until mc ready local >/dev/null 2>&1; do
i=$((i + 1))
if [ "$i" -ge 120 ]; then
printf 'minio did not become ready\n' >&2
exit 1
fi
sleep 1
done
mc mb --ignore-existing "local/$bucket" >/dev/null
mc anonymous set none "local/$bucket" >/dev/null
# Пользователь API: при повторном запуске оставляем существующего, чтобы не
# разорвать уже работающий API. Секрет при первом создании берётся из secrets.
mc admin user add local "$access_key" "$secret_key" >/dev/null 2>&1 || true
if ! mc admin user info local "$access_key" >/dev/null 2>&1; then
printf 'failed to create API user\n' >&2
exit 1
fi
cat >/tmp/messenger-attachments-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::$bucket/attachments/*"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::$bucket"],
"Condition": {"StringLike": {"s3:prefix": ["attachments/*"]}}
},
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::$bucket"]
}
]
}
EOF
mc admin policy detach local "$policy_name" --user "$access_key" >/dev/null 2>&1 || true
mc admin policy remove local "$policy_name" >/dev/null 2>&1 || true
mc admin policy create local "$policy_name" /tmp/messenger-attachments-policy.json >/dev/null
mc admin policy attach local "$policy_name" --user "$access_key" >/dev/null
printf 'minio bootstrap complete: bucket=%s private=yes policy=%s\n' "$bucket" "$policy_name"
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Запуск сверки PostgreSQL/S3 внутри работающего API-контейнера.
#
# Использует те же secrets и переменные окружения, что и API, поэтому не
# требует отдельного набора credentials. По умолчанию — dry-run; для удаления
# мусора добавьте --apply.
set -eu
stack=${STACK_NAME:-lab5}
container=$(docker ps -q -f "name=${stack}_api" | head -n 1)
if [ -z "$container" ]; then
printf 'no running %s_api container\n' "$stack" >&2
exit 2
fi
docker exec "$container" python -m messenger.reconcile "$@"
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (restart-broker).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode restart-broker %*
exit /b %ERRORLEVEL%
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Restart RabbitMQ with its named volume; active durable messages must survive.
set -eu
stack=${STACK_NAME:-lab5}
docker service update --force "${stack}_rabbitmq" >/dev/null
printf 'rabbitmq restart requested\n'
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (restart).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode restart %*
exit /b %ERRORLEVEL%
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
# Restart API and every state store without deleting volumes.
#
# Used by make test-persistence. Sessions live in Valkey with AOF and users,
# chats and messages in PostgreSQL, so the same bearer token and data survive.
set -eu
stack=${STACK_NAME:-lab5}
ready_url=${READY_URL:-http://127.0.0.1:8080/health/ready}
for service in "${stack}_postgres" "${stack}_valkey" "${stack}_minio" "${stack}_rabbitmq" \
"${stack}_relay" "${stack}_worker" "${stack}_api" "${stack}_traefik"; do
printf 'restarting %s\n' "$service"
# detach: не ждём сходимости каждого сервиса; готовность проверяется один раз ниже.
docker service update --detach=true --force "$service" >/dev/null
done
i=0
while [ "$i" -lt 60 ]; do
if curl -fsS "$ready_url" >/dev/null 2>&1; then
printf 'stack ready after restart\n'
exit 0
fi
i=$((i + 1))
sleep 2
done
printf 'stack did not become ready within 120s\n' >&2
exit 1
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (restore).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode restore %*
exit /b %ERRORLEVEL%
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
# Restore the API service to 2 replicas after scripts/stop-one.sh.
set -eu
stack=${STACK_NAME:-lab5}
service="${stack}_api"
# Swarm normally creates the replacement itself after stopping one task. This hook
# restores the declared replica count and waits for two healthy tasks; a forced
# rolling update is used only when the service is still under-replicated.
docker service update --restart-condition any --replicas 2 "$service" >/dev/null
running=$(docker service ps -q "$service" --filter desired-state=running | wc -l | tr -d ' ')
if [ "$running" -lt 2 ]; then
docker service update --force "$service" >/dev/null
fi
i=0
while [ "$i" -lt 60 ]; do
running=$(docker service ps -q "$service" --filter desired-state=running | wc -l | tr -d ' ')
if [ "$running" -ge 2 ] && curl -fsS http://127.0.0.1:8080/health/ready >/dev/null 2>&1; then
printf 'api restored: %s running tasks and readiness OK\n' "$running"
exit 0
fi
i=$((i + 1))
sleep 2
done
printf 'api did not recover within 120s\n' >&2
exit 1
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (rollout).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode rollout %*
exit /b %ERRORLEVEL%
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Start-first rolling update of the API service under load.
#
# Swarm replaces one task at a time (parallelism 1), waiting for the new task's
# health check before removing the old one. Traefik keeps routing to ready tasks.
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$root"
stack=${STACK_NAME:-lab5}
image=${API_IMAGE:-mtusi-messenger-lab5:5.0.0}
docker build --build-arg APP_REVISION="$image" -t "$image" .
docker service update \
--image "$image" \
--update-order start-first \
--update-parallelism 1 \
--update-delay 5s \
--update-failure-action rollback \
"${stack}_api"
docker service ps "${stack}_api" --no-trunc
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (start-worker).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode start-worker %*
exit /b %ERRORLEVEL%
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Restore one worker replica after scripts/stop-worker.sh.
set -eu
stack=${STACK_NAME:-lab5}
docker service scale "${stack}_worker=1" >/dev/null
printf 'worker scaled to 1\n'
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (stop-one).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode stop-one %*
exit /b %ERRORLEVEL%
+50
View File
@@ -0,0 +1,50 @@
#!/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"
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper for scripts/hooks.ps1 (stop-worker).
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode stop-worker %*
exit /b %ERRORLEVEL%
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Scale the worker to zero; accepted jobs stay durable in the outbox/queue.
set -eu
stack=${STACK_NAME:-lab5}
docker service scale "${stack}_worker=0" >/dev/null
printf 'worker scaled to 0\n'