Перенести решение lab3 как базу lab4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
# Creates local Docker secrets for a synthetic lab stand.
|
||||
# Existing files are never overwritten; values are never printed.
|
||||
set -eu
|
||||
|
||||
dir="$(cd "$(dirname "$0")/.." && pwd)/infra/secrets"
|
||||
mkdir -p "$dir"
|
||||
# Host access is limited by the directory mode; the files themselves must stay
|
||||
# readable by the non-root users inside containers (bind-mounted secrets).
|
||||
chmod 700 "$dir" 2>/dev/null || true
|
||||
|
||||
random() {
|
||||
od -An -tx1 -N24 /dev/urandom | tr -d ' \n'
|
||||
}
|
||||
|
||||
write_new() {
|
||||
if [ -f "$dir/$1" ]; then
|
||||
echo "keep infra/secrets/$1"
|
||||
else
|
||||
printf '%s' "$2" > "$dir/$1"
|
||||
chmod 644 "$dir/$1" 2>/dev/null || true
|
||||
echo "create infra/secrets/$1"
|
||||
fi
|
||||
}
|
||||
|
||||
if [ ! -f "$dir/postgres_password.txt" ]; then
|
||||
write_new postgres_password.txt "$(random)"
|
||||
fi
|
||||
pg_password="$(cat "$dir/postgres_password.txt")"
|
||||
write_new database_url.txt "postgresql://messenger:${pg_password}@db:5432/messenger"
|
||||
|
||||
if [ ! -f "$dir/valkey_password.txt" ]; then
|
||||
write_new valkey_password.txt "$(random)"
|
||||
fi
|
||||
valkey_password="$(cat "$dir/valkey_password.txt")"
|
||||
write_new cache_url.txt "redis://:${valkey_password}@valkey:6379/0"
|
||||
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
# Вариант жёсткого отказа (для сравнения): SIGKILL без graceful shutdown.
|
||||
# Используется в собственных экспериментах; публичный тест запускается со stop-one.sh.
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?target API instance alias required}"
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!0-9a-f]* | "") echo "unexpected instance id format" >&2; exit 2 ;;
|
||||
esac
|
||||
for id in $(service_ids api); do
|
||||
case "$id" in "$TARGET_INSTANCE_ID"*)
|
||||
docker kill --signal KILL "$id" >/dev/null
|
||||
echo "killed api container $(short "$id") at $(date -u +%H:%M:%S)"
|
||||
exit 0 ;;
|
||||
esac
|
||||
done
|
||||
echo "instance $TARGET_INSTANCE_ID is not a running api container" >&2
|
||||
exit 3
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/bin/sh
|
||||
# Общие функции операторских скриптов. Используют только docker CLI и метки Compose,
|
||||
# поэтому работают и на хосте, и в контейнере tester (docker.sock).
|
||||
PROJECT="${COMPOSE_PROJECT:-messenger-lab3}"
|
||||
|
||||
# ID контейнеров сервиса (по умолчанию только работающих); -a — включая остановленные.
|
||||
service_ids() {
|
||||
# $1 — сервис, $2 — необязательный флаг -a
|
||||
docker ps ${2:-} -q --no-trunc \
|
||||
--filter "label=com.docker.compose.project=$PROJECT" \
|
||||
--filter "label=com.docker.compose.service=$1"
|
||||
}
|
||||
|
||||
# Ждать, пока все переданные контейнеры станут healthy (timeout в секундах первым аргументом).
|
||||
# В POSIX sh переменные функций глобальны: имена с префиксом _wh_, чтобы не затереть
|
||||
# переменные вызывающего цикла.
|
||||
wait_healthy() {
|
||||
_wh_timeout="$1"; shift
|
||||
_wh_deadline=$(( $(date +%s) + _wh_timeout ))
|
||||
for _wh_id in "$@"; do
|
||||
while :; do
|
||||
_wh_state=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$_wh_id" 2>/dev/null || echo missing)
|
||||
case "$_wh_state" in healthy|running) break ;; esac
|
||||
if [ "$(date +%s)" -ge "$_wh_deadline" ]; then
|
||||
echo "container $(echo "$_wh_id" | cut -c1-12) not healthy (state=$_wh_state)" >&2
|
||||
return 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
short() { echo "$1" | cut -c1-12; }
|
||||
@@ -0,0 +1,99 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import asyncpg
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MIGRATIONS_DIR = ROOT / "migrations"
|
||||
# Lab3: migrations run once in the "migrate" service before the API replicas
|
||||
# start. The advisory lock still serialises two accidental parallel runs
|
||||
# (e.g. a manual run during a rolling update); the second one then sees all
|
||||
# versions in schema_migrations and only prints SKIP.
|
||||
MIGRATION_LOCK_ID = 727003
|
||||
|
||||
|
||||
def read_database_url() -> str:
|
||||
file_name = os.getenv("DATABASE_URL_FILE")
|
||||
|
||||
if file_name:
|
||||
return Path(file_name).read_text(encoding="utf-8").strip()
|
||||
|
||||
value = os.getenv("DATABASE_URL")
|
||||
|
||||
if not value:
|
||||
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required.")
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def plain_postgres_url(url: str) -> str:
|
||||
if url.startswith("postgresql+asyncpg://"):
|
||||
return url.replace("postgresql+asyncpg://", "postgresql://", 1)
|
||||
|
||||
return url
|
||||
|
||||
|
||||
async def connect_with_retry(url: str, attempts: int = 30):
|
||||
for attempt in range(1, attempts + 1):
|
||||
try:
|
||||
return await asyncpg.connect(url, timeout=3)
|
||||
except (OSError, asyncpg.PostgresError) as exc:
|
||||
if attempt == attempts:
|
||||
raise
|
||||
print(f"WAIT database ({type(exc).__name__}), retry {attempt}")
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
async def migrate() -> None:
|
||||
connection = await connect_with_retry(
|
||||
plain_postgres_url(read_database_url())
|
||||
)
|
||||
|
||||
try:
|
||||
await connection.execute(
|
||||
"SELECT pg_advisory_lock($1)",
|
||||
MIGRATION_LOCK_ID,
|
||||
)
|
||||
await connection.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
applied_rows = await connection.fetch(
|
||||
"SELECT version FROM schema_migrations"
|
||||
)
|
||||
applied = {row["version"] for row in applied_rows}
|
||||
|
||||
for migration_file in sorted(MIGRATIONS_DIR.glob("*.sql")):
|
||||
version = migration_file.name
|
||||
|
||||
if version in applied:
|
||||
print(f"SKIP {version}")
|
||||
continue
|
||||
|
||||
sql = migration_file.read_text(encoding="utf-8")
|
||||
|
||||
print(f"APPLY {version}")
|
||||
|
||||
async with connection.transaction():
|
||||
await connection.execute(sql)
|
||||
await connection.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES ($1)",
|
||||
version,
|
||||
)
|
||||
|
||||
print("PASS: migrations applied")
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(migrate())
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Persistence hook: restarts the LB, every API replica and both stores
|
||||
# (PostgreSQL with its volume, Valkey cache). No "down -v", no re-seed.
|
||||
# Uses only the docker CLI and Compose labels, so it also runs in "tester".
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
api=$(service_ids api); lb=$(service_ids lb); db=$(service_ids db); valkey=$(service_ids valkey)
|
||||
[ -n "$api" ] && [ -n "$db" ] && [ -n "$lb" ] && [ -n "$valkey" ] || { echo "stack is not running" >&2; exit 2; }
|
||||
echo "stopping lb + api, then db + valkey"
|
||||
docker stop --time 15 $lb $api >/dev/null
|
||||
docker stop --time 30 $db $valkey >/dev/null
|
||||
echo "starting db + valkey"
|
||||
docker start $db $valkey >/dev/null
|
||||
wait_healthy 60 $db $valkey
|
||||
echo "starting api"
|
||||
docker start $api >/dev/null
|
||||
wait_healthy 60 $api
|
||||
docker start $lb >/dev/null
|
||||
echo "restart complete: db=$(short $db) valkey=$(short $valkey) api=$(for i in $api; do short $i; done | tr '\n' ' ')"
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
# Восстановление после stop-one.sh: запускает остановленные API-реплики и ждёт healthy.
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
all=$(service_ids api -a)
|
||||
running=$(service_ids api)
|
||||
started=""
|
||||
for id in $all; do
|
||||
case " $running " in *" $id "*) continue ;; esac
|
||||
docker start "$id" >/dev/null
|
||||
started="$started $id"
|
||||
echo "started api container $(short "$id")"
|
||||
done
|
||||
[ -z "$started" ] || wait_healthy 60 $started
|
||||
echo "running api replicas: $(service_ids api | wc -l | tr -d ' ')"
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
# Failover hook: останавливает ОДНУ API-реплику, обслужившую тест, и оставляет её остановленной.
|
||||
# TARGET_INSTANCE_ID = X-Instance-Id = hostname контейнера = префикс его Docker ID.
|
||||
# БД, LB и volumes не затрагиваются. Восстановление: scripts/start-api.sh.
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!0-9a-f]* | "") echo "unexpected instance id format" >&2; exit 2 ;;
|
||||
esac
|
||||
target=""
|
||||
for id in $(service_ids api); do
|
||||
case "$id" in "$TARGET_INSTANCE_ID"*) target="$id" ;; esac
|
||||
done
|
||||
if [ -z "$target" ]; then
|
||||
echo "instance $TARGET_INSTANCE_ID is not a running api container of project $PROJECT" >&2
|
||||
exit 3
|
||||
fi
|
||||
# docker stop = SIGTERM -> graceful drain (~3 s) -> выход; SIGKILL только после 15 s.
|
||||
docker stop --time 15 "$target" >/dev/null
|
||||
echo "stopped api container $(short "$target") at $(date -u +%H:%M:%S)"
|
||||
Reference in New Issue
Block a user