Лаба 4: вложения в S3, уровни 3-5, reconciler (трек 2)

This commit is contained in:
2026-11-14 09:19:07 +03:00
parent ec540a1a72
commit 0dc99c9e33
63 changed files with 4810 additions and 18 deletions
+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
# Создаёт локальные секреты, которых ещё нет. Существующие не перезаписывает. В Git не попадают (secrets/ в .gitignore)
set -eu
cd "$(dirname "$0")/.."
mkdir -p secrets
BUCKET="${S3_BUCKET:-messenger-attachments}"
rnd() { openssl rand -hex "$1"; }
put() { [ -s "secrets/$1" ] || { printf '%s' "$2" > "secrets/$1"; echo "created secrets/$1"; }; }
if [ ! -s secrets/postgres_password ]; then
PW=$(rnd 24)
printf '%s' "$PW" > secrets/postgres_password
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$PW" > secrets/database_url
echo "created secrets/postgres_password, secrets/database_url"
fi
put s3_admin_access_key_id "admin$(rnd 8)"
put s3_admin_secret_access_key "$(rnd 24)"
put s3_api_access_key_id "api$(rnd 8)"
put s3_api_secret_access_key "$(rnd 24)"
if [ ! -s secrets/s3_config ]; then
# Конфиг identities SeaweedFS: admin (создание bucket) и api (только свой bucket)
printf '{"identities":[{"name":"admin","credentials":[{"accessKey":"%s","secretKey":"%s"}],"actions":["Admin","Read","Write","List","Tagging"]},{"name":"api","credentials":[{"accessKey":"%s","secretKey":"%s"}],"actions":["Read:%s","Write:%s","List:%s"]}]}' \
"$(cat secrets/s3_admin_access_key_id)" "$(cat secrets/s3_admin_secret_access_key)" \
"$(cat secrets/s3_api_access_key_id)" "$(cat secrets/s3_api_secret_access_key)" \
"$BUCKET" "$BUCKET" "$BUCKET" > secrets/s3_config
echo "created secrets/s3_config"
fi
chmod 644 secrets/* # локальный стенд с синтетическими данными: нужно, чтобы читал не-root пользователь в контейнере
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
# Перезапуск API и ВСЕХ хранилищ (PostgreSQL, Valkey, S3) с сохранением volumes (никаких down -v).
# В конце ждёт, пока S3 реально отдаёт данные: контейнер healthy раньше, чем volume-сервер готов читать.
set -eu
cd "$(dirname "$0")/.."
C="docker compose --env-file .env"
$C stop api
$C restart postgres valkey s3
$C start api
i=0
while [ "$i" -lt 60 ]; do
if $C exec -T api python -c "
from src import storage, config
r = storage.client().list_objects_v2(Bucket=config.S3_BUCKET, Prefix='attachments/', MaxKeys=1)
for o in r.get('Contents', []):
storage.get_object(o['Key']).read(1)
" >/dev/null 2>&1; then
exit 0
fi
i=$((i + 1)); sleep 1
done
echo "S3 data path is not ready" >&2
exit 1
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Поочерёдная замена API-реплик новой версией образа (APP_VERSION=v2 scripts/rolling-update.sh).
# Миграции запускаются ОДИН раз до замены; migrations/002 только добавляет таблицу, поэтому старая версия с ней совместима.
set -eu
cd "$(dirname "$0")/.."
: "${APP_VERSION:?set new version, e.g. APP_VERSION=v2}"
export APP_VERSION
COMPOSE="docker compose --env-file .env"
$COMPOSE build migrate
$COMPOSE run --rm migrate
N=$($COMPOSE ps -q api | wc -l | tr -d ' ')
wait_healthy() {
i=0
while [ "$i" -lt 90 ]; do
c=$($COMPOSE ps api --format '{{.Health}}' | grep -c '^healthy$' || true)
[ "$c" -ge "$N" ] && return 0
i=$((i + 1)); sleep 1
done
echo "replicas did not become healthy" >&2; return 1
}
for cid in $($COMPOSE ps -q api); do
echo "replacing $cid" >&2
docker stop -t 20 "$cid" >/dev/null # SIGTERM: readiness 503, drain 5 с, затем завершение
docker rm "$cid" >/dev/null
$COMPOSE up -d --no-deps --no-recreate --scale api="$N" api # создаётся реплика из нового образа
wait_healthy
sleep 5 # LB добавляет новую реплику после 2 успешных проверок
done
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
# Базовая нагрузка, затем по очереди отказ каждой API-реплики под нагрузкой с восстановлением между ними.
set -eu
cd "$(dirname "$0")/.."
COMPOSE="docker compose --env-file .env"
wait_healthy() {
i=0
while [ "$i" -lt 90 ]; do
c=$($COMPOSE ps api --format '{{.Health}}' | grep -c '^healthy$' || true)
[ "$c" -ge 2 ] && return 0
i=$((i + 1)); sleep 1
done
echo "replicas did not become healthy" >&2; return 1
}
python3 student_tests/loadgen.py --duration 30 --output evidence/load-baseline.json
for idx in 0 1; do
python3 student_tests/loadgen.py --duration 40 --action-script scripts/stop-one.sh \
--action-at 10 --target-index "$idx" --output "evidence/load-stop-$idx.json"
$COMPOSE ps -a > "evidence/load-stop-$idx-ps.txt"
$COMPOSE start api
wait_healthy
sleep 10 # LB возвращает реплику после 2 успешных проверок
done
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Одна сессия, 10 запросов через LB: в ответах должны быть >=2 разных X-Instance-Id.
set -eu
BASE="${BASE_URL:-http://localhost:8080}"
U="demo_$(date +%s)"
curl -sf -X POST "$BASE/api/v1/users" -H 'Content-Type: application/json' \
-d "{\"username\":\"$U\",\"display_name\":\"Demo\",\"password\":\"demo-password-123\"}" >/dev/null
TOKEN=$(curl -sf -X POST "$BASE/api/v1/auth/sessions" -u "$U:demo-password-123" \
| python3 -c 'import sys,json; print(json.load(sys.stdin)["token"])')
for i in 1 2 3 4 5 6 7 8 9 10; do
curl -si "$BASE/api/v1/users/me" -H "Authorization: Bearer $TOKEN" | grep -i '^x-instance-id'
done | sort | uniq -c
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Останавливает ОДНУ API-реплику по TARGET_INSTANCE_ID (= hostname контейнера = короткий ID)
# Реплика остаётся остановленной. БД, LB и volumes не затрагиваются
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")/.."
CID=$(docker ps --filter "label=com.docker.compose.service=api" \
--filter "id=$TARGET_INSTANCE_ID" --format '{{.ID}}')
[ -n "$CID" ] || { echo "no running api container for this instance" >&2; exit 1; }
docker stop -t 2 "$CID" >/dev/null
echo "stopped api container $CID" >&2