ЛР 3 — БВТ-2302 — Сабитов — на 3
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
"""Temporarily use a two-second TTL, then restore both API configurations."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
os.chdir(Path(__file__).resolve().parents[1])
|
||||
base = os.environ.get('BASE_URL', 'http://localhost:' + os.environ.get('LAB3_HOST_PORT', '8080'))
|
||||
compose = ['docker', 'compose', '--env-file', '.env', 'up', '-d', '--no-deps',
|
||||
'--force-recreate', '--wait', '--wait-timeout', '60', 'api1', 'api2']
|
||||
normal = dict(os.environ, BASE_URL=base)
|
||||
short = dict(normal, SESSION_TTL_SECONDS='2')
|
||||
try:
|
||||
subprocess.run(compose, env=short, check=True, timeout=90)
|
||||
subprocess.run([sys.executable, 'scripts/wait_replicas.py'], env=short, check=True)
|
||||
subprocess.run([sys.executable, 'tests/student_tests.py', '--base-url', base, '--expiry'], env=short, check=True)
|
||||
finally:
|
||||
subprocess.run(compose, env=normal, check=True, timeout=90)
|
||||
subprocess.run([sys.executable, 'scripts/wait_replicas.py'], env=normal, check=True)
|
||||
print('PASS: session expiration tested with TTL=2; original API settings restored')
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Create local credentials once. Never print or overwrite an existing secret."""
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
path = root / '.env'
|
||||
if path.exists():
|
||||
print('Existing .env retained')
|
||||
else:
|
||||
settings = (root / '.env.example').read_text(encoding='utf-8')
|
||||
settings = settings.replace('POSTGRES_PASSWORD=', 'POSTGRES_PASSWORD=' + secrets.token_hex(24))
|
||||
with path.open('x', encoding='utf-8', newline='\n') as output:
|
||||
output.write(settings)
|
||||
print('Created local .env with a random password; keep it outside Git')
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Nonsecret Docker process/volume evidence. Does not output container environment."""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, text=True, encoding='utf-8').strip()
|
||||
|
||||
|
||||
def snapshot():
|
||||
services = {}
|
||||
for service in ('db', 'api1', 'api2', 'lb'):
|
||||
container = command('docker', 'compose', '--env-file', '.env', 'ps', '-q', service)
|
||||
assert container, service + ' is not running'
|
||||
info = json.loads(command('docker', 'inspect', container))[0]
|
||||
bindings = info['HostConfig'].get('PortBindings') or {}
|
||||
if service != 'lb':
|
||||
assert not bindings, 'Internal ports must not be published: ' + service
|
||||
else:
|
||||
assert set(bindings) == {'8080/tcp'}
|
||||
assert bindings['8080/tcp'][0]['HostIp'] == '127.0.0.1'
|
||||
services[service] = {'id': container[:12], 'started': info['State']['StartedAt']}
|
||||
if service == 'db':
|
||||
volume = next(m['Name'] for m in info['Mounts'] if m['Destination'] == '/var/lib/postgresql/data')
|
||||
created = command('docker', 'volume', 'inspect', '--format', '{{.CreatedAt}}', volume)
|
||||
return {'services': services, 'volume': volume, 'volume_created': created}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--save')
|
||||
parser.add_argument('--compare')
|
||||
args = parser.parse_args()
|
||||
state = snapshot()
|
||||
print(json.dumps(state, sort_keys=True))
|
||||
if args.save:
|
||||
Path(args.save).write_text(json.dumps(state), encoding='utf-8')
|
||||
if args.compare:
|
||||
before = json.loads(Path(args.compare).read_text(encoding='utf-8'))
|
||||
assert before['volume'] == state['volume'] and before['volume_created'] == state['volume_created'], 'Volume replaced'
|
||||
for service in state['services']:
|
||||
assert before['services'][service]['started'] != state['services'][service]['started'], service + ' did not restart'
|
||||
print('PASS: both APIs, LB and PostgreSQL restarted; same persistent volume retained')
|
||||
# psql reads its own environment inside the container. No password is printed.
|
||||
versions = command('docker', 'compose', '--env-file', '.env', 'exec', '-T', 'db', 'sh', '-c',
|
||||
'psql -X -At -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT version FROM schema_migrations ORDER BY version"')
|
||||
assert versions.splitlines() == ['1', '2'], 'Unexpected migration versions'
|
||||
print('PASS: migrations 001 and 002 each installed exactly once; only LB publishes a host port')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose --env-file .env stop -t 3 lb api1 api2 db
|
||||
if errorlevel 1 exit /b 1
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60
|
||||
exit /b %errorlevel%
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env stop -t 3 lb api1 api2 db
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\restore.ps1
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,19 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($env:TARGET_INSTANCE_ID -notin @('api1', 'api2')) { throw 'Invalid target' }
|
||||
$target = $env:TARGET_INSTANCE_ID
|
||||
$id = docker compose --env-file .env ps -a -q $target
|
||||
if ($LASTEXITCODE -ne 0 -or !$id) { throw 'Target container missing' }
|
||||
$running = docker inspect --format '{{.State.Running}}' $id
|
||||
if ($LASTEXITCODE -ne 0 -or $running -ne 'false') { throw 'Target must actually be stopped' }
|
||||
foreach ($service in @('db', 'lb', 'api1', 'api2')) {
|
||||
if ($service -eq $target) { continue }
|
||||
$id = docker compose --env-file .env ps -q $service
|
||||
if ($LASTEXITCODE -ne 0 -or !$id) { throw "$service must be running" }
|
||||
$running = docker inspect --format '{{.State.Running}}' $id
|
||||
if ($LASTEXITCODE -ne 0 -or $running -ne 'true') { throw "$service stopped unexpectedly" }
|
||||
}
|
||||
Write-Output "PASS: $target really stopped; the other API, LB and database stayed running"
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 $target
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Restore failed' }
|
||||
python -X utf8 scripts/wait_replicas.py
|
||||
if ($LASTEXITCODE -ne 0) { throw 'LB recovery failed' }
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
case "${TARGET_INSTANCE_ID:-}" in api1|api2) ;; *) exit 2 ;; esac
|
||||
id=$(docker compose --env-file .env ps -a -q "$TARGET_INSTANCE_ID")
|
||||
test "$(docker inspect --format '{{.State.Running}}' "$id")" = false
|
||||
for service in db lb api1 api2; do
|
||||
test "$service" = "$TARGET_INSTANCE_ID" && continue
|
||||
id=$(docker compose --env-file .env ps -q "$service")
|
||||
test -n "$id"
|
||||
test "$(docker inspect --format '{{.State.Running}}' "$id")" = true
|
||||
done
|
||||
echo "PASS: $TARGET_INSTANCE_ID really stopped; the other API, LB and database stayed running"
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 "$TARGET_INSTANCE_ID"
|
||||
# Wait for HAProxy's next successful check; do not assume Compose health is LB health.
|
||||
python3 scripts/wait_replicas.py
|
||||
@@ -0,0 +1,11 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
if "%TARGET_INSTANCE_ID%"=="api1" goto stop
|
||||
if "%TARGET_INSTANCE_ID%"=="api2" goto stop
|
||||
echo Expected TARGET_INSTANCE_ID=api1 or api2
|
||||
exit /b 2
|
||||
:stop
|
||||
docker compose --env-file .env stop -t 3 %TARGET_INSTANCE_ID%
|
||||
if errorlevel 1 exit /b 1
|
||||
>evidence\last-stopped.txt echo %TARGET_INSTANCE_ID%
|
||||
exit /b 0
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
case "${TARGET_INSTANCE_ID:-}" in
|
||||
api1|api2) target="$TARGET_INSTANCE_ID" ;;
|
||||
*) echo 'Expected TARGET_INSTANCE_ID=api1 or api2' >&2; exit 2 ;;
|
||||
esac
|
||||
docker compose --env-file .env stop -t 3 "$target"
|
||||
# Only a nonsecret service alias, used by verification to prove both targets.
|
||||
printf '%s\n' "$target" > evidence/last-stopped.txt
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
# Requires Docker Compose, Python 3.9+ and make. Run from a clone or unpacked folder.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export PYTHONUTF8=1
|
||||
export PYTHONDONTWRITEBYTECODE=1
|
||||
export BASE_URL="${BASE_URL:-http://localhost:${LAB3_HOST_PORT:-8080}}"
|
||||
chmod +x scripts/restart.sh scripts/stop-one.sh scripts/restore.sh
|
||||
echo "Lab 3 verification $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait --wait-timeout 90
|
||||
make check
|
||||
make test BASE_URL="$BASE_URL"
|
||||
python3 tests/student_tests.py --base-url "$BASE_URL"
|
||||
python3 tests/contract_edge_tests.py --base-url "$BASE_URL"
|
||||
python3 tests/lab3_tests.py --base-url "$BASE_URL" --restart-script scripts/restart.sh
|
||||
state=$(mktemp)
|
||||
trap 'rm -f "$state"' EXIT
|
||||
python3 scripts/operator_state.py --save "$state"
|
||||
make test-persistence BASE_URL="$BASE_URL" ACTION_SCRIPT=scripts/restart.sh
|
||||
python3 scripts/operator_state.py --compare "$state"
|
||||
make test-failover BASE_URL="$BASE_URL" ACTION_SCRIPT=scripts/stop-one.sh
|
||||
TARGET_INSTANCE_ID=$(cat evidence/last-stopped.txt)
|
||||
export TARGET_INSTANCE_ID
|
||||
sh scripts/restore.sh
|
||||
python3 tests/failover_each.py --base-url "$BASE_URL" --action-script scripts/stop-one.sh --restore-script scripts/restore.sh
|
||||
make test BASE_URL="$BASE_URL"
|
||||
echo 'PASS: full Lab 3 verification completed'
|
||||
@@ -0,0 +1,68 @@
|
||||
param(
|
||||
[ValidateRange(1, 65535)]
|
||||
[int]$Port = 8080
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$previousPort = $env:LAB3_HOST_PORT
|
||||
$previousBase = $env:BASE_URL
|
||||
$previousUtf8 = $env:PYTHONUTF8
|
||||
$previousBytecode = $env:PYTHONDONTWRITEBYTECODE
|
||||
function Assert-Success([string]$Step) {
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Step failed (exit code $LASTEXITCODE)" }
|
||||
}
|
||||
function Write-Evidence([string]$Line) {
|
||||
Add-Content -LiteralPath $evidence -Value $Line -Encoding UTF8
|
||||
Write-Host $Line
|
||||
}
|
||||
function Run-Python([string[]]$Arguments) {
|
||||
Write-Evidence ("python " + ($Arguments -join ' '))
|
||||
& python -X utf8 @Arguments | ForEach-Object { Write-Evidence $_ }
|
||||
Assert-Success 'Python check'
|
||||
}
|
||||
Push-Location -LiteralPath (Join-Path $PSScriptRoot '..')
|
||||
$state = Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString() + '.json')
|
||||
try {
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONDONTWRITEBYTECODE = '1'
|
||||
$env:LAB3_HOST_PORT = [string]$Port
|
||||
if (!(Test-Path -LiteralPath '.env')) {
|
||||
$password = python -X utf8 -c 'import secrets; print(secrets.token_hex(24))'
|
||||
Assert-Success 'Local password generation'
|
||||
(Get-Content -LiteralPath '.env.example') -replace '^POSTGRES_PASSWORD=.*', "POSTGRES_PASSWORD=$password" |
|
||||
Set-Content -LiteralPath '.env' -Encoding Ascii
|
||||
}
|
||||
$evidence = 'evidence/results-windows.txt'
|
||||
Set-Content -LiteralPath $evidence -Value ("Lab 3 verification " + (Get-Date -Format o)) -Encoding UTF8
|
||||
docker compose --env-file .env config --quiet
|
||||
Assert-Success 'Compose configuration'
|
||||
docker compose --env-file .env up -d --build --wait --wait-timeout 90
|
||||
Assert-Success 'Compose startup'
|
||||
$address = docker compose --env-file .env port lb 8080
|
||||
Assert-Success 'LB port lookup'
|
||||
if ($address -notmatch '^127\.0\.0\.1:\d+$') { throw 'Expected local LB address' }
|
||||
$env:BASE_URL = "http://$address"
|
||||
Write-Evidence "PASS: Compose startup, public entrypoint $env:BASE_URL"
|
||||
Run-Python @('scripts/check_contract.py')
|
||||
Run-Python @('tests/smoke.py', '--base-url', $env:BASE_URL)
|
||||
Run-Python @('tests/student_tests.py', '--base-url', $env:BASE_URL)
|
||||
Run-Python @('tests/contract_edge_tests.py', '--base-url', $env:BASE_URL)
|
||||
Run-Python @('tests/lab3_tests.py', '--base-url', $env:BASE_URL, '--restart-script', 'scripts/restart.cmd')
|
||||
Run-Python @('scripts/operator_state.py', '--save', $state)
|
||||
Run-Python @('tests/resilience.py', '--mode', 'persistence', '--base-url', $env:BASE_URL, '--action-script', 'scripts/restart.cmd')
|
||||
Run-Python @('scripts/operator_state.py', '--compare', $state)
|
||||
Run-Python @('tests/resilience.py', '--mode', 'failover', '--base-url', $env:BASE_URL, '--action-script', 'scripts/stop-one.cmd')
|
||||
$env:TARGET_INSTANCE_ID = (Get-Content -LiteralPath 'evidence/last-stopped.txt').Trim()
|
||||
& powershell -NoProfile -ExecutionPolicy Bypass -File scripts/restore.ps1 | ForEach-Object { Write-Evidence $_ }
|
||||
Assert-Success 'Restore after public failover'
|
||||
Run-Python @('tests/failover_each.py', '--base-url', $env:BASE_URL, '--action-script', 'scripts/stop-one.cmd', '--restore-script', 'scripts/restore.cmd')
|
||||
Run-Python @('tests/smoke.py', '--base-url', $env:BASE_URL)
|
||||
Write-Evidence 'PASS: full Lab 3 verification completed'
|
||||
}
|
||||
finally {
|
||||
if (Test-Path -LiteralPath $state) { Remove-Item -LiteralPath $state }
|
||||
$env:LAB3_HOST_PORT = $previousPort
|
||||
$env:BASE_URL = $previousBase
|
||||
$env:PYTHONUTF8 = $previousUtf8
|
||||
$env:PYTHONDONTWRITEBYTECODE = $previousBytecode
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Wait until both real API aliases are observed through the LB."""
|
||||
import os
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
base = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
seen = set()
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + '/health/ready', timeout=2) as reply:
|
||||
seen.add(reply.headers['X-Instance-Id'])
|
||||
except OSError:
|
||||
pass
|
||||
if {'api1', 'api2'} <= seen:
|
||||
print('PASS: both replicas observed through LB')
|
||||
break
|
||||
time.sleep(0.15)
|
||||
else:
|
||||
raise SystemExit('Both API replicas did not return to LB')
|
||||
Reference in New Issue
Block a user