diff --git a/.env.example b/.env.example index 2767104..495c15f 100644 --- a/.env.example +++ b/.env.example @@ -20,6 +20,8 @@ DB_STATEMENT_TIMEOUT_MS=5000 DB_OP_TIMEOUT=6 REQUEST_TIMEOUT=8 DB_READY_TIMEOUT=1.5 +READY_CHECK_SECONDS=1 +READY_FAILURES=2 SESSION_CACHE_TTL_SECONDS=30 SESSION_SWEEP_SECONDS=60 CACHE_TIMEOUT=0.2 diff --git a/REPORT.md b/REPORT.md index 8082da7..848f0bc 100644 --- a/REPORT.md +++ b/REPORT.md @@ -63,10 +63,11 @@ docker compose down -v | Компонент | Изменение | |---|---| | `compose.yaml` | Два сервиса `api-1`, `api-2` за Nginx; CPU/RAM лимиты; API не публикуют порты; нет `container_name` | -| `infra/nginx.conf` | Round-robin; passive health (max_fails=3, fail_timeout=10s); `proxy_next_upstream ... non_idempotent` для повтора POST на другую реплику при 502/503/ошибке соединения; `resolver 127.0.0.11` + `resolve` в upstream, чтобы nginx видел новый IP реплики после её пересоздания; keepalive-соединения к API | +| `infra/nginx.conf` | Round-robin; список серверов upstream подключается из файла, который ведёт `infra/nginx-health.sh`; пассивная защита `max_fails=1 fail_timeout=10s`; повтор на другую реплику при 502/503/ошибке соединения: для GET везде, для POST только на маршруте `/api/v1/chats/{id}/messages` (`non_idempotent`), где обязателен Idempotency-Key; `resolver 127.0.0.11` + `resolve`, чтобы nginx видел новый IP реплики после её пересоздания; keepalive-соединения к API | +| `infra/nginx-health.sh` | Активная проверка готовности внутри контейнера nginx: раз в 1 с `GET /health/ready` каждой реплики; 2 неудачи подряд → сервер помечается `down` в upstream и выполняется `nginx -s reload`; 2 успеха подряд → возвращается. Если неготовы все, никто не помечается `down` | | `app/config.py` | Добавлен `IDEMPOTENCY_TTL_SECONDS` | -| `app/repo.py` | `create_message_idempotent()` — advisory lock + INSERT message + INSERT idempotency_keys в одной транзакции | -| `app/main.py` | Валидация `Idempotency-Key`, вызов idempotent-метода, очистка просроченных ключей в sweeper | +| `app/repo.py` | `create_message_idempotent()` — advisory lock, затем проверка членства в чате (и для нового запроса, и для повтора), затем INSERT message + INSERT idempotency_keys в одной транзакции | +| `app/main.py` | Валидация `Idempotency-Key`, вызов idempotent-метода, очистка просроченных ключей в sweeper; фоновая проверка связи с PostgreSQL раз в 1 с, после 2 неудач подряд бизнес-запросы получают 503 до восстановления связи | | `migrations/0002_idempotency.sql` | Таблица `idempotency_keys` (PK: user_id, chat_id, key) | | `scripts/stop-one.sh` | Останавливает реплику по `TARGET_INSTANCE_ID` (= имя сервиса) | | `scripts/restart.sh` | Перезапуск всего стенда с сохранением volumes | @@ -89,6 +90,7 @@ docker compose down -v | `SESSION_TTL_SECONDS` | TTL сессии | 3600 | | `DB_POOL_MAX` | Макс. подключений к PostgreSQL | 10 | | `GRACEFUL_TIMEOUT` | Время graceful shutdown Uvicorn | 8 | +| `READY_CHECK_SECONDS`, `READY_FAILURES` | Интервал фоновой проверки PostgreSQL и число неудач подряд до режима «не готов» | 1, 2 | ## Доказательства критериев @@ -101,14 +103,15 @@ docker compose down -v | Повтор POST с тем же Idempotency-Key — нет дубля | smoke test (idempotency replay section) | replay == first | evidence/smoke.txt | | Конкурентный повтор через разные реплики | `python3 student-tests/test_parallel_idempotency.py` | PASS: 8 parallel requests, 1 message | evidence/parallel_idempotency.txt | | Health/readiness, timeouts, graceful shutdown | SIGTERM → лог "draining", 503 на новые запросы; Nginx убирает backend | docker compose logs api-1 | evidence/graceful_shutdown.txt | -| Nginx исключает упавший backend | max_fails=3, fail_timeout=10s; после stop — запросы идут на живую реплику | failover test | evidence/failover_both.txt | -| Максимальное время обнаружения отказа | Nginx passive: ≤3 ошибки × время одного connect = <1 с | first_recovery_seconds в failover output: 1.46 с | evidence/failover_both.txt | +| Nginx исключает упавший или неготовый backend | Активная проверка `/health/ready` (`infra/nginx-health.sh`) + `max_fails=1`; после stop — запросы идут на живую реплику | failover test; лог nginx `health: api-1 not ready, marked down` | evidence/failover_both.txt, evidence/review_scenarios.txt | +| Максимальное время обнаружения отказа | Остановленная реплика: первая же ошибка соединения повторяется на другой реплике и выключает сервер (`max_fails=1`). Неготовая реплика: ≤ 2 проверки × (1 с интервал + 1 с таймаут) ≈ 4 с, всё это время GET и POST сообщений повторяются на живой реплике | first_recovery_seconds: 0.33 с | evidence/failover_both.txt | | Последовательная остановка каждой реплики | stop api-1 → test → restore → stop api-2 → test | Оба теста PASS | evidence/failover_both.txt | | RPS, ошибки, время восстановления | failover output JSON | successful_writes, failed_attempts, first_recovery_seconds | evidence/failover_both.txt | | CPU/RAM лимиты | `docker compose config \| grep -A2 limits` | api: 0.5 CPU / 256M; nginx: 0.25 CPU / 64M; pg: 1.0 CPU / 512M | evidence/limits.txt | | API не публикуют порты мимо LB | `docker compose ps` — только nginx на 8080 | Порты: "127.0.0.1:8080->8080/tcp" только у nginx | evidence/ports.txt | | Нет container_name | compose.yaml | Нет ни одного container_name | compose.yaml | -| Rolling update под нагрузкой | `student-tests/rolling_update.sh`: нагрузка 60 с, `up -d --no-deps --force-recreate api-1` → ждём healthy → api-2 | Оба контейнера заменены (разные ID), 884 RPS, 0 ошибок | evidence/rolling_update.txt | +| Rolling update под нагрузкой | `student-tests/rolling_update.sh`: нагрузка 60 с, `up -d --no-deps --force-recreate api-1` → ждём healthy → api-2 | Оба контейнера заменены (разные ID), 910 RPS, 0 ошибок | evidence/rolling_update.txt | +| Замечания ревью PR #61 (повтор после потери членства, повтор POST /chats балансировщиком, неготовая реплика в upstream) | `python3 student-tests/test_review_scenarios.py` | До исправлений 5 FAIL (повтор → 201; 3 POST /chats ушли на две реплики; неготовая api-1 обслужила 20 из 40 GET), после — PASS | evidence/review_scenarios.txt | | Миграции однократны | Отдельный контейнер `migrate`; advisory lock; checksum | `docker compose logs migrate` → "skip 0001 / apply 0002" | evidence/migrate.txt | | Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS: persistence preserved confirmed data | evidence/persistence.txt | @@ -122,7 +125,7 @@ docker compose down -v - Hardware: Apple M4, 16 GB RAM, macOS, Docker Desktop. Клиент нагрузки работает на том же хосте. - Профиль: `tests/load.py --duration 30 --concurrency 16`, closed-loop POST сообщений с Idempotency-Key. - Прогрев 5 с, затем 3 прогона по 30 с на конфигурацию; в таблицах медиана, в скобках min..max. -- Лимиты API задаются override-файлами `infra/scaling/limits.yaml` и `infra/scaling/replicas-4.yaml`, nginx получает свой upstream `infra/scaling/nginx-{1,2,4}.conf`. Фактические лимиты проверяются через `docker inspect` (`*_limits.txt`). +- Лимиты API задаются override-файлами `infra/scaling/limits.yaml` и `infra/scaling/replicas-4.yaml`, список реплик для nginx задаётся переменной `API_UPSTREAMS` (в замерах ниже использовались отдельные файлы `nginx-{1,2,4}.conf` с тем же upstream; после ревью они заменены активной проверкой, путь запросов через nginx не изменился). Фактические лимиты проверяются через `docker inspect` (`*_limits.txt`). - Лимиты остальных сервисов не меняются: nginx 0.25 CPU, PostgreSQL 1.0 CPU, Valkey 0.25 CPU. - В середине каждого прогона снимается `docker stats` (`*_stats.txt`), чтобы видеть, какой контейнер упёрся в лимит. - Скрипты: `student-tests/scaling_experiment.sh`, `student-tests/scaling_summary.py`. Сырые данные: `evidence/scaling/*.json`, сводка `evidence/scaling/summary.csv`, график `evidence/scaling/rps.svg`. @@ -168,11 +171,12 @@ docker compose down -v | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | |---|---|---|---| -| Остановка api-1 | Nginx направляет трафик на api-2; ≤10 с до восстановления; 0 потерь подтверждённых сообщений | 121 запись, 0 ошибок | 1.46 с / 0 потерь | -| Остановка api-2 (после восстановления api-1) | Аналогично | 120 записей, 1 неудачная попытка в переходный момент | 1.46 с / 0 потерь | +| Остановка api-1 | Nginx направляет трафик на api-2; ≤10 с до восстановления; 0 потерь подтверждённых сообщений | 130 записей, 0 ошибок | 0.33 с / 0 потерь | +| Остановка api-2 (после восстановления api-1) | Аналогично | 130 записей, 0 ошибок | 0.33 с / 0 потерь | | Перезапуск всего стенда | Данные и сессии сохраняются (volumes) | PASS: все данные и сессия сохранены | ~5 с перезапуск / 0 потерь | -| Rolling update api-1, затем api-2 под нагрузкой | Кратковременный рост p99; 0 потерь | 884 RPS, 0 ошибок из 53 067, p99=18.7 мс | 0 потерь | +| Rolling update api-1, затем api-2 под нагрузкой | Кратковременный рост p99; 0 потерь | 910 RPS, 0 ошибок из 54 625, p99=17.9 мс | 0 потерь | | Пересоздание реплики с новым IP без перезапуска nginx | nginx находит новый адрес | До `resolve` nginx слал запросы на старый IP и failover-тест падал; после `resolve` обе реплики снова в балансировке | ≤5 с (valid резолвера) | +| Живая api-1 без связи с PostgreSQL (`/health/ready`=503) | Реплика исключается из бизнес-маршрутизации | Через ~2–4 с `infra/nginx-health.sh` помечает api-1 `down`; 40 из 40 GET с прогретой сессией обслужила api-2; POST сообщений 20/20 успешны; POST /chats в первые секунды до исключения получили 503 без повтора и без создания чата; после восстановления api-1 вернулась в upstream | 0 потерь, лишних записей нет | ## Ограничения и следующие шаги @@ -187,12 +191,13 @@ docker compose down -v **Учебные упрощения:** - Один Docker-хост, нет multi-node failover -- Nginx open-source: только passive health checks (max_fails), нет active probes +- Nginx open-source не умеет активные health checks, поэтому они сделаны shell-скриптом в контейнере nginx (`nginx -s reload` при смене состояния). Если скрипт упадёт, upstream останется в последнем состоянии, и защитой будут только `max_fails` и проверка готовности внутри API +- В первые ~2–4 с после потери связи с БД не-идемпотентные POST (кроме сообщений), попавшие на неготовую реплику, получают 503 без повтора. Это сделано намеренно: nginx не знает, успела ли реплика что-то записать, и прозрачный повтор мог бы создать дубль - Idempotency-ключи хранятся в PostgreSQL — при высокой нагрузке advisory lock на одном ключе может стать bottleneck - HTTP без TLS (допустимо для локального стенда с синтетическими данными, lab7 добавит HTTPS) **Возможные улучшения:** - PostgreSQL streaming replication + automatic failover (Patroni) -- Nginx Plus или HAProxy для active health checks +- HAProxy или Nginx Plus со встроенными active health checks вместо скрипта - Idempotency через distributed lock (Valkey) + PostgreSQL для снижения contention - Multi-node deployment (Docker Swarm / Kubernetes) diff --git a/app/config.py b/app/config.py index 579620e..85eaceb 100644 --- a/app/config.py +++ b/app/config.py @@ -34,6 +34,8 @@ DB_STATEMENT_TIMEOUT_MS = _int("DB_STATEMENT_TIMEOUT_MS", 5000) DB_OP_TIMEOUT = _float("DB_OP_TIMEOUT", 6.0) REQUEST_TIMEOUT = _float("REQUEST_TIMEOUT", 8.0) DB_READY_TIMEOUT = _float("DB_READY_TIMEOUT", 1.5) +READY_CHECK_SECONDS = _float("READY_CHECK_SECONDS", 1.0) +READY_FAILURES = _int("READY_FAILURES", 2) CACHE_TIMEOUT = _float("CACHE_TIMEOUT", 0.2) MAX_INFLIGHT_REQUESTS = _int("MAX_INFLIGHT_REQUESTS", 64) MAX_BODY_BYTES = _int("MAX_BODY_BYTES", 65536) diff --git a/app/main.py b/app/main.py index c258cec..c847244 100644 --- a/app/main.py +++ b/app/main.py @@ -34,7 +34,7 @@ PAGE_SIZE = os.sysconf("SC_PAGE_SIZE") if hasattr(os, "sysconf") else 4096 db = Database() sessions = SessionStore(db) -state = {"draining": False, "inflight": 0, "rejected": {}} +state = {"draining": False, "ready": True, "inflight": 0, "rejected": {}} def rss_mb() -> float: @@ -68,6 +68,22 @@ async def sweeper() -> None: log.warning("idempotency cleanup skipped") +async def readiness_watch() -> None: + failures = 0 + while True: + if await db.ready(): + failures = 0 + if not state["ready"]: + state["ready"] = True + log.info("ready again: database reachable") + else: + failures += 1 + if failures >= config.READY_FAILURES and state["ready"]: + state["ready"] = False + log.warning("not ready: database unreachable, business requests get 503") + await asyncio.sleep(config.READY_CHECK_SECONDS) + + @asynccontextmanager async def lifespan(_app: FastAPI): previous = {} @@ -85,7 +101,7 @@ async def lifespan(_app: FastAPI): signal.signal(sig, on_signal) await db.open() await sessions.open() - task = asyncio.create_task(sweeper()) + tasks = [asyncio.create_task(sweeper()), asyncio.create_task(readiness_watch())] log.info( "started: instance=%s session_store=%s session_ttl=%d cache_ttl=%d pool=%d..%d max_inflight=%d max_body=%d idem_ttl=%d", config.INSTANCE_ID, config.SESSION_STORE, config.SESSION_TTL_SECONDS, config.SESSION_CACHE_TTL_SECONDS, @@ -93,7 +109,8 @@ async def lifespan(_app: FastAPI): config.IDEMPOTENCY_TTL_SECONDS, ) yield - task.cancel() + for task in tasks: + task.cancel() await sessions.close() await db.close() log.info("stopped: cache=%s rejected=%s", sessions.stats, state["rejected"]) @@ -110,6 +127,9 @@ async def guard(request: Request, call_next): if state["draining"] and request.url.path != "/health/live": count_rejection("draining") return error_body(rid, config.INSTANCE_ID, 503, "unavailable", "Сервер завершает работу", {"Retry-After": "1", "Connection": "close"}) + if not exempt and not state["ready"]: + count_rejection("not_ready") + return error_body(rid, config.INSTANCE_ID, 503, "unavailable", "Нет связи с базой данных", {"Retry-After": "1"}) if not exempt and state["inflight"] >= config.MAX_INFLIGHT_REQUESTS: count_rejection("inflight") return error_body(rid, config.INSTANCE_ID, 429, "rate_limited", "Слишком много одновременных запросов", {"Retry-After": "1"}) diff --git a/app/repo.py b/app/repo.py index dfa85d9..71f1bce 100644 --- a/app/repo.py +++ b/app/repo.py @@ -143,6 +143,13 @@ async def create_message_idempotent(conn, chat_id: str, sender_id: str, text: st lock_id = _idem_lock_id(sender_id, chat_id, idem_key) await conn.execute("SELECT pg_advisory_xact_lock(%s)", (lock_id,)) + cur = await conn.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, sender_id), + ) + if await cur.fetchone() is None: + return "not_member", None + cur = await conn.execute( "SELECT request_body_hash, response_json FROM idempotency_keys" " WHERE user_id = %s AND chat_id = %s AND key = %s", diff --git a/compose.yaml b/compose.yaml index ee77b12..dc4d088 100644 --- a/compose.yaml +++ b/compose.yaml @@ -32,10 +32,17 @@ x-api: &api-defaults services: nginx: image: nginx:1.27.3-alpine + command: ["/bin/sh", "/opt/nginx-health.sh"] + environment: + API_UPSTREAMS: ${API_UPSTREAMS:-api-1 api-2} + HEALTH_INTERVAL: "1" + HEALTH_FALL: "2" + HEALTH_RISE: "2" ports: - "127.0.0.1:8080:8080" volumes: - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + - ./infra/nginx-health.sh:/opt/nginx-health.sh:ro depends_on: api-1: condition: service_healthy diff --git a/evidence/failover_both.txt b/evidence/failover_both.txt index 27211b0..81900be 100644 --- a/evidence/failover_both.txt +++ b/evidence/failover_both.txt @@ -1,11 +1,11 @@ === Failover run 1 === python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080" Executing explicit failover hook; hook output suppressed to avoid leaking secrets. -{"observed_instances_before": 2, "successful_writes": 121, "failed_attempts": 0, "first_recovery_seconds": 1.463} +{"observed_instances_before": 2, "successful_writes": 130, "failed_attempts": 0, "first_recovery_seconds": 0.333} PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. === Failover run 2 (other replica) === python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080" Executing explicit failover hook; hook output suppressed to avoid leaking secrets. -{"observed_instances_before": 2, "successful_writes": 120, "failed_attempts": 1, "first_recovery_seconds": 1.455} +{"observed_instances_before": 2, "successful_writes": 130, "failed_attempts": 0, "first_recovery_seconds": 0.325} PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/review_scenarios.txt b/evidence/review_scenarios.txt new file mode 100644 index 0000000..a87f552 --- /dev/null +++ b/evidence/review_scenarios.txt @@ -0,0 +1,39 @@ +### Before fixes (commit fbb8916) +== 1. Idempotent replay after membership removal +PASS: first POST with key -> 201 (got 201) +PASS: history after removal -> 404 (got 404) +FAIL: replay with same key and body after removal -> 404 (got 201) +== 2. Live but not ready api-1 (no route to PostgreSQL) +FAIL: nginx active check marks api-1 down in upstream +PASS: Docker marks api-1 unhealthy +FAIL: 40 GET /users/me with warm session: served by not-ready api-1 = 20 +PASS: 40 GET /users/me: 200 responses = 40 +PASS: 20 POST messages during outage -> all 201 (got [201]) +== 3. LB does not transparently retry non-idempotent POST /chats +PASS: chats in DB (11) == 201 responses (11), POST /chats codes=[201, 201, 201, 201, 201, 201, 201, 201, 201, 201] +FAIL: nginx access log: 12 POST /chats, sent to two upstreams: 3 +FAIL: non_idempotent only on messages route: {'/': True} +PASS: api-1 healthy again after PostgreSQL route restored +PASS: api-1 returns to LB rotation +PASS: nginx upstream has no servers marked down +RESULT: FAIL (5) + +### After fixes +== 1. Idempotent replay after membership removal +PASS: first POST with key -> 201 (got 201) +PASS: history after removal -> 404 (got 404) +PASS: replay with same key and body after removal -> 404 (got 404) +== 2. Live but not ready api-1 (no route to PostgreSQL) +PASS: nginx active check marks api-1 down in upstream +PASS: Docker marks api-1 unhealthy +PASS: 40 GET /users/me with warm session: served by not-ready api-1 = 0 +PASS: 40 GET /users/me: 200 responses = 40 +PASS: 20 POST messages during outage -> all 201 (got [201]) +== 3. LB does not transparently retry non-idempotent POST /chats +PASS: chats in DB (9) == 201 responses (9), POST /chats codes=[503, 201, 503, 201, 201, 201, 201, 201, 201, 201] +PASS: nginx access log: 12 POST /chats, sent to two upstreams: 0 +PASS: non_idempotent only on messages route: {'~ ^/api/v1/chats/[^/]+/messages$': True, '/': False} +PASS: api-1 healthy again after PostgreSQL route restored +PASS: api-1 returns to LB rotation +PASS: nginx upstream has no servers marked down +RESULT: PASS diff --git a/evidence/rolling_load.json b/evidence/rolling_load.json index ed814db..694628a 100644 --- a/evidence/rolling_load.json +++ b/evidence/rolling_load.json @@ -4,14 +4,14 @@ "requested_duration_seconds": 60.0, "elapsed_seconds": 60.012, "concurrency": 4, - "successful_requests": 53067, + "successful_requests": 54625, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 884.267, + "successful_rps": 910.231, "successful_latency_ms": { - "p50": 3.936, - "p95": 6.112, - "p99": 18.691 + "p50": 3.848, + "p95": 5.7, + "p99": 17.851 }, "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." } diff --git a/evidence/rolling_update.txt b/evidence/rolling_update.txt index 58730af..52f2c8e 100644 --- a/evidence/rolling_update.txt +++ b/evidence/rolling_update.txt @@ -1,22 +1,21 @@ -=== rolling update === -14:22:50 recreate api-1 (old container df4ba056eb90) -14:22:56 api-1 healthy (new container 53a60bfc9073) -14:23:06 recreate api-2 (old container 6b53175a3693) -14:23:12 api-2 healthy (new container 047f8e956a97) +14:14:27 recreate api-1 (old container 572155b7facd) +14:14:33 api-1 healthy (new container a81474023dca) +14:14:43 recreate api-2 (old container 35c30c16ece5) +14:14:49 api-2 healthy (new container 1ac67f968005) { "lab": 3, "workload": "closed-loop POST messages; no automatic retries", "requested_duration_seconds": 60.0, "elapsed_seconds": 60.012, "concurrency": 4, - "successful_requests": 53067, + "successful_requests": 54625, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 884.267, + "successful_rps": 910.231, "successful_latency_ms": { - "p50": 3.936, - "p95": 6.112, - "p99": 18.691 + "p50": 3.848, + "p95": 5.7, + "p99": 17.851 }, "note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead." } diff --git a/infra/nginx-health.sh b/infra/nginx-health.sh new file mode 100644 index 0000000..692cab7 --- /dev/null +++ b/infra/nginx-health.sh @@ -0,0 +1,63 @@ +#!/bin/sh +set -u + +SERVERS="${API_UPSTREAMS:-api-1 api-2}" +INTERVAL="${HEALTH_INTERVAL:-1}" +FALL="${HEALTH_FALL:-2}" +RISE="${HEALTH_RISE:-2}" +OUT=/etc/nginx/upstream/servers.conf + +mkdir -p "$(dirname "$OUT")" + +var() { echo "$1" | tr -c 'a-zA-Z0-9\n' '_'; } + +render() { + any_up=0 + for s in $SERVERS; do + eval "[ \"\$up_$(var "$s")\" = 1 ]" && any_up=1 + done + for s in $SERVERS; do + mark="" + if [ "$any_up" = 1 ] && eval "[ \"\$up_$(var "$s")\" = 0 ]"; then + mark=" down" + fi + echo "server $s:8080 resolve max_fails=1 fail_timeout=10s$mark;" + done +} + +for s in $SERVERS; do + v=$(var "$s") + eval "up_$v=1 ok_$v=0 bad_$v=0" +done +render > "$OUT" + +watch() { + pending=0 + while sleep "$INTERVAL"; do + changed=0 + for s in $SERVERS; do + v=$(var "$s") + if wget -q -T 1 -O /dev/null "http://$s:8080/health/ready" 2>/dev/null; then + eval "ok_$v=\$((ok_$v + 1)) bad_$v=0" + if eval "[ \"\$up_$v\" = 0 ] && [ \"\$ok_$v\" -ge $RISE ]"; then + eval "up_$v=1"; changed=1; echo "health: $s ready, back in upstream" + fi + else + eval "bad_$v=\$((bad_$v + 1)) ok_$v=0" + if eval "[ \"\$up_$v\" = 1 ] && [ \"\$bad_$v\" -ge $FALL ]"; then + eval "up_$v=0"; changed=1; echo "health: $s not ready, marked down" + fi + fi + done + if [ "$changed" = 1 ]; then + render > "$OUT" + pending=1 + fi + if [ "$pending" = 1 ] && nginx -s reload 2>/dev/null; then + pending=0 + fi + done +} + +watch & +exec nginx -g 'daemon off;' diff --git a/infra/nginx.conf b/infra/nginx.conf index 10cd973..6277c25 100644 --- a/infra/nginx.conf +++ b/infra/nginx.conf @@ -9,8 +9,7 @@ http { upstream api { zone api 64k; - server api-1:8080 resolve max_fails=3 fail_timeout=10s; - server api-2:8080 resolve max_fails=3 fail_timeout=10s; + include /etc/nginx/upstream/servers.conf; keepalive 32; keepalive_timeout 4s; } @@ -24,19 +23,25 @@ http { server { listen 8080; + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_connect_timeout 1s; + proxy_read_timeout 10s; + proxy_send_timeout 5s; + proxy_next_upstream_tries 2; + proxy_next_upstream_timeout 5s; + + location ~ ^/api/v1/chats/[^/]+/messages$ { + proxy_pass http://api; + proxy_next_upstream error timeout http_502 http_503 non_idempotent; + } + location / { proxy_pass http://api; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_connect_timeout 1s; - proxy_read_timeout 10s; - proxy_send_timeout 5s; - proxy_next_upstream error timeout http_502 http_503 non_idempotent; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 5s; + proxy_next_upstream error timeout http_502 http_503; } } } diff --git a/infra/scaling/limits.yaml b/infra/scaling/limits.yaml index eceb45c..d5ebea5 100644 --- a/infra/scaling/limits.yaml +++ b/infra/scaling/limits.yaml @@ -1,8 +1,4 @@ services: - nginx: - volumes: - - ./infra/scaling/nginx-${REPLICAS:-2}.conf:/etc/nginx/nginx.conf:ro - api-1: deploy: resources: diff --git a/infra/scaling/nginx-1.conf b/infra/scaling/nginx-1.conf deleted file mode 100644 index 6fc95a1..0000000 --- a/infra/scaling/nginx-1.conf +++ /dev/null @@ -1,41 +0,0 @@ -worker_processes auto; - -events { - worker_connections 256; -} - -http { - resolver 127.0.0.11 valid=5s ipv6=off; - - upstream api { - zone api 64k; - server api-1:8080 resolve max_fails=3 fail_timeout=10s; - keepalive 32; - keepalive_timeout 4s; - } - - log_format main '$remote_addr - $upstream_addr [$time_local] ' - '"$request" $status $body_bytes_sent ' - '"$upstream_response_time" "$request_time"'; - - access_log /var/log/nginx/access.log main; - - server { - listen 8080; - - location / { - proxy_pass http://api; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_connect_timeout 1s; - proxy_read_timeout 10s; - proxy_send_timeout 5s; - proxy_next_upstream error timeout http_502 http_503 non_idempotent; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 5s; - } - } -} diff --git a/infra/scaling/nginx-2.conf b/infra/scaling/nginx-2.conf deleted file mode 100644 index 10cd973..0000000 --- a/infra/scaling/nginx-2.conf +++ /dev/null @@ -1,42 +0,0 @@ -worker_processes auto; - -events { - worker_connections 256; -} - -http { - resolver 127.0.0.11 valid=5s ipv6=off; - - upstream api { - zone api 64k; - server api-1:8080 resolve max_fails=3 fail_timeout=10s; - server api-2:8080 resolve max_fails=3 fail_timeout=10s; - keepalive 32; - keepalive_timeout 4s; - } - - log_format main '$remote_addr - $upstream_addr [$time_local] ' - '"$request" $status $body_bytes_sent ' - '"$upstream_response_time" "$request_time"'; - - access_log /var/log/nginx/access.log main; - - server { - listen 8080; - - location / { - proxy_pass http://api; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_connect_timeout 1s; - proxy_read_timeout 10s; - proxy_send_timeout 5s; - proxy_next_upstream error timeout http_502 http_503 non_idempotent; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 5s; - } - } -} diff --git a/infra/scaling/nginx-4.conf b/infra/scaling/nginx-4.conf deleted file mode 100644 index a0213fd..0000000 --- a/infra/scaling/nginx-4.conf +++ /dev/null @@ -1,44 +0,0 @@ -worker_processes auto; - -events { - worker_connections 256; -} - -http { - resolver 127.0.0.11 valid=5s ipv6=off; - - upstream api { - zone api 64k; - server api-1:8080 resolve max_fails=3 fail_timeout=10s; - server api-2:8080 resolve max_fails=3 fail_timeout=10s; - server api-3:8080 resolve max_fails=3 fail_timeout=10s; - server api-4:8080 resolve max_fails=3 fail_timeout=10s; - keepalive 32; - keepalive_timeout 4s; - } - - log_format main '$remote_addr - $upstream_addr [$time_local] ' - '"$request" $status $body_bytes_sent ' - '"$upstream_response_time" "$request_time"'; - - access_log /var/log/nginx/access.log main; - - server { - listen 8080; - - location / { - proxy_pass http://api; - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_connect_timeout 1s; - proxy_read_timeout 10s; - proxy_send_timeout 5s; - proxy_next_upstream error timeout http_502 http_503 non_idempotent; - proxy_next_upstream_tries 2; - proxy_next_upstream_timeout 5s; - } - } -} diff --git a/student-tests/scaling_experiment.sh b/student-tests/scaling_experiment.sh index 2d07629..4e8efc8 100755 --- a/student-tests/scaling_experiment.sh +++ b/student-tests/scaling_experiment.sh @@ -26,10 +26,10 @@ wait_instances() { for cfg in $CONFIGS; do IFS=: read -r label replicas cpus mem <<< "$cfg" - export REPLICAS=$replicas API_CPUS=$cpus API_MEM=$mem + apis=$(seq -f "api-%g" 1 "$replicas" | tr '\n' ' ') + export API_CPUS=$cpus API_MEM=$mem API_UPSTREAMS="${apis% }" files=(-f compose.yaml -f infra/scaling/limits.yaml) [ "$replicas" -eq 4 ] && files+=(-f infra/scaling/replicas-4.yaml) - apis=$(seq -f "api-%g" 1 "$replicas" | tr '\n' ' ') echo "=== $label: $replicas x ${cpus} CPU / $mem ===" docker compose "${files[@]}" up -d --force-recreate $apis >/dev/null 2>&1 @@ -63,7 +63,7 @@ for cfg in $CONFIGS; do | grep -E '" [45][0-9][0-9] |\[(error|warn)\]' > "$OUT/${label}_nginx_problems.txt" || true done -export REPLICAS=2 API_CPUS=0.50 API_MEM=256M +unset API_CPUS API_MEM API_UPSTREAMS docker compose -f compose.yaml -f infra/scaling/replicas-4.yaml rm -sf api-3 api-4 >/dev/null 2>&1 || true docker compose up -d --force-recreate api-1 api-2 nginx >/dev/null 2>&1 wait_instances 2 diff --git a/student-tests/test_review_scenarios.py b/student-tests/test_review_scenarios.py new file mode 100644 index 0000000..8d62d92 --- /dev/null +++ b/student-tests/test_review_scenarios.py @@ -0,0 +1,191 @@ +#!/usr/bin/env python3 +import argparse +import base64 +import json +import os +import re +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +BASE = "http://localhost:8080" +failures = [] + + +def check(cond, message): + print(("PASS: " if cond else "FAIL: ") + message) + if not cond: + failures.append(message) + + +def compose(*args, check_rc=True): + return subprocess.run(["docker", "compose", *args], cwd=ROOT, check=check_rc, + capture_output=True, text=True).stdout + + +def psql(sql): + return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", + "-tAc", sql).strip() + + +def api(method, path, body=None, headers=None): + h = {"Accept": "application/json"} + h.update(headers or {}) + data = None + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + req = urllib.request.Request(BASE + path, data=data, headers=h, method=method) + try: + resp = urllib.request.urlopen(req, timeout=10) + except urllib.error.HTTPError as e: + resp = e + raw = resp.read() + return resp.code, (json.loads(raw) if raw else None), resp.headers.get("X-Instance-Id", "") + + +def setup(): + pw = "Review-" + uuid.uuid4().hex[:12] + users = [] + for name in ("alice", "bob"): + username = "rv_%s_%s" % (name, uuid.uuid4().hex[:8]) + _, user, _ = api("POST", "/api/v1/users", {"username": username, "display_name": name, "password": pw}) + users.append((username, user)) + cred = base64.b64encode(("%s:%s" % (users[0][0], pw)).encode()).decode() + _, sess, _ = api("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred}) + auth = {"Authorization": "Bearer " + sess["token"]} + return users[0][1], users[1][1], auth + + +def new_chat(alice, bob, auth, title): + return api("POST", "/api/v1/chats", {"title": title, "member_ids": [alice["id"], bob["id"]]}, auth) + + +def scenario_replay_acl(alice, bob, auth): + print("== 1. Idempotent replay after membership removal") + _, chat, _ = new_chat(alice, bob, auth, "ACL replay") + key = uuid.uuid4().hex + path = "/api/v1/chats/%s/messages" % chat["id"] + code, _, _ = api("POST", path, {"text": "before removal"}, dict(auth, **{"Idempotency-Key": key})) + check(code == 201, "first POST with key -> 201 (got %s)" % code) + psql("DELETE FROM chat_members WHERE chat_id = '%s' AND user_id = '%s'" % (chat["id"], alice["id"])) + code, _, _ = api("GET", path, headers=auth) + check(code == 404, "history after removal -> 404 (got %s)" % code) + code, _, _ = api("POST", path, {"text": "before removal"}, dict(auth, **{"Idempotency-Key": key})) + check(code == 404, "replay with same key and body after removal -> 404 (got %s)" % code) + + +def api1_ip(): + cid = compose("ps", "-q", "api-1").strip() + return subprocess.run(["docker", "inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", cid], + check=True, capture_output=True, text=True).stdout.strip() + + +def api1_health(): + cid = compose("ps", "-q", "api-1").strip() + return subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], + capture_output=True, text=True).stdout.strip() + + +def break_api1_db(): + compose("exec", "-T", "-u", "root", "api-1", "sh", "-c", + "cp /etc/hosts /tmp/hosts.orig && echo '10.255.255.1 postgres' >> /etc/hosts") + psql("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE client_addr = '%s'" % api1_ip()) + + +def restore_api1_db(): + compose("exec", "-T", "-u", "root", "api-1", "sh", "-c", + "[ -f /tmp/hosts.orig ] && cat /tmp/hosts.orig > /etc/hosts", check_rc=False) + + +def wait_for(pred, timeout): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if pred(): + return True + time.sleep(1) + return False + + +def nginx_upstreams(): + return compose("exec", "-T", "nginx", "cat", "/etc/nginx/upstream/servers.conf", check_rc=False) + + +def scenario_unready_replica(alice, bob, auth): + print("== 2. Live but not ready api-1 (no route to PostgreSQL)") + for _ in range(4): + api("GET", "/api/v1/users/me", headers=auth) + since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + break_api1_db() + try: + before = int(psql("SELECT count(*) FROM chat_members WHERE user_id = '%s'" % alice["id"])) + codes = [] + for i in range(10): + codes.append(new_chat(alice, bob, auth, "no-retry %d" % i)[0]) + time.sleep(0.5) + + marked = wait_for(lambda: "api-1:8080 resolve max_fails=1 fail_timeout=10s down;" in nginx_upstreams(), 20) + check(marked, "nginx active check marks api-1 down in upstream") + became = wait_for(lambda: api1_health() == "unhealthy", 40) + check(became, "Docker marks api-1 unhealthy") + + served = [] + for _ in range(40): + code, _, inst = api("GET", "/api/v1/users/me", headers=auth) + served.append((code, inst)) + time.sleep(0.5) + by_api1 = sum(1 for _, inst in served if inst == "api-1") + ok = sum(1 for code, _ in served if code == 200) + check(by_api1 == 0, "40 GET /users/me with warm session: served by not-ready api-1 = %d" % by_api1) + check(ok == 40, "40 GET /users/me: 200 responses = %d" % ok) + + code, chat, _ = new_chat(alice, bob, auth, "messages during outage") + if code == 201: + msg_codes = [] + for i in range(20): + msg_codes.append(api("POST", "/api/v1/chats/%s/messages" % chat["id"], {"text": "m%d" % i}, + dict(auth, **{"Idempotency-Key": uuid.uuid4().hex}))[0]) + check(msg_codes.count(201) == 20, "20 POST messages during outage -> all 201 (got %s)" % sorted(set(msg_codes))) + after = int(psql("SELECT count(*) FROM chat_members WHERE user_id = '%s'" % alice["id"])) + + print("== 3. LB does not transparently retry non-idempotent POST /chats") + created = codes.count(201) + (1 if code == 201 else 0) + check(after - before == created, "chats in DB (%d) == 201 responses (%d), POST /chats codes=%s" + % (after - before, created, codes)) + log = compose("logs", "--no-log-prefix", "--since", since, "nginx") + chat_posts = [l for l in log.splitlines() if '"POST /api/v1/chats HTTP' in l] + retried = [l for l in chat_posts if re.search(r":8080, [0-9]", l)] + check(bool(chat_posts) and not retried, + "nginx access log: %d POST /chats, sent to two upstreams: %d" % (len(chat_posts), len(retried))) + conf = compose("exec", "-T", "nginx", "nginx", "-T") + blocks = re.findall(r"location ([^{]+)\{([^}]*)\}", conf) + policy = {loc.strip(): "non_idempotent" in body for loc, body in blocks} + check(policy.get("/") is False and policy.get("~ ^/api/v1/chats/[^/]+/messages$") is True, + "non_idempotent only on messages route: %s" % policy) + finally: + restore_api1_db() + back = wait_for(lambda: api1_health() == "healthy", 40) + check(back, "api-1 healthy again after PostgreSQL route restored") + seen = wait_for(lambda: any(api("GET", "/health/live")[2] == "api-1" for _ in range(6)), 20) + check(seen, "api-1 returns to LB rotation") + check("down" not in nginx_upstreams(), "nginx upstream has no servers marked down") + + +def main(): + global BASE + p = argparse.ArgumentParser() + p.add_argument("--base-url", default=BASE) + BASE = p.parse_args().base_url.rstrip("/") + alice, bob, auth = setup() + scenario_replay_acl(alice, bob, auth) + scenario_unready_replica(alice, bob, auth) + print("RESULT: %s" % ("PASS" if not failures else "FAIL (%d)" % len(failures))) + sys.exit(1 if failures else 0) + + +if __name__ == "__main__": + main()