forked from mtusi2026/mtusi2026lab2
ЛР2: PostgreSQL, сессии, Redis-кэш, трек 5.2
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
# Windows PowerShell 5.1+ equivalent of `make up && ./scripts/collect-evidence.sh`.
|
||||
# Starts the Compose stand, runs every check and writes outputs to evidence\ (no tokens/passwords).
|
||||
# Run from the repo root:
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1
|
||||
# Optional: -SkipResearch (skip track 5.2), -SkipFailures (do not stop redis/postgres).
|
||||
param([switch]$SkipResearch, [switch]$SkipFailures)
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONIOENCODING = 'utf-8'
|
||||
$ev = Join-Path $root 'evidence'
|
||||
New-Item -ItemType Directory -Force -Path $ev | Out-Null
|
||||
|
||||
if (Get-Command py -ErrorAction SilentlyContinue) { $script:PyExe = 'py'; $script:PyPre = @('-3') }
|
||||
elseif (Get-Command python -ErrorAction SilentlyContinue) { $script:PyExe = 'python'; $script:PyPre = @() }
|
||||
else { throw 'Python 3.9+ not found (install from python.org, enable "Add to PATH")' }
|
||||
function Py { & $script:PyExe @script:PyPre @args }
|
||||
function Dc { & docker compose --env-file .env @args }
|
||||
|
||||
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
|
||||
$content = @((Get-Stamp), ('$ ' + $title)) + $lines + @('exit=' + $code)
|
||||
Set-Content -Path (Join-Path $ev ($name + '.txt')) -Encoding UTF8 -Value $content
|
||||
$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; docker compose version; images; ps' {
|
||||
& docker version --format 'docker {{.Server.Version}}'; Dc version; Dc --profile ttl images; Dc --profile ttl ps
|
||||
}
|
||||
Invoke-Step 'make-check' 'python scripts/check_contract.py' { Py scripts/check_contract.py }
|
||||
Invoke-Step 'smoke' 'python tests/smoke.py --base-url http://localhost:8080' { Py tests/smoke.py --base-url http://localhost:8080 }
|
||||
Invoke-Step 'test-api' 'python student-tests/test_api.py' { Py student-tests/test_api.py }
|
||||
Invoke-Step 'test-expiry' 'python student-tests/test_expiry.py # api-ttl, SESSION_TTL_SECONDS=2' { Py student-tests/test_expiry.py }
|
||||
Invoke-Step 'test-cache-race' 'docker compose run --rm --no-deps 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 'restart-hook.txt') -Encoding UTF8 -Value @()
|
||||
# Windows: .cmd wrapper around restart.ps1; pwsh on Linux/macOS: the POSIX hook.
|
||||
$hook = if ($IsLinux -or $IsMacOS) { 'scripts/restart.sh' } else { 'scripts\restart.cmd' }
|
||||
Invoke-Step 'persistence' ('python tests/resilience.py --mode persistence --action-script ' + $hook) {
|
||||
Py tests/resilience.py --mode persistence --action-script $hook --base-url http://localhost:8080
|
||||
}
|
||||
if (-not $SkipFailures) {
|
||||
Invoke-Step 'test-failures' 'python student-tests/test_failures.py # stops/starts redis and postgres' { Py student-tests/test_failures.py }
|
||||
}
|
||||
Invoke-Step 'migrations-rerun' 'docker compose exec -T api python -m messenger migrate' { Dc exec -T api python -m messenger migrate }
|
||||
Invoke-Step 'load' 'python tests/load.py --duration 30 --concurrency 4 --output evidence/load.json' {
|
||||
Py tests/load.py --base-url http://localhost:8080 --duration 30 --concurrency 4 --output evidence/load.json
|
||||
}
|
||||
$race = @(Dc logs --no-color api 2>$null | Select-String -SimpleMatch 'registration race resolved').Count
|
||||
Set-Content -Path (Join-Path $ev 'race-unique-violations.txt') -Encoding ASCII -Value $race
|
||||
if (-not $SkipResearch) {
|
||||
Dc --profile research up -d --wait postgres-restore
|
||||
Invoke-Step 'track2' 'python research/track2.py' { Py research/track2.py }
|
||||
}
|
||||
Write-Host 'Done: evidence collected in evidence\' -ForegroundColor Green
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Полный прогон доказательств на Compose-стенде; вывод — в evidence/ (без токенов и паролей).
|
||||
# Предусловие: make up (стенд запущен). Тест отказов и restart-hook перезапускают контейнеры.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
dc() { docker compose --env-file .env "$@"; }
|
||||
mkdir -p evidence
|
||||
stamp() { echo "# $(date -u +%FT%TZ) commit=$(git rev-parse --short HEAD 2>/dev/null || echo n/a) host=$(uname -srm)"; }
|
||||
run() { name=$1; shift; { stamp; echo "\$ $*"; "$@" 2>&1; echo "exit=$?"; } > "evidence/$name.txt" || true; tail -3 "evidence/$name.txt"; }
|
||||
|
||||
dc --profile ttl up -d --build --wait
|
||||
{ stamp; docker version --format 'docker {{.Server.Version}}'; dc version; dc --profile ttl images; dc --profile ttl ps; } > evidence/stack.txt 2>&1
|
||||
run make-check make check
|
||||
run smoke make test
|
||||
run test-api python3 student-tests/test_api.py
|
||||
run test-expiry python3 student-tests/test_expiry.py
|
||||
run test-cache-race make test-cache-race
|
||||
: > evidence/restart-hook.txt
|
||||
run persistence make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
run test-failures python3 student-tests/test_failures.py
|
||||
run migrations-rerun dc exec -T api python -m messenger migrate
|
||||
run load python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
|
||||
dc logs --no-color api 2>/dev/null | grep -c 'registration race resolved' > evidence/race-unique-violations.txt || true
|
||||
dc --profile research up -d --wait postgres-restore
|
||||
run track2 python3 research/track2.py
|
||||
echo "evidence collected in evidence/"
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# Сбор доказательств на НАТИВНОМ стенде (PostgreSQL 16 + Redis 7 + API как процессы ОС).
|
||||
# Использовался в среде без доступа к Docker Hub; для сдачи предпочтителен scripts/collect-evidence.sh.
|
||||
# Ожидает: кластеры /srv/stand/pg (5432) и /srv/stand/pg-restore (5433), Redis 6379, API 8080/8081.
|
||||
set -u
|
||||
cd "$(dirname "$0")/../.."
|
||||
N=scripts/dev/native-ctl.sh
|
||||
export PGPASSWORD=${PGPASSWORD:-$(cat /srv/stand/secrets/pg_password)}
|
||||
export PSQL="psql -h 127.0.0.1 -U messenger -d messenger"
|
||||
export STOP_DB="$N stop db" START_DB="$N start db" STOP_CACHE="$N stop cache" START_CACHE="$N start cache"
|
||||
export SRC_PSQL="psql -h 127.0.0.1 -p 5432 -U messenger" SRC_PG_DUMP="pg_dump -h 127.0.0.1 -p 5432 -U messenger"
|
||||
export DST_PSQL="psql -h 127.0.0.1 -p 5433 -U messenger" DST_PG_RESTORE="pg_restore -h 127.0.0.1 -p 5433 -U messenger"
|
||||
export DUMP_PATH=/srv/stand/backups/research.dump DUMP_HOST_PATH=/srv/stand/backups/research.dump
|
||||
stamp() { echo "# $(date -u +%FT%TZ) native stand; $(uname -srm); nproc=$(nproc); mem=$(free -m | awk '/Mem/{print $2}')MiB"; }
|
||||
run() { name=$1; shift; { stamp; echo "\$ $*"; "$@" 2>&1; echo "exit=$?"; } > "evidence/$name.txt"; tail -2 "evidence/$name.txt"; }
|
||||
mkdir -p evidence
|
||||
run make-check make check
|
||||
run smoke make test
|
||||
run test-api python3 student-tests/test_api.py
|
||||
grep -c 'registration race resolved' /srv/stand/api.log > evidence/race-unique-violations.txt
|
||||
run test-expiry python3 student-tests/test_expiry.py
|
||||
: > /srv/stand/restart-evidence.log
|
||||
run persistence make test-persistence ACTION_SCRIPT=scripts/dev/restart-native.sh
|
||||
cp /srv/stand/restart-evidence.log evidence/restart-hook.txt
|
||||
run test-failures python3 student-tests/test_failures.py
|
||||
run load python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
# Управление нативным стендом (без Docker): native-ctl.sh stop|start db|cache|api|api-ttl
|
||||
set -eu
|
||||
STAND=${STAND:-/srv/stand}
|
||||
RPW=$(cat "$STAND/secrets/redis_password") # синтетический пароль стенда, вне репозитория
|
||||
case "$1:$2" in
|
||||
stop:db) su postgres -c "/usr/lib/postgresql/16/bin/pg_ctl -D $STAND/pg -m fast -w stop" >/dev/null ;;
|
||||
start:db) su postgres -c "/usr/lib/postgresql/16/bin/pg_ctl -D $STAND/pg -w start -l $STAND/pg.log -o '-p 5432 -k /run/postgresql'" >/dev/null ;;
|
||||
stop:cache) redis-cli -a "$RPW" --no-auth-warning shutdown nosave >/dev/null 2>&1 || true ;;
|
||||
start:cache) redis-server --port 6379 --save '' --appendonly no --requirepass "$RPW" --maxmemory 64mb \
|
||||
--maxmemory-policy allkeys-lru --daemonize yes --dir "$STAND/redis" --logfile "$STAND/redis.log" ;;
|
||||
stop:api|stop:api-ttl) kill "$(cat "$STAND/$2.pid")"; while kill -0 "$(cat "$STAND/$2.pid")" 2>/dev/null; do sleep 0.2; done ;;
|
||||
start:api) "$STAND/start-api.sh" api 8080 3600 ;;
|
||||
start:api-ttl) "$STAND/start-api.sh" api-ttl 8081 2 ;;
|
||||
*) echo "usage: $0 stop|start db|cache|api|api-ttl" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# Хук перезапуска для НАТИВНОГО стенда без Docker (как собирались доказательства в среде без
|
||||
# доступа к Docker Hub). Основной хук для сдачи — scripts/restart.sh (Compose).
|
||||
# Перезапускает API, PostgreSQL и Redis, сохраняя каталоги данных. Ничего не удаляет и не seed-ит.
|
||||
set -eu
|
||||
STAND=${STAND:-/srv/stand}
|
||||
RPW=$(cat "$STAND/secrets/redis_password") # синтетический пароль стенда, вне репозитория
|
||||
LOG=${RESTART_EVIDENCE:-$STAND/restart-evidence.log}
|
||||
pids() {
|
||||
printf 'api=%s postgres=%s redis=%s\n' \
|
||||
"$(cat "$STAND/api.pid" 2>/dev/null || echo -)" \
|
||||
"$(head -1 "$STAND/pg/postmaster.pid" 2>/dev/null || echo -)" \
|
||||
"$(redis-cli -a "$RPW" --no-auth-warning info server 2>/dev/null | sed -n 's/^process_id:\(.*\)\r$/\1/p')"
|
||||
}
|
||||
{ printf '%s before: ' "$(date -u +%FT%TZ)"; pids; } >> "$LOG"
|
||||
kill "$(cat "$STAND/api.pid")" 2>/dev/null || true
|
||||
while kill -0 "$(cat "$STAND/api.pid")" 2>/dev/null; do sleep 0.2; done
|
||||
su postgres -c "/usr/lib/postgresql/16/bin/pg_ctl -D $STAND/pg -m fast -w restart -l $STAND/pg.log -o '-p 5432 -k /run/postgresql'" >/dev/null
|
||||
redis-cli -a "$RPW" --no-auth-warning shutdown nosave >/dev/null 2>&1 || true
|
||||
sleep 0.3
|
||||
redis-server --port 6379 --save '' --appendonly no --requirepass "$RPW" --maxmemory 64mb \
|
||||
--maxmemory-policy allkeys-lru --daemonize yes --dir "$STAND/redis" --logfile "$STAND/redis.log"
|
||||
"$STAND/start-api.sh" api 8080 3600
|
||||
sleep 0.5
|
||||
{ printf '%s after: ' "$(date -u +%FT%TZ)"; pids; } >> "$LOG"
|
||||
@@ -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).'
|
||||
@@ -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)."
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd files run without a shell.
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,34 @@
|
||||
# Windows PowerShell version of scripts/restart.sh (restart hook for the persistence test).
|
||||
# Restarts API and ALL used stores (PostgreSQL, Redis) keeping volumes. No down -v, no flush, no re-seed.
|
||||
# Container state before/after (StartedAt, PID) is appended to 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 = if ($env:RESTART_EVIDENCE) { $env:RESTART_EVIDENCE } else { Join-Path $root 'evidence\restart-hook.txt' }
|
||||
|
||||
function Invoke-Compose {
|
||||
& docker compose --env-file $envFile @args
|
||||
if ($LASTEXITCODE -ne 0) { throw ('docker compose ' + ($args -join ' ') + ' failed') }
|
||||
}
|
||||
function Get-State {
|
||||
foreach ($svc in 'api', 'postgres', 'redis') {
|
||||
$cid = (& docker compose --env-file $envFile ps -q $svc | Select-Object -First 1)
|
||||
& docker inspect -f ($svc + ' status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}') $cid
|
||||
}
|
||||
& docker volume ls --format '{{.Name}}' | Where-Object { $_ -match 'pgdata$' } | ForEach-Object { 'volume kept: ' + $_ }
|
||||
}
|
||||
|
||||
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)
|
||||
Invoke-Compose stop api
|
||||
Invoke-Compose restart postgres redis
|
||||
Invoke-Compose start api
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
# Restart hook для make test-persistence (Compose).
|
||||
# Перезапускает API и ВСЕ используемые хранилища (PostgreSQL, Redis), сохраняя volumes.
|
||||
# Никаких down -v / FLUSH / повторного seed. Состояние контейнеров до/после (StartedAt, PID)
|
||||
# дописывается в evidence/restart-hook.txt — доказательство, что процессы действительно сменились.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
ENV_FILE=${ENV_FILE:-.env}
|
||||
dc() { docker compose --env-file "$ENV_FILE" "$@"; }
|
||||
LOG=${RESTART_EVIDENCE:-evidence/restart-hook.txt}
|
||||
state() {
|
||||
for svc in api postgres redis; do
|
||||
cid=$(dc ps -q "$svc")
|
||||
docker inspect -f "$svc status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}" "$cid"
|
||||
done
|
||||
docker volume ls --format '{{.Name}}' | grep -E 'pgdata$' | sed 's/^/volume kept: /'
|
||||
}
|
||||
{ echo "== $(date -u +%FT%TZ) before restart"; state; } >> "$LOG"
|
||||
dc stop api
|
||||
dc restart postgres redis
|
||||
dc start api
|
||||
{ echo "== $(date -u +%FT%TZ) after restart"; state; } >> "$LOG"
|
||||
Reference in New Issue
Block a user