Lab 3: HAProxy + 2 replicas, idempotency, graceful shutdown, track 1

This commit is contained in:
2026-11-16 21:48:11 +03:00
parent 0ab3a341aa
commit a3ac20d017
107 changed files with 24088 additions and 15 deletions
+95
View File
@@ -0,0 +1,95 @@
# Windows PowerShell 5.1+ equivalent of scripts/collect-evidence.sh (lab3).
# Starts the Compose stand (LB + API replicas + migrate + PostgreSQL + Redis), runs every check and writes
# outputs to evidence\ (no tokens/passwords). Stops/restarts containers during failover/restart tests.
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 [-WithTrack1] [-SkipFailures]
param([switch]$WithTrack1, [switch]$SkipFailures)
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$env:PYTHONUTF8 = '1'
$env:PYTHONIOENCODING = 'utf-8'
# IPv4 explicitly: on Windows 'localhost' resolves to ::1 first; the LB listens on 127.0.0.1 only.
$env:NO_PROXY = '127.0.0.1,localhost'
$B = 'http://127.0.0.1:8080'
$env:BASE_URL = $B
$env:TTL_BASE_URL = 'http://127.0.0.1:8081'
$ev = Join-Path $root 'evidence'
New-Item -ItemType Directory -Force -Path $ev | Out-Null
# Full path of the Python APPLICATION: a bare 'py' would resolve to a PowerShell function first.
$pyApp = Get-Command py -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
$pythonApp = Get-Command python -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if ($pyApp) { $script:PyExe = $pyApp.Source; $script:PyPre = @('-3') }
elseif ($pythonApp) { $script:PyExe = $pythonApp.Source; $script:PyPre = @() }
else { throw 'Python 3.9+ not found (install from python.org, enable "Add to PATH")' }
function Invoke-Python { & $script:PyExe @script:PyPre @args }
function Dc { & docker compose --env-file .env @args }
$hookStop = if ($IsLinux -or $IsMacOS) { 'scripts/stop-one.sh' } else { 'scripts\stop-one.cmd' }
$hookRestart = if ($IsLinux -or $IsMacOS) { 'scripts/restart.sh' } else { 'scripts\restart.cmd' }
$startReplicas = Join-Path $PSScriptRoot 'start-replicas.ps1'
function Get-Stamp {
$commit = 'n/a'
if (Get-Command git -ErrorAction SilentlyContinue) {
$c = (& git rev-parse --short HEAD 2>$null)
if ($LASTEXITCODE -eq 0 -and $c) { $commit = $c }
}
'# ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' commit=' + $commit + ' host=' + [Environment]::OSVersion.VersionString + ' cpus=' + [Environment]::ProcessorCount
}
function Invoke-Step([string]$name, [string]$title, [scriptblock]$block) {
Write-Host ('>>> ' + $name) -ForegroundColor Cyan
$global:LASTEXITCODE = 0
$lines = @(& $block 2>&1 | ForEach-Object { "$_" })
$code = $global:LASTEXITCODE
Set-Content -Path (Join-Path $ev ($name + '.txt')) -Encoding UTF8 -Value (@((Get-Stamp), ('$ ' + $title)) + $lines + @('exit=' + $code))
$lines | Select-Object -Last 2 | ForEach-Object { Write-Host (' ' + $_) }
if ($code -ne 0) { Write-Host (' exit=' + $code + ' (see evidence\' + $name + '.txt)') -ForegroundColor Yellow }
}
& docker version --format '{{.Server.Version}}' *> $null
if ($LASTEXITCODE -ne 0) { throw 'Docker is not running: start Docker Desktop first' }
& (Join-Path $PSScriptRoot 'init-secrets.ps1')
Set-Location $root
Write-Host '>>> docker compose up (build, wait for healthchecks)' -ForegroundColor Cyan
Dc --profile ttl up -d --build --wait
if ($LASTEXITCODE -ne 0) { Dc logs --tail=80; throw 'docker compose up failed' }
Invoke-Step 'stack' 'docker version; compose images; ps' { & docker version --format 'docker {{.Server.Version}}'; Dc version; Dc --profile ttl images; Dc --profile ttl ps -a }
Invoke-Step 'instances' 'X-Instance-Id of 6 requests via LB' {
1..6 | ForEach-Object { (Invoke-WebRequest -UseBasicParsing "$B/health/live").Headers['X-Instance-Id'] }
}
Invoke-Step 'make-check' 'python scripts/check_contract.py' { Invoke-Python scripts/check_contract.py }
Invoke-Step 'smoke' "python tests/smoke.py --base-url $B" { Invoke-Python tests/smoke.py --base-url $B }
Invoke-Step 'test-api' 'python student-tests/test_api.py' { Invoke-Python student-tests/test_api.py }
Invoke-Step 'test-idempotency' 'python student-tests/test_idempotency.py' { Invoke-Python student-tests/test_idempotency.py }
Invoke-Step 'test-expiry' 'python student-tests/test_expiry.py # api-ttl via LB :8081' { Invoke-Python student-tests/test_expiry.py }
Invoke-Step 'test-cache-race' 'docker compose run api: python student-tests/test_cache_race.py' {
Dc run --rm --no-deps -T -v ((Join-Path $root 'student-tests') + ':/app/student-tests:ro') --entrypoint python api student-tests/test_cache_race.py
}
Set-Content -Path (Join-Path $ev 'failover-hook.txt') -Encoding UTF8 -Value @()
foreach ($i in 1, 2) {
Invoke-Step ('failover-' + $i) ('python tests/resilience.py --mode failover --action-script ' + $hookStop) {
Invoke-Python tests/resilience.py --mode failover --action-script $hookStop --base-url $B
}
Invoke-Step ('restore-' + $i) 'scripts\start-replicas.ps1' { & $startReplicas }
}
Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Encoding UTF8 -Value @()
Invoke-Step 'persistence' ('python tests/resilience.py --mode persistence --action-script ' + $hookRestart) {
Invoke-Python tests/resilience.py --mode persistence --action-script $hookRestart --base-url $B
}
if (-not $SkipFailures) {
Invoke-Step 'test-failures' 'python student-tests/test_failures.py # stops/starts redis and postgres' { Invoke-Python student-tests/test_failures.py }
}
Invoke-Step 'migrations-rerun' 'docker compose run --rm --no-deps migrate' { Dc run --rm --no-deps migrate }
Invoke-Step 'lb-failover-series' 'python research/lb_experiments.py failover-series --mode both' { Invoke-Python research/lb_experiments.py failover-series --mode both }
Write-Host 'NOTE: rolling update uses scripts/rolling-update.sh (POSIX sh). On Windows run it from Git Bash/WSL.' -ForegroundColor Yellow
Invoke-Step 'load' 'python tests/load.py --duration 30 --concurrency 4' {
Invoke-Python tests/load.py --base-url $B --duration 30 --concurrency 4 --output evidence/load.json
}
if ($WithTrack1) {
$env:COMPOSE_FILE = 'compose.yaml;research/compose.track1.yaml'
Invoke-Step 'track1' 'python research/track1.py run all' { Dc --profile bench build loadgen; Invoke-Python research/track1.py run all }
Remove-Item Env:COMPOSE_FILE
Invoke-Step 'track1-report' 'python research/track1.py report' { Invoke-Python research/track1.py report }
}
Write-Host 'Done: evidence collected in evidence\' -ForegroundColor Green
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Полный прогон доказательств lab3 на Compose-стенде; вывод — evidence/ (без токенов и паролей).
# Останавливает/перезапускает контейнеры стенда (failover, restart, отказы БД/Redis, rolling update).
# Трек 5.1 (≈1 ч) запускается отдельно: make track1 (или SKIP_TRACK1=0 ./scripts/collect-evidence.sh).
set -eu
cd "$(dirname "$0")/.."
. scripts/lib.sh
PY=${PYTHON:-python3}
B=${BASE_URL:-http://127.0.0.1:8080}
export BASE_URL=$B TTL_BASE_URL=${TTL_BASE_URL:-http://127.0.0.1:8081}
mkdir -p evidence
stamp() { echo "# $(now) commit=$(git rev-parse --short HEAD 2>/dev/null || echo n/a) host=$(uname -srm) cpus=$(getconf _NPROCESSORS_ONLN)"; }
run() { name=$1; shift; { stamp; echo "\$ $*"; "$@" 2>&1; echo "exit=$?"; } > "evidence/$name.txt" || true; tail -2 "evidence/$name.txt"; }
./scripts/init-secrets.sh
dc --profile ttl up -d --build --wait
{ stamp; docker version --format 'docker {{.Server.Version}}'; dc version; dc --profile ttl images; dc --profile ttl ps; state; } > evidence/stack.txt 2>&1
run instances sh -c "for i in 1 2 3 4 5 6; do curl -s -o /dev/null -D - $B/health/live | grep -i x-instance-id; done"
run make-check make check
run smoke $PY tests/smoke.py --base-url "$B"
run test-api $PY student-tests/test_api.py
run test-idempotency $PY student-tests/test_idempotency.py
run test-expiry $PY student-tests/test_expiry.py
run test-cache-race make test-cache-race
: > evidence/failover-hook.txt
run failover-1 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B"
run restore-1 ./scripts/start-replicas.sh
run failover-2 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B"
run restore-2 ./scripts/start-replicas.sh
: > evidence/restart-hook.txt
run persistence $PY tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url "$B"
run test-failures $PY student-tests/test_failures.py
run migrations-rerun dc run --rm --no-deps migrate
run lb-failover-series $PY research/lb_experiments.py failover-series --mode both
: > evidence/rolling-update.txt
run lb-rolling-update $PY research/lb_experiments.py rolling-update
run load $PY tests/load.py --base-url "$B" --duration 30 --concurrency 4 --output evidence/load.json
if [ "${SKIP_TRACK1:-1}" = 0 ]; then
run track1 env COMPOSE_FILE=compose.yaml:research/compose.track1.yaml $PY research/track1.py run all
run track1-report $PY research/track1.py report
fi
echo "evidence collected in evidence/"
+36
View File
@@ -0,0 +1,36 @@
# Windows PowerShell 5.1+ version of scripts/init-secrets.sh.
# Creates local synthetic secrets in secrets\ and .env (both git-ignored).
# Idempotent: existing files are NOT overwritten. Values are never printed.
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
New-Item -ItemType Directory -Force -Path (Join-Path $root 'secrets'), (Join-Path $root 'backups') | Out-Null
$ascii = New-Object System.Text.ASCIIEncoding
function New-Hex {
$bytes = New-Object byte[] 24
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
($bytes | ForEach-Object { $_.ToString('x2') }) -join ''
}
function Set-SecretFile([string]$name, [string]$value) {
$path = Join-Path (Join-Path $root 'secrets') $name
if (-not (Test-Path $path)) {
# No BOM, no trailing CR/LF: the value is read verbatim inside Linux containers.
[System.IO.File]::WriteAllText($path, $value, $ascii)
}
}
function Get-SecretFile([string]$name) {
([System.IO.File]::ReadAllText((Join-Path (Join-Path $root 'secrets') $name))).Trim()
}
Set-SecretFile 'postgres_password' (New-Hex)
Set-SecretFile 'redis_password' (New-Hex)
$pg = Get-SecretFile 'postgres_password'
$rd = Get-SecretFile 'redis_password'
Set-SecretFile 'database_url' ("postgresql://messenger:" + $pg + "@postgres:5432/messenger")
Set-SecretFile 'cache_url' ("redis://:" + $rd + "@redis:6379/0")
if (-not (Test-Path (Join-Path $root '.env'))) {
Copy-Item (Join-Path $root '.env.example') (Join-Path $root '.env')
}
Write-Output 'secrets\ and .env are ready (values not shown).'
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Создаёт локальные синтетические secrets для стенда (каталог secrets/ в .gitignore).
# Идемпотентно: существующие файлы НЕ перезаписываются (иначе пароль разойдётся с уже
# инициализированным volume PostgreSQL). Значения не печатаются.
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets backups
chmod 700 secrets
gen() { python3 -c 'import secrets; print(secrets.token_hex(24))'; }
if [ ! -f secrets/postgres_password ]; then gen > secrets/postgres_password; fi
if [ ! -f secrets/redis_password ]; then gen > secrets/redis_password; fi
PG=$(cat secrets/postgres_password)
RD=$(cat secrets/redis_password)
[ -f secrets/database_url ] || printf 'postgresql://messenger:%s@postgres:5432/messenger\n' "$PG" > secrets/database_url
[ -f secrets/cache_url ] || printf 'redis://:%s@redis:6379/0\n' "$RD" > secrets/cache_url
# Файлы монтируются в контейнеры как /run/secrets/*; процесс API работает под uid 10001,
# поэтому файл должен быть читаем внутри контейнера. Каталог secrets/ закрыт (700) на хосте.
chmod 644 secrets/*
[ -f .env ] || cp .env.example .env
echo "secrets/ and .env are ready (values not shown)."
+19
View File
@@ -0,0 +1,19 @@
# Общие функции хуков (POSIX sh). Подключается: . "$(dirname "$0")/lib.sh"
cd "$(dirname "$0")/.."
ENV_FILE=${ENV_FILE:-.env}
dc() { docker compose --env-file "$ENV_FILE" "$@"; }
now() { date -u +%FT%TZ; }
# Состояние всех контейнеров проекта: сервис, имя, статус, StartedAt, PID, alias реплики API.
state() {
for cid in $(dc ps -a -q); do
docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' "$cid" |
sed 's# /# #'
done | sort
}
# Контейнер API-реплики по её X-Instance-Id (alias пишется репликой в /tmp/instance-id).
container_of() {
for cid in $(dc ps -q api); do
if [ "$(docker exec "$cid" cat /tmp/instance-id 2>/dev/null)" = "$1" ]; then echo "$cid"; return 0; fi
done
return 1
}
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
exit /b %ERRORLEVEL%
+31
View File
@@ -0,0 +1,31 @@
# Windows PowerShell version of scripts/restart.sh (persistence hook): restart LB, ALL API replicas,
# PostgreSQL and Redis keeping volumes. State before/after -> evidence\restart-hook.txt
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
$log = Join-Path $root 'evidence\restart-hook.txt'
function Dc { & docker compose --env-file $envFile @args 2>$null | Out-Null; if ($LASTEXITCODE -ne 0) { throw ('docker compose ' + ($args -join ' ') + ' failed') } }
function Get-State {
foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) {
& docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid
}
& docker volume ls --format 'volume {{.Name}}' | Where-Object { $_ -match 'pgdata' }
}
try {
Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' before restart')
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
$ttl = @(& docker compose --env-file $envFile ps -q api-ttl 2>$null).Count -gt 0
Dc stop lb api
if ($ttl) { Dc stop api-ttl }
Dc restart postgres redis
Dc start api
if ($ttl) { Dc start api-ttl }
Dc start lb
Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' after restart')
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
exit 0
} catch {
[Console]::Error.WriteLine($_.Exception.Message)
exit 1
}
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Persistence hook: перезапускает LB, ВСЕ API-реплики и все хранилища (PostgreSQL, Redis),
# сохраняя volumes. Никаких down -v / FLUSH / повторного seed. Миграции повторно не нужны.
# Состояние контейнеров до/после (StartedAt, PID) — в evidence/restart-hook.txt.
set -eu
. "$(dirname "$0")/lib.sh"
LOG=${RESTART_EVIDENCE:-evidence/restart-hook.txt}
{ echo "== $(now) before restart"; state; docker volume ls --format 'volume {{.Name}}' | grep pgdata; } >> "$LOG"
running_ttl=$(dc ps -q api-ttl 2>/dev/null || true)
dc stop lb api >/dev/null 2>&1
[ -z "$running_ttl" ] || dc stop api-ttl >/dev/null 2>&1
dc restart postgres redis >/dev/null 2>&1
dc start api >/dev/null 2>&1
[ -z "$running_ttl" ] || dc start api-ttl >/dev/null 2>&1
dc start lb >/dev/null 2>&1
{ echo "== $(now) after restart"; state; docker volume ls --format 'volume {{.Name}}' | grep pgdata; } >> "$LOG"
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Rolling update API-реплик без остановки сервиса (Compose).
# 1. собрать новый образ (старые контейнеры продолжают работать на старом image id);
# 2. применить миграции ОДИН раз (one-shot migrate). Миграции обязаны быть expand-only
# (совместимы с работающей версией), см. REPORT.md;
# 3. для каждой старой реплики: поднять одну новую (--scale N+1 --no-recreate), дождаться
# healthy, затем остановить старую через SIGTERM (drain 3 с, LB выводит её) и удалить.
# Число готовых реплик во время замены не опускается ниже N. Журнал — evidence/rolling-update.txt.
set -eu
. "$(dirname "$0")/lib.sh"
LOG=${ROLLING_EVIDENCE:-evidence/rolling-update.txt}
VERSION=${APP_VERSION:-$(date -u +%Y%m%d%H%M%S)}
BUILD_CMD=${BUILD_CMD:-"docker compose --env-file $ENV_FILE build --build-arg APP_VERSION=$VERSION api"}
wait_healthy() { # $1 = container id
i=0
while [ "$(docker inspect -f '{{.State.Health.Status}}' "$1")" != healthy ]; do
i=$((i + 1)); [ $i -le 120 ] || { echo "replica $1 not healthy" >&2; return 1; }
sleep 0.5
done
}
old=$(dc ps -q api)
n=$(echo "$old" | wc -w)
{ echo "== $(now) rolling update start: $n replicas, new version $VERSION"; for c in $old; do docker inspect -f 'old {{.Name}} image={{.Image}}' "$c"; done; } >> "$LOG"
$BUILD_CMD >/dev/null
dc run --rm --no-deps migrate >> "$LOG" 2>&1
for c in $old; do
before=$(dc ps -q api)
dc up -d --no-deps --no-recreate --scale api=$((n + 1)) api >/dev/null 2>&1
new=$(for x in $(dc ps -q api); do echo "$before" | grep -q "$x" || echo "$x"; done)
wait_healthy "$new"
echo "$(now) new $(docker inspect -f '{{.Name}} image={{.Image}}' "$new") healthy; stopping old $(docker inspect -f '{{.Name}}' "$c")" >> "$LOG"
docker stop -t 15 "$c" >/dev/null
docker rm "$c" >/dev/null
done
{ echo "== $(now) rolling update done"; for c in $(dc ps -q api); do docker inspect -f 'now {{.Name}} image={{.Image}} health={{.State.Health.Status}}' "$c"; done; } >> "$LOG"
+14
View File
@@ -0,0 +1,14 @@
# Windows PowerShell version of scripts/start-replicas.sh: start stopped API replicas, wait for healthy.
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
$ids = @(& docker compose --env-file $envFile ps -a -q api)
foreach ($cid in $ids) { & docker start $cid | Out-Null }
for ($i = 0; $i -lt 120; $i++) {
$bad = @($ids | Where-Object { (& docker inspect -f '{{.State.Health.Status}}' $_) -ne 'healthy' }).Count
if ($bad -eq 0) { break }
Start-Sleep -Milliseconds 500
}
foreach ($cid in $ids) { & docker inspect -f '{{.Name}} {{.State.Status}} {{.State.Health.Status}}' $cid }
if ($bad -ne 0) { exit 1 }
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Восстанавливает остановленные API-реплики (после stop-one) и ждёт их healthcheck (≤60 с).
set -eu
. "$(dirname "$0")/lib.sh"
for cid in $(dc ps -a -q api); do docker start "$cid" >/dev/null; done
i=0
while [ $i -lt 120 ]; do
bad=0
for cid in $(dc ps -a -q api); do
[ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || bad=1
done
[ $bad -eq 0 ] && break
i=$((i + 1)); sleep 0.5
done
state | grep '^api '
[ $bad -eq 0 ]
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1"
exit /b %ERRORLEVEL%
+30
View File
@@ -0,0 +1,30 @@
# Windows PowerShell version of scripts/stop-one.sh (failover hook). Stops EXACTLY ONE API replica whose
# X-Instance-Id is in $env:TARGET_INSTANCE_ID and leaves it stopped. DB/Redis/LB/volumes untouched.
# Restore afterwards: scripts\start-replicas.ps1
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
$log = Join-Path $root 'evidence\failover-hook.txt'
if (-not $env:TARGET_INSTANCE_ID) { [Console]::Error.WriteLine('TARGET_INSTANCE_ID is required'); exit 2 }
function Get-State {
foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) {
& docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid
}
}
$target = $null
foreach ($cid in (& docker compose --env-file $envFile ps -q api)) {
$id = (& docker exec $cid cat /tmp/instance-id 2>$null)
if ($id -and $id.Trim() -eq $env:TARGET_INSTANCE_ID) { $target = $cid }
}
if (-not $target) { [Console]::Error.WriteLine('no running api replica with this id'); exit 1 }
$name = (& docker inspect -f '{{.Name}}' $target).TrimStart('/')
$stamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
Add-Content -Path $log -Encoding UTF8 -Value ("== $stamp stop-one target=" + $env:TARGET_INSTANCE_ID + " container=$name")
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
& docker stop -t 15 $target | Out-Null
if ($LASTEXITCODE -ne 0) { exit 1 }
$stamp = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
Add-Content -Path $log -Encoding UTF8 -Value ("== $stamp after stop")
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
exit 0
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Failover hook: останавливает РОВНО ОДНУ API-реплику — ту, чей X-Instance-Id передан тестом в
# TARGET_INSTANCE_ID, — и оставляет её остановленной. БД, Redis, LB и volumes не трогает.
# docker stop → SIGTERM → реплика 3 с отвечает 503 на /health/ready (LB выводит её), затем закрывает
# listener и дожидается запросов в полёте. Возврат ≈ 4 с (< 10 с). Восстановление: scripts/start-replicas.sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
. "$(dirname "$0")/lib.sh"
LOG=${FAILOVER_EVIDENCE:-evidence/failover-hook.txt}
cid=$(container_of "$TARGET_INSTANCE_ID") || { echo "no running api replica with id $TARGET_INSTANCE_ID" >&2; exit 1; }
name=$(docker inspect -f '{{.Name}}' "$cid" | tr -d /)
{ echo "== $(now) stop-one target=$TARGET_INSTANCE_ID container=$name"; state; } >> "$LOG"
docker stop -t 15 "$cid" >/dev/null
{ echo "== $(now) after stop"; state; } >> "$LOG"