This commit is contained in:
2026-10-15 00:24:46 +03:00
parent 0ab3a341aa
commit d9b9e8593c
73 changed files with 5029 additions and 37 deletions
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Создаёт локальные секреты стенда в каталоге secrets/ (он в .gitignore и в Git не попадает).
# Запуск один раз: sh scripts/init-secrets.sh
# Повторный запуск ничего не меняет: у уже созданного volume PostgreSQL пароль сменить так нельзя.
set -eu
cd "$(dirname "$0")/.."
if [ -e secrets/postgres_password ]; then
echo "secrets/ уже существует, оставляю как есть."
echo "Чтобы начать с нуля: docker compose down -v (удалит данные!), затем удалить secrets/ и запустить снова."
exit 0
fi
umask 077 # каталог secrets/ доступен только владельцу
mkdir -p secrets
# 24 случайных байта -> 48 hex-символов. /dev/urandom есть и в Linux/macOS, и в Git Bash.
random_hex() { od -An -tx1 -N24 /dev/urandom | tr -d ' \n'; }
PG_PASSWORD=$(random_hex)
CACHE_PASSWORD=$(random_hex)
# printf без перевода строки в конце: в файле только значение.
printf '%s' "$PG_PASSWORD" > secrets/postgres_password
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$PG_PASSWORD" > secrets/database_url
printf 'valkey://messenger:%s@valkey:6379/0' "$CACHE_PASSWORD" > secrets/cache_url
printf '%s\n' \
'user default off' \
'user health on nopass -@all +ping +info +dbsize' \
"user messenger on >$CACHE_PASSWORD ~sess:* resetchannels -@all +get +mget +set +del +ping" \
> secrets/valkey_users.acl
# Файлы читают процессы в контейнерах под своими пользователями (postgres, valkey, app),
# поэтому сами файлы доступны на чтение; посторонних на хосте не пускает каталог (700).
chmod 644 secrets/*
echo "Готово: secrets/postgres_password, database_url, cache_url, valkey_users.acl (значения не выводятся)."
+11
View File
@@ -0,0 +1,11 @@
@echo off
rem Windows restart hook for make test-persistence: same steps as scripts/restart.sh.
rem Python on Windows cannot run .sh directly (WinError 193), so this .cmd is used instead.
rem Restarts ALL api replicas and ALL stores (PostgreSQL, Valkey), then the balancer.
rem Volumes are kept (no down -v). Containers are the same (same ID, new start time).
cd /d "%~dp0.."
docker compose stop api || exit /b 1
docker compose restart postgres valkey || exit /b 1
docker compose start api || exit /b 1
docker compose restart lb || exit /b 1
exit /b 0
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Restart hook для make test-persistence (Linux/macOS).
# Перезапускает ВСЕ реплики API и ВСЕ используемые хранилища (PostgreSQL, Valkey),
# а затем балансировщик. Volumes сохраняются: нет down -v, flush или повторного seed.
# Контейнеры те же (restart/stop/start, не recreate): ID не меняется, меняется время старта.
set -eu
cd "$(dirname "$0")/.."
docker compose stop api # все реплики: readiness 503 -> уход из балансировки -> выход
docker compose restart postgres valkey # корректная остановка (SIGINT/SIGTERM) и запуск тех же контейнеров
docker compose start api # реплики ждут готовности PostgreSQL и проверяют схему
docker compose restart lb # балансировщик заново находит реплики по DNS
+6
View File
@@ -0,0 +1,6 @@
@echo off
rem Failover hook for make test-failover on Windows (same as scripts/stop-one.sh).
rem Python on Windows cannot start .sh files directly (WinError 193), a .cmd file works.
rem Stops ONE api replica from TARGET_INSTANCE_ID; the logic is in scripts\stop_one.py.
python "%~dp0stop_one.py"
exit /b %ERRORLEVEL%
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
# Failover hook для make test-failover (Linux/macOS): останавливает ОДНУ реплику API —
# ту, чей X-Instance-Id тест передал в TARGET_INSTANCE_ID, и оставляет её остановленной.
# Логика (проверка значения, поиск контейнера, docker stop) — в scripts/stop_one.py,
# общем для этого скрипта и для scripts/stop-one.cmd (Windows).
# Восстановить реплику после теста: make restore (docker compose up -d --wait).
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
exec "${PYTHON:-python3}" "$(dirname "$0")/stop_one.py"
+49
View File
@@ -0,0 +1,49 @@
"""Failover hook logic for tests/resilience.py --mode failover (lab3).
Called by scripts/stop-one.sh (Linux/macOS) and scripts/stop-one.cmd (Windows).
The test puts X-Instance-Id of the replica that served its first message into
TARGET_INSTANCE_ID. In this solution X-Instance-Id is the container hostname, and
Docker sets the hostname to the short container ID. So the script finds that ID
among the RUNNING containers of the "api" service of this Compose project and
stops only that one container. Postgres, Valkey, the balancer and volumes are not
touched. The replica stays stopped; restore it with `make restore`
(docker compose up -d --wait) or `docker start <id>`.
docker stop sends SIGTERM: the replica first answers 503 on /health/ready for
SHUTDOWN_DRAIN_SECONDS (HAProxy takes it out of rotation), then finishes started
requests and exits. --time 8: SIGKILL after 8 s at most, so the hook always returns
within the 10 s the test allows.
This file is plain ASCII on purpose: scripts/check_contract.py reads every
scripts/*.py with the default encoding, which is cp1251 on a Russian Windows.
"""
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STOP_TIMEOUT_SECONDS = 8
def main() -> int:
target = os.environ.get("TARGET_INSTANCE_ID", "").strip().lower()
# The value comes from an HTTP header: accept only a hex container ID, nothing else.
if not re.fullmatch(r"[0-9a-f]{12,64}", target):
print("TARGET_INSTANCE_ID must be a container id (X-Instance-Id)", file=sys.stderr)
return 2
running = subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT,
capture_output=True, text=True, check=True).stdout.split()
matches = [container for container in running if container.startswith(target)]
if len(matches) != 1:
print("no running api container with id " + target, file=sys.stderr)
return 1
subprocess.run(["docker", "stop", "--time", str(STOP_TIMEOUT_SECONDS), matches[0]],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
print("stopped api container " + matches[0][:12])
return 0
if __name__ == "__main__":
sys.exit(main())