ЛР 6 — БВТ2302 — Лебедев — на 5

This commit is contained in:
2026-11-22 23:19:26 +03:00
parent 470d9d6f1e
commit 90508e41e9
148 changed files with 19332 additions and 16 deletions
+140
View File
@@ -0,0 +1,140 @@
# Windows PowerShell 5.1+ equivalent of scripts/collect-evidence.sh (lab6).
# Starts the Compose stand (LB + API replicas + workers + one-shot bootstrap + PostgreSQL + Redis + SeaweedFS S3 +
# NATS JetStream + OTel Collector + Prometheus + Loki + Tempo + Grafana), runs every check and writes outputs to
# evidence\ (no tokens/passwords/keys). Stops/restarts containers (worker, DB, Collector, Tempo, Loki, API
# replicas); volumes are never removed. Takes ~90 minutes (-SkipRegression: ~60, -SkipResearch: -35 more).
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 [-SkipRegression] [-SkipResearch]
param([switch]$SkipRegression, [switch]$SkipResearch)
$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, (Join-Path $ev 'track1'), (Join-Path $ev 'track2'), (Join-Path $ev 'incidents') | 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' }
$mount = (Join-Path $root 'student-tests') + ':/app/student-tests:ro'
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 'migrations' 'schema_migrations; docker compose logs migrate' {
Dc exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'
Dc logs --no-log-prefix migrate
}
Invoke-Step 'broker-bootstrap' 'docker compose logs broker-init' { Dc logs --no-log-prefix broker-init }
Invoke-Step 's3-bootstrap' 'docker compose logs s3-init' { Dc logs --no-log-prefix s3-init }
Invoke-Step 'no-local-files' 'docker inspect api/worker: ReadonlyRootfs, tmpfs, mounts' {
foreach ($cid in @(Dc ps -q api worker)) {
& docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' $cid
}
}
Invoke-Step 'published-ports' 'docker compose ps: published ports' { Dc ps --format '{{.Service}} {{.Ports}}' | Sort-Object -Unique }
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 }
# ---------------------------------------------------------------- lab6: observability
Invoke-Step 'collector-config-validate' 'otelcol-contrib validate --config=collector.yaml' {
Dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml
}
Invoke-Step 'test-observability' 'python student-tests/test_observability.py' { Invoke-Python student-tests/test_observability.py }
Invoke-Step 'observability' 'python research/obs_snapshot.py' { Invoke-Python research/obs_snapshot.py }
Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Encoding UTF8 -Value @()
Invoke-Step 'test-telemetry-persistence' 'python student-tests/test_telemetry_persistence.py # restarts everything' {
Invoke-Python student-tests/test_telemetry_persistence.py
}
foreach ($sc in 'worker-stop', 'db-slow', 'handler-slow', 'db-down', 'telemetry-down', 'collector-down') {
Invoke-Step ('incident-' + $sc) ('python research/incidents.py ' + $sc) {
Invoke-Python research/incidents.py $sc --out evidence/incidents
}
}
# ---------------------------------------------------------------- public failover / persistence checks
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
}
# ---------------------------------------------------------------- lab2-lab5 regression with telemetry enabled
if (-not $SkipRegression) {
Invoke-Step 'test-pipeline' 'python student-tests/test_pipeline.py' { Invoke-Python student-tests/test_pipeline.py }
Invoke-Step 'test-imgproc' 'docker compose run worker: python student-tests/test_imgproc.py' {
Dc run --rm --no-deps -T -v $mount --entrypoint python worker student-tests/test_imgproc.py
}
Invoke-Step 'defense-demo' 'python student-tests/defense_demo.py' { Invoke-Python student-tests/defense_demo.py }
Invoke-Step 'test-attachments' 'python student-tests/test_attachments.py' { Invoke-Python student-tests/test_attachments.py }
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 $mount --entrypoint python api student-tests/test_cache_race.py
}
Invoke-Step 'test-jobs-failures' 'python student-tests/test_jobs_failures.py' { Invoke-Python student-tests/test_jobs_failures.py }
Invoke-Step 'test-storage-failures' 'python student-tests/test_storage_failures.py' { Invoke-Python student-tests/test_storage_failures.py }
Invoke-Step 'test-failures' 'python student-tests/test_failures.py' { Invoke-Python student-tests/test_failures.py }
Invoke-Step 'test-track2-lab5' 'python student-tests/test_pipeline_idempotency.py' { Invoke-Python student-tests/test_pipeline_idempotency.py }
Invoke-Step 'track2-chaos-seed1' 'python research/track2_chaos.py --seed 1' {
Invoke-Python research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json
}
}
# ---------------------------------------------------------------- track 1
if (-not $SkipResearch) {
Invoke-Step 'track1-telemetry-cost' 'python research/telemetry_cost.py --reps 3 --rate 60 --window 60' {
Invoke-Python research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
}
}
Invoke-Step 'jobs-failed' 'docker compose exec api python -m messenger jobs failed --limit 20' { Dc exec -T api python -m messenger jobs failed --limit 20 }
Invoke-Step 'jobs-invariants' 'docker compose exec api python -m messenger jobs invariants --settled --verify-bytes' {
Dc exec -T api python -m messenger jobs invariants --settled --verify-bytes
}
Invoke-Step 'migrations-rerun' 'docker compose run --rm --no-deps migrate' { Dc run --rm --no-deps migrate }
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
}
Invoke-Step 'test-observability-final' 'python student-tests/test_observability.py' { Invoke-Python student-tests/test_observability.py }
Invoke-Step 'observability-final' 'python research/obs_snapshot.py' { Invoke-Python research/obs_snapshot.py }
Write-Host 'Done: evidence collected in evidence\' -ForegroundColor Green
+71
View File
@@ -0,0 +1,71 @@
#!/bin/sh
# Полный прогон доказательств lab6 на Compose-стенде; вывод — evidence/ (без токенов, паролей и ключей).
# Останавливает/перезапускает контейнеры стенда (worker, БД, Collector, Tempo, Loki, реплики API …).
# Volumes не удаляются. Длительность ≈ 90 мин; SKIP_REGRESSION=1 (без тестов lab2–lab5) — ≈ 60 мин,
# SKIP_RESEARCH=1 (без трека 1) — ещё −35 мин.
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} NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost
mkdir -p evidence evidence/incidents evidence/track1 evidence/track2
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"; }
IN_WORKER="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python worker"
IN_API="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python api"
./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 -a; state; } > evidence/stack.txt 2>&1
run migrations sh -c "docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'; docker compose --env-file .env logs --no-log-prefix migrate"
run broker-bootstrap dc logs --no-log-prefix broker-init
run s3-bootstrap dc logs --no-log-prefix s3-init
run no-local-files sh -c "for c in \$(docker compose --env-file .env ps -q api worker); do docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' \$c; done"
run published-ports sh -c "docker compose --env-file .env ps --format '{{.Service}} {{.Ports}}' | sort -u"
run make-check make check
run smoke $PY tests/smoke.py --base-url "$B"
# ---------------------------------------------------------------- lab6: наблюдаемость
run collector-config-validate dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml
run test-observability $PY student-tests/test_observability.py
run observability $PY research/obs_snapshot.py
: > evidence/restart-hook.txt
run test-telemetry-persistence $PY student-tests/test_telemetry_persistence.py
for s in worker-stop db-slow handler-slow db-down telemetry-down collector-down; do
run incident-$s $PY research/incidents.py $s --out evidence/incidents
done
# ---------------------------------------------------------------- публичные проверки отказа и сохранности
: > 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"
# ---------------------------------------------------------------- регрессия lab2–lab5 (make test при включённой telemetry)
if [ "${SKIP_REGRESSION:-0}" != 1 ]; then
run test-pipeline $PY student-tests/test_pipeline.py
run test-imgproc $IN_WORKER student-tests/test_imgproc.py
run defense-demo $PY student-tests/defense_demo.py
run test-attachments $PY student-tests/test_attachments.py
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 $IN_API student-tests/test_cache_race.py
run test-jobs-failures $PY student-tests/test_jobs_failures.py
run test-storage-failures $PY student-tests/test_storage_failures.py
run test-failures $PY student-tests/test_failures.py
run test-track2-lab5 $PY student-tests/test_pipeline_idempotency.py
run track2-chaos-seed1 $PY research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json
fi
# ---------------------------------------------------------------- трек 1
if [ "${SKIP_RESEARCH:-0}" != 1 ]; then
run track1-telemetry-cost $PY research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
fi
run jobs-failed dc exec -T api python -m messenger jobs failed --limit 20
run jobs-invariants dc exec -T api python -m messenger jobs invariants --settled --verify-bytes
run migrations-rerun dc run --rm --no-deps migrate
run load $PY tests/load.py --base-url "$B" --duration 30 --concurrency 4 --output evidence/load.json
run test-observability-final $PY student-tests/test_observability.py
run observability-final $PY research/obs_snapshot.py
echo "evidence collected in evidence/"
+88
View File
@@ -0,0 +1,88 @@
# 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")
# S3 (SeaweedFS): two identities. admin - only for bucket bootstrap (s3-init service);
# messenger-api - Read/Write/List ONLY on the attachments bucket (cannot create/delete buckets).
function New-KeyId {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
$bytes = New-Object byte[] 20
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
($bytes | ForEach-Object { $chars[$_ % $chars.Length] }) -join ''
}
Set-SecretFile 's3_admin_access_key_id' (New-KeyId)
Set-SecretFile 's3_admin_secret_access_key' (New-Hex)
Set-SecretFile 's3_access_key_id' (New-KeyId)
Set-SecretFile 's3_secret_access_key' (New-Hex)
$bucket = 'messenger-attachments'
$envPath = Join-Path $root '.env'
if (Test-Path $envPath) {
$line = Select-String -Path $envPath -Pattern '^S3_BUCKET=(.+)$' | Select-Object -First 1
if ($line) { $bucket = $line.Matches[0].Groups[1].Value.Trim() }
}
$cfgPath = Join-Path (Join-Path $root 'secrets') 's3_config.json'
if (-not (Test-Path $cfgPath)) {
$cfg = [ordered]@{ identities = @(
[ordered]@{ name = 'admin'; credentials = @([ordered]@{ accessKey = (Get-SecretFile 's3_admin_access_key_id'); secretKey = (Get-SecretFile 's3_admin_secret_access_key') });
actions = @('Admin', 'Read', 'List', 'Tagging', 'Write') },
[ordered]@{ name = 'messenger-api'; credentials = @([ordered]@{ accessKey = (Get-SecretFile 's3_access_key_id'); secretKey = (Get-SecretFile 's3_secret_access_key') });
actions = @(('Read:' + $bucket), ('Write:' + $bucket), ('List:' + $bucket)) }
) }
[System.IO.File]::WriteAllText($cfgPath, ($cfg | ConvertTo-Json -Depth 6), $ascii)
}
# NATS JetStream: service password (API, worker, bootstrap) and the server config that holds it.
Set-SecretFile 'nats_password' (New-Hex)
$np = Get-SecretFile 'nats_password'
Set-SecretFile 'broker_url' ('nats://messenger:' + $np + '@nats:4222')
$natsConf = @(
'# nats-server (lab5): JetStream on disk with fsync on every write, password auth,',
'# monitoring (healthcheck) only on 127.0.0.1 inside the container.',
'server_name: nats-lab6',
'listen: "0.0.0.0:4222"',
'http: "127.0.0.1:8222"',
'max_payload: 65536',
'jetstream {',
' store_dir: "/data"',
' max_memory_store: 64MB',
' max_file_store: 2GB',
' sync_interval: always',
'}',
'authorization {',
(' users = [ { user: "messenger", password: "' + $np + '" } ]'),
'}'
) -join "`n"
Set-SecretFile 'nats.conf' ($natsConf + "`n")
# lab6: Grafana admin password (UI on 127.0.0.1:3000; tests read it locally and never print it).
Set-SecretFile 'grafana_admin_password' (New-Hex)
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).'
+63
View File
@@ -0,0 +1,63 @@
#!/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
# S3 (SeaweedFS): две identity. admin — только для bootstrap bucket (сервис s3-init);
# api — права Read/Write/List ТОЛЬКО на bucket вложений (не может создавать/удалять бакеты).
keyid() { python3 -c 'import secrets,string; print("".join(secrets.choice(string.ascii_uppercase+string.digits) for _ in range(20)))'; }
[ -f secrets/s3_admin_access_key_id ] || keyid > secrets/s3_admin_access_key_id
[ -f secrets/s3_admin_secret_access_key ] || gen > secrets/s3_admin_secret_access_key
[ -f secrets/s3_access_key_id ] || keyid > secrets/s3_access_key_id
[ -f secrets/s3_secret_access_key ] || gen > secrets/s3_secret_access_key
BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | cut -d= -f2); BUCKET=${BUCKET:-messenger-attachments}
[ -f secrets/s3_config.json ] || python3 - "$BUCKET" > secrets/s3_config.json <<'PY'
import json, sys
b = sys.argv[1]
r = lambda n: open("secrets/" + n).read().strip()
print(json.dumps({"identities": [
{"name": "admin", "credentials": [{"accessKey": r("s3_admin_access_key_id"), "secretKey": r("s3_admin_secret_access_key")}],
"actions": ["Admin", "Read", "List", "Tagging", "Write"]},
{"name": "messenger-api", "credentials": [{"accessKey": r("s3_access_key_id"), "secretKey": r("s3_secret_access_key")}],
"actions": ["Read:" + b, "Write:" + b, "List:" + b]}]}, indent=1))
PY
# NATS JetStream: пароль сервисов (API, worker, bootstrap) и конфигурация сервера с ним.
[ -f secrets/nats_password ] || gen > secrets/nats_password
NP=$(cat secrets/nats_password)
[ -f secrets/broker_url ] || printf 'nats://messenger:%s@nats:4222\n' "$NP" > secrets/broker_url
[ -f secrets/nats.conf ] || cat > secrets/nats.conf <<NATS
# nats-server (lab5+): JetStream на диске с fsync каждой записи, доступ по паролю,
# мониторинг (healthcheck) — только 127.0.0.1 внутри контейнера.
server_name: nats-lab6
listen: "0.0.0.0:4222"
http: "127.0.0.1:8222"
max_payload: 65536
jetstream {
store_dir: "/data"
max_memory_store: 64MB
max_file_store: 2GB
sync_interval: always
}
authorization {
users = [ { user: "messenger", password: "$NP" } ]
}
NATS
# lab6: пароль admin Grafana (вход в UI на 127.0.0.1:3000; тесты читают его локально, не печатая).
[ -f secrets/grafana_admin_password ] || gen > secrets/grafana_admin_password
# Файлы монтируются в контейнеры как /run/secrets/*; процесс API работает под uid 10001,
# поэтому файл должен быть читаем внутри контейнера. Каталог secrets/ закрыт (700) на хосте.
chmod 644 secrets/*
[ -f .env ] || cp .env.example .env
mkdir -p backups
echo "secrets/ and .env are ready (values not shown)."
+26
View File
@@ -0,0 +1,26 @@
# Общие функции хуков (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
}
# Ждать healthy у всех контейнеров сервиса (не дольше 60 с).
wait_healthy() {
for cid in $(dc ps -q "$1"); do
i=0
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || [ $i -ge 120 ]; do i=$((i + 1)); sleep 0.5; done
done
}
+18
View File
@@ -0,0 +1,18 @@
# Defense scenario step 3: restart NATS (volume natsdata kept) and all API replicas; workers are NOT started.
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
function Wait-Healthy([string]$svc) {
foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) {
for ($i = 0; $i -lt 120; $i++) {
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
Start-Sleep -Milliseconds 500
}
}
}
& docker compose --env-file $envFile restart nats 2>$null | Out-Null
Wait-Healthy 'nats'
& docker compose --env-file $envFile restart api 2>$null | Out-Null
Wait-Healthy 'api'
& docker compose --env-file $envFile ps -a nats api --format '{{.Name}} {{.State}} {{.Health}}'
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
# Сценарий защиты, шаг 3: перезапустить брокер (NATS, volume natsdata сохраняется) и все реплики API.
# Worker НЕ запускает (если остановлены — остаются остановленными). Volumes не удаляются.
set -eu
. "$(dirname "$0")/lib.sh"
{ echo "== $(now) before"; state; } | grep -E '^(==|nats|api) '
dc restart nats >/dev/null 2>&1
wait_healthy nats
dc restart api >/dev/null 2>&1
wait_healthy api
{ echo "== $(now) after"; state; } | grep -E '^(==|nats|api) '
+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%
+41
View File
@@ -0,0 +1,41 @@
# Windows PowerShell version of scripts/restart.sh (persistence hook): restart LB, ALL API replicas, workers,
# PostgreSQL, Redis, S3, NATS JetStream and observability (Collector, Prometheus, Loki, Tempo, Grafana) 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 --filter label=com.docker.compose.project=mtusi-lab6 --format 'volume {{.Name}}'
}
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
$workers = @(& docker compose --env-file $envFile ps -q worker 2>$null).Count -gt 0
Dc stop lb api worker
if ($ttl) { Dc stop api-ttl }
Dc restart postgres redis s3 nats otel-collector prometheus loki tempo grafana
# Wait for healthy storages (S3: gateway + master leader + writes; NATS: JetStream) before API/worker/LB.
foreach ($svc in 'postgres', 'redis', 's3', 'nats', 'prometheus') {
$cid = (& docker compose --env-file $envFile ps -q $svc | Select-Object -First 1)
for ($i = 0; $i -lt 120; $i++) {
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
Start-Sleep -Milliseconds 500
}
}
Dc start api
if ($ttl) { Dc start api-ttl }
if ($workers) { Dc start worker }
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
}
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Persistence hook: перезапускает LB, ВСЕ API-реплики, worker и все хранилища (PostgreSQL, Redis, S3,
# NATS JetStream) и всю наблюдаемость (Collector, Prometheus, Loki, Tempo, Grafana), сохраняя volumes. Никаких down -v / FLUSH / повторного seed. Миграции повторно не нужны.
# Состояние контейнеров до/после (StartedAt, PID) — в evidence/restart-hook.txt.
set -eu
. "$(dirname "$0")/lib.sh"
LOG=${RESTART_EVIDENCE:-evidence/restart-hook.txt}
vols() { docker volume ls --filter label=com.docker.compose.project=mtusi-lab6 --format 'volume {{.Name}}'; }
{ echo "== $(now) before restart"; state; vols; } >> "$LOG"
running_ttl=$(dc ps -q api-ttl 2>/dev/null || true)
running_worker=$(dc ps -q worker 2>/dev/null || true)
dc stop lb api worker >/dev/null 2>&1
[ -z "$running_ttl" ] || dc stop api-ttl >/dev/null 2>&1
dc restart postgres redis s3 nats otel-collector prometheus loki tempo grafana >/dev/null 2>&1
# Дождаться healthy хранилищ (S3: шлюз + лидер master + запись; NATS: JetStream), затем API/worker/LB.
for svc in postgres redis s3 nats prometheus; do wait_healthy "$svc"; done
dc start api >/dev/null 2>&1
[ -z "$running_ttl" ] || dc start api-ttl >/dev/null 2>&1
[ -z "$running_worker" ] || dc start worker >/dev/null 2>&1
dc start lb >/dev/null 2>&1
{ echo "== $(now) after restart"; state; vols; } >> "$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 ]
+16
View File
@@ -0,0 +1,16 @@
# Start stopped workers and wait until healthy.
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
function Wait-Healthy([string]$svc) {
foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) {
for ($i = 0; $i -lt 120; $i++) {
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
Start-Sleep -Milliseconds 500
}
}
}
& docker compose --env-file $envFile start worker 2>$null | Out-Null
Wait-Healthy 'worker'
& docker compose --env-file $envFile ps -a worker --format '{{.Name}} {{.State}} {{.Health}}'
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Запустить остановленные worker и дождаться healthy.
set -eu
. "$(dirname "$0")/lib.sh"
dc start worker >/dev/null 2>&1
wait_healthy worker
echo "$(now) workers started:"; dc ps -a worker --format '{{.Name}} {{.State}} {{.Health}}'
+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"
+15
View File
@@ -0,0 +1,15 @@
# Defense scenario: stop ALL workers and leave them stopped (API, broker, storages untouched).
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
function Wait-Healthy([string]$svc) {
foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) {
for ($i = 0; $i -lt 120; $i++) {
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
Start-Sleep -Milliseconds 500
}
}
}
& docker compose --env-file $envFile stop worker 2>$null | Out-Null
& docker compose --env-file $envFile ps -a worker --format '{{.Name}} {{.State}}'
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Сценарий защиты: остановить ВСЕ worker (SIGTERM → дорабатывают текущее ≤ 20 с, остальное вернёт брокер)
# и оставить их остановленными. API, брокер, хранилища и volumes не трогает.
set -eu
. "$(dirname "$0")/lib.sh"
dc stop worker >/dev/null 2>&1
echo "$(now) workers stopped:"; dc ps -a worker --format '{{.Name}} {{.State}}'