Implement lab3 load balancing and failover

This commit is contained in:
Ilia Sokolov
2026-10-31 17:19:05 +03:00
parent 0ab3a341aa
commit 06d47fbb5b
27 changed files with 2438 additions and 25 deletions
+25
View File
@@ -0,0 +1,25 @@
# Creates local secrets and .env (Windows PowerShell 5.1 / PowerShell 7).
# Existing files are NEVER overwritten: the password of an already initialised database volume
# must keep matching secrets/postgres_password.
$ErrorActionPreference = 'Stop'
Set-Location (Join-Path $PSScriptRoot '..')
$db = if ($env:POSTGRES_DB) { $env:POSTGRES_DB } else { 'messenger' }
$user = if ($env:POSTGRES_USER) { $env:POSTGRES_USER } else { 'messenger' }
New-Item -ItemType Directory -Force -Path 'secrets' | Out-Null
# UTF-8 WITHOUT BOM and without a trailing newline: readable by the PostgreSQL image and by the app.
$utf8 = New-Object System.Text.UTF8Encoding($false)
$pwFile = Join-Path (Get-Location) 'secrets/postgres_password'
$urlFile = Join-Path (Get-Location) 'secrets/database_url'
if (-not (Test-Path $pwFile)) {
$bytes = New-Object byte[] 24
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
$password = ($bytes | ForEach-Object { $_.ToString('x2') }) -join ''
[System.IO.File]::WriteAllText($pwFile, $password, $utf8)
Write-Host 'created secrets/postgres_password'
}
if (-not (Test-Path $urlFile)) {
$password = [System.IO.File]::ReadAllText($pwFile).Trim()
[System.IO.File]::WriteAllText($urlFile, "postgres://${user}:${password}@postgres:5432/${db}?sslmode=disable", $utf8)
Write-Host 'created secrets/database_url'
}
if (-not (Test-Path '.env')) { Copy-Item '.env.example' '.env'; Write-Host 'created .env' }
+20
View File
@@ -0,0 +1,20 @@
#!/bin/sh
# Создаёт локальные секреты и .env (Linux/macOS/Git Bash). Существующие файлы НЕ перезаписываются:
# пароль уже созданной БД в volume должен совпадать с secrets/postgres_password.
set -eu
cd "$(dirname "$0")/.."
DB="${POSTGRES_DB:-messenger}"
USER_NAME="${POSTGRES_USER:-messenger}"
mkdir -p secrets
if [ ! -f secrets/postgres_password ]; then
head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n' > secrets/postgres_password
echo "created secrets/postgres_password" >&2
fi
if [ ! -f secrets/database_url ]; then
printf 'postgres://%s:%s@postgres:5432/%s?sslmode=disable' "$USER_NAME" "$(cat secrets/postgres_password)" "$DB" > secrets/database_url
echo "created secrets/database_url" >&2
fi
# Контейнеры работают не от вашего пользователя: файлы должны читаться всеми (каталог в Git не попадает).
chmod 755 secrets
chmod 644 secrets/postgres_password secrets/database_url
if [ ! -f .env ]; then cp .env.example .env; echo "created .env" >&2; fi
+25
View File
@@ -0,0 +1,25 @@
@echo off
rem Full restart of LB, all API replicas and PostgreSQL, volumes are preserved (Windows). No secrets are printed.
setlocal
cd /d "%~dp0.." || exit /b 1
docker compose stop lb api postgres >nul 2>&1
if errorlevel 1 exit /b 1
docker compose start postgres >nul 2>&1
if errorlevel 1 exit /b 1
set /a tries=0
:waitpg
docker compose exec -T postgres sh -c "pg_isready -q -U $POSTGRES_USER -d $POSTGRES_DB" >nul 2>&1
if not errorlevel 1 goto pgready
set /a tries+=1
if %tries% GEQ 45 exit /b 1
rem ping instead of timeout: timeout fails when stdin is redirected (as in tests/resilience.py)
ping -n 2 127.0.0.1 >nul
goto waitpg
:pgready
docker compose start api >nul 2>&1
if errorlevel 1 exit /b 1
docker compose start lb >nul 2>&1
exit /b %errorlevel%
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# Полный перезапуск LB, ВСЕХ реплик API и используемых хранилищ (PostgreSQL) с сохранением volumes.
# Не использует down -v / удаление volumes / повторный seed. Вывод секретов отсутствует.
set -eu
cd "$(dirname "$0")/.."
# stop → SIGTERM (graceful): API дожидается запросов, PostgreSQL делает fast shutdown и сбрасывает WAL.
docker compose stop lb api postgres >/dev/null 2>&1
docker compose start postgres >/dev/null 2>&1
tries=0
until docker compose exec -T postgres sh -c 'pg_isready -q -U "$POSTGRES_USER" -d "$POSTGRES_DB"' >/dev/null 2>&1; do
tries=$((tries + 1))
if [ "$tries" -ge 45 ]; then
echo "postgres did not become ready in time" >&2
exit 1
fi
sleep 1
done
docker compose start api >/dev/null 2>&1
docker compose start lb >/dev/null 2>&1
exit 0
+3
View File
@@ -0,0 +1,3 @@
@echo off
cd /d "%~dp0.." || exit /b 1
docker compose up -d
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# Восстановление: поднимает все остановленные/недостающие сервисы (в т.ч. остановленную реплику API).
set -eu
cd "$(dirname "$0")/.."
docker compose up -d
+11
View File
@@ -0,0 +1,11 @@
@echo off
rem Stops exactly ONE API replica: the container whose hostname equals TARGET_INSTANCE_ID (X-Instance-Id).
rem Leaves it stopped; DB, LB and volumes are untouched. Restore separately: docker compose up -d
setlocal
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
cd /d "%~dp0.." || exit /b 1
set "CID="
for /f %%i in ('docker ps -q --filter "id=%TARGET_INSTANCE_ID%" --filter "label=com.docker.compose.service=api"') do if not defined CID set "CID=%%i"
if not defined CID exit /b 1
docker stop --time 5 %CID% >nul 2>&1
exit /b %errorlevel%
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# Останавливает РОВНО ОДНУ API-реплику: ту, чей X-Instance-Id (= hostname контейнера) передан в
# TARGET_INSTANCE_ID, и оставляет её остановленной. БД, LB и volumes не трогаются. Секреты не печатаются.
# Восстановление отдельно: docker compose up -d (или scripts/start-all.sh)
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!A-Za-z0-9._-]*|"") echo "bad instance id" >&2; exit 2 ;;
esac
cd "$(dirname "$0")/.."
# Фильтр по compose-сервису api: LB/БД остановить этим скриптом невозможно.
cid=$(docker ps -q --filter "id=$TARGET_INSTANCE_ID" --filter "label=com.docker.compose.service=api" | head -n 1)
[ -n "$cid" ] || { echo "api container for instance not found" >&2; exit 1; }
# SIGTERM → graceful shutdown (ready=503, drain, закрытие listener); через 5 с — SIGKILL.
docker stop --time 5 "$cid" >/dev/null