forked from mtusi2026/mtusi2026lab3
реализация 3 лабы
This commit is contained in:
+3
-3
@@ -1,14 +1,14 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# init_local.py copies this template to local .env and creates secrets separately.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
HOST_PORT=8080
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
# File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Imported implementation stores shared sessions in Valkey.
|
||||
SESSION_STORE=valkey
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
# Contract requires at least 24 hours (86400 seconds).
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
|
||||
@@ -1,18 +1,31 @@
|
||||
## Лабораторная 3
|
||||
|
||||
Автор / группа: TODO
|
||||
Целевая оценка (3/4/5): TODO
|
||||
Трек 5, если заявлен: TODO
|
||||
Автор / группа: Савельев Иван, БВТ2304
|
||||
Целевая оценка (3/4/5): 4
|
||||
Трек 5, если заявлен: не заявлен
|
||||
|
||||
Что реализовано и что перенесено: TODO
|
||||
Команды запуска из чистого clone: TODO
|
||||
Результаты проверок и ссылка на REPORT.md: TODO
|
||||
Ограничения / известные ошибки: TODO
|
||||
Источники и использование ИИ: TODO
|
||||
Перенесены API, PostgreSQL, Valkey-сессии и миграции lab2. Добавлены HAProxy,
|
||||
две API-реплики, X-Instance-Id и общая атомарная идемпотентность сообщений.
|
||||
Миграции выполняются отдельным сервисом; реализованы остановка выбранной
|
||||
реплики и поочерёдная замена под нагрузкой.
|
||||
|
||||
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [ ] Контракт и публичные тесты не ослаблены.
|
||||
- [ ] make check и make test выполнены; приложен реальный вывод.
|
||||
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
Запуск: создать .venv, установить requirements.txt и requirements-dev.txt,
|
||||
выполнить ./scripts/start.sh и ./scripts/check.sh. Полный отдельный тестовый
|
||||
стенд: ./scripts/check-docker.sh.
|
||||
|
||||
Проверки: make check/validate, публичные smoke/persistence/failover,
|
||||
28 собственных тестов, SIGTERM, readiness при отказах зависимостей,
|
||||
отказ каждой API-реплики и поочерёдная замена с RPS/ошибками/временем восстановления.
|
||||
Команды, результаты и ограничения — в [REPORT.md](../REPORT.md),
|
||||
вывод и исходные счётчики — evidence/lab3-checks.txt и evidence/lab3-checks.json.
|
||||
|
||||
Ограничения: один хост; PostgreSQL, Valkey и LB без HA; возможны краткие
|
||||
переходные ошибки; миграции перед заменой должны быть обратно совместимыми.
|
||||
Использована помощь Codex; первичные источники перечислены в REPORT.md.
|
||||
|
||||
- [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
|
||||
- [x] Контракт и публичные тесты не ослаблены.
|
||||
- [x] make check и make test выполнены; приложен реальный вывод.
|
||||
- [x] Сценарии отказов/безопасности своего уровня воспроизведены.
|
||||
- [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
|
||||
- [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
|
||||
|
||||
@@ -15,13 +15,10 @@ jobs:
|
||||
- run: python -m venv .venv
|
||||
- run: .venv/bin/python -m pip install -r requirements.txt
|
||||
- run: ./scripts/check-docker.sh
|
||||
- run: ./scripts/research.sh
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: lab2-evidence
|
||||
name: lab3-evidence
|
||||
path: |
|
||||
evidence/docker-checks.txt
|
||||
evidence/research.txt
|
||||
evidence/research.json
|
||||
evidence/query-plans.json
|
||||
evidence/lab3-checks.txt
|
||||
evidence/lab3-checks.json
|
||||
|
||||
@@ -1,37 +1,181 @@
|
||||
# Отчёт — лабораторная 3
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Савельев Иван, БВТ2304.
|
||||
- Целевая оценка: **4**, весь уровень 3 и все пункты уровня 4. Треки оценки 5 не заявлены.
|
||||
- Решение: Docker Compose + HAProxy, две реплики FastAPI, общий PostgreSQL и Valkey.
|
||||
- Commit/PR: после публикации. Локальные проверки относятся к рабочим изменениям поверх `source_commit` из `evidence/lab3-checks.json`.
|
||||
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Engine с Compose v2, Python 3.11, Bash и make. Для демонстрации `demo.sh` также нужны curl и jq. Проверено на Docker Engine 29.0.1, Compose 2.40.3, macOS arm64. Команды выполнять из корня репозитория:
|
||||
|
||||
## Архитектура и решения
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||
./scripts/start.sh
|
||||
./scripts/check.sh
|
||||
./scripts/demo.sh
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab2, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
`start.sh` создаёт локальные `.env` и `secrets/`, собирает образ, поднимает PostgreSQL и Valkey, выполняет отдельный сервис `migrate`, запускает две API-реплики и HAProxy. API ожидают успешного завершения миграций. Скрипт возвращает управление после проверки обеих реплик через LB. Основной адрес — `http://localhost:8080`.
|
||||
|
||||
## Доказательства критериев
|
||||
Пароль PostgreSQL генерируется случайно в `secrets/postgres_password`; DSN и URL Valkey находятся в `secrets/database_url` и `secrets/cache_url`. Существующие значения не перезаписываются. Каталог имеет права 0700, файлы — 0444 для чтения пользователем контейнера 10001. `.env`, `secrets/`, `.venv` исключены из Git и Docker build context. `.env.example` содержит настройки и пути, без значений секретов.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Переменная | Использование |
|
||||
| --- | --- |
|
||||
| APP_HOST, APP_PORT | Адрес API внутри контейнера: 0.0.0.0:8080 |
|
||||
| HOST_PORT | Порт единственного публичного входа HAProxy на 127.0.0.1, по умолчанию 8080 |
|
||||
| API_REPLICAS | Количество реплик сервиса api, по умолчанию 2; конфигурация LB содержит 10 мест |
|
||||
| SESSION_STORE | valkey, общее хранилище серверных сессий |
|
||||
| SESSION_TTL_SECONDS | TTL новой сессии, по умолчанию 3600; рестарт TTL не продлевает |
|
||||
| DATABASE_URL_FILE, CACHE_URL_FILE | Пути к Docker secrets |
|
||||
| IDEMPOTENCY_TTL_SECONDS | Срок результата повтора, по умолчанию 86400, меньше 24 часов запрещено |
|
||||
| APP_ENV | Учебная метка окружения; поведение приложения не переключает |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Если порт занят, например стендом lab2:
|
||||
|
||||
## Эксперименты и отказы
|
||||
```sh
|
||||
HOST_PORT=8081 ./scripts/start.sh
|
||||
BASE_URL=http://localhost:8081 ./scripts/check.sh
|
||||
```
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Для дальнейших команд с нестандартным портом сохранить `HOST_PORT=8081` в `.env` или передавать его в окружении. Для HTTP-проверок передавать соответствующий `BASE_URL`.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
```sh
|
||||
docker compose ps -a
|
||||
docker compose logs --tail 30 api lb
|
||||
./scripts/restart.sh # API, PostgreSQL, Valkey и LB; volumes сохраняются
|
||||
./scripts/stop.sh # удаление контейнеров и сети с сохранением volumes
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
# Только для намеренного удаления учебных данных текущего Compose project:
|
||||
docker compose down --volumes
|
||||
```
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Compose project `mtusi-lab3` отделён от lab2. Тестовый сценарий использует своё случайное имя и порт; в конце удаляет только свои тестовые контейнеры и volumes.
|
||||
|
||||
## Архитектура и перенос из lab2
|
||||
|
||||
```text
|
||||
Клиент → HAProxy :8080 → api × 2 → PostgreSQL (данные и результаты повторов)
|
||||
↘ Valkey (общие Bearer-сессии)
|
||||
Отдельный migrate → PostgreSQL; завершается до первого запуска API
|
||||
```
|
||||
|
||||
Сохранены пользователи, Argon2id, Basic-вход, Bearer-сессии с TTL и отзывом, чаты, проверки доступа, сообщения, единые ошибки, X-Request-Id и keyset-пагинация. PostgreSQL остаётся источником истины для данных. Valkey хранит SHA-256 токена → пользователя и время окончания, с AOF `appendfsync always`, `noeviction` и постоянным volume. Подтверждённые данные и действующие сессии переживают обычный рестарт. Локального состояния, от которого зависит корректность, в API нет.
|
||||
|
||||
Добавлены `X-Instance-Id`, общая идемпотентность, LB и управление репликами. `X-Instance-Id` равен hostname контейнера и стабилен в течение жизни процесса. В доказательствах он сопоставлен с настоящим container ID; заголовок не подменяется балансировщиком. Любой ответ, сформированный API, включая health и ошибки, содержит оба служебных заголовка.
|
||||
|
||||
HAProxy использует round robin без sticky session. `server-template` получает адреса масштабируемого сервиса `api` из Docker DNS `127.0.0.11`; записи переопрашиваются, устаревшие адреса удаляются. `hold valid/obsolete=1s`, повтор разрешения — 1s. Новые IP после пересоздания обнаруживаются без рестарта LB. `wait-ready.sh` проверяет Docker health всех работающих API и наблюдает каждую через LB.
|
||||
|
||||
API не публикуют порты на хост, работают от UID/GID 10001, без volumes данных и без `container_name`. Только LB публикует порт. Секрет PostgreSQL доступен БД; DSN — API и мигратору; URL Valkey — только API. LB не получает секреты. PostgreSQL и Valkey используют отдельные именованные volumes.
|
||||
|
||||
| Контейнер | CPU | RAM |
|
||||
| --- | ---: | ---: |
|
||||
| Каждый API | 1 | 256 MiB |
|
||||
| HAProxy | 0.5 | 64 MiB |
|
||||
| PostgreSQL | 1 | 512 MiB |
|
||||
| Valkey | 0.5 | 128 MiB |
|
||||
| Одноразовый migrate | 1 | 256 MiB |
|
||||
|
||||
## Готовность, таймауты и SIGTERM
|
||||
|
||||
`/health/live` проверяет жизнь процесса. `/health/ready` проверяет PostgreSQL и Valkey: обе зависимости критичны для обязательного синхронного пути. При отказе любой зависимости live остаётся 200, ready становится 503. При старте API также проверяет наличие и checksum всех миграций, не выполняя DDL.
|
||||
|
||||
HAProxy проверяет `/health/ready` каждую 1 секунду. Два последовательных неуспеха исключают backend (`fall 2`), два успеха возвращают (`rise 2`). Таймаут подключения — 1s, ответа healthcheck — 1s. Консервативная верхняя оценка обнаружения отказа по этим настройкам — **6 секунд**: ожидание ближайшей проверки, два подключения/ответа и интервал между ними; задержки планирования ОС в оценку не входят. Отказ с немедленным connection refused обычно обнаруживается быстрее. Это укладывается в требование восстановления за 10 секунд.
|
||||
|
||||
Остальные таймауты HAProxy: server 8s, client 10s, чтение HTTP-заголовков 5s. `retries 1` относится к установлению backend-соединения; повторов уже отправленных HTTP POST по статусам не включено. Клиент повторяет неопределённый POST сообщения с исходным ключом.
|
||||
|
||||
API является PID 1. При SIGTERM Uvicorn прекращает приём новых соединений, даёт текущим запросам до 5 секунд и закрывает пул. Docker даёт 8 секунд до принудительного завершения. Проверка с незавершённым телом POST измеряет отказ новых соединений и выход до 8 секунд; проверяется `Application shutdown complete`, exit code 0 и отсутствие OOM. Переходные ошибки до исключения backend из LB учитываются в нагрузочном сценарии.
|
||||
|
||||
## Общая идемпотентность
|
||||
|
||||
Для POST сообщения требуется ровно один `Idempotency-Key` по шаблону `[A-Za-z0-9._:-]{1,128}`. Отсутствие и неверный формат дают 400. Область ключа — пользователь, POST, путь конкретного чата, ключ. Метод и тип пути фиксированы единственным обработчиком; таблица хранит `(user_id, chat_id, key)` как первичный ключ.
|
||||
|
||||
В одной транзакции PostgreSQL:
|
||||
|
||||
1. Проверяется членство в чате; сессия повторно проверяется middleware при каждом запросе.
|
||||
2. Берётся транзакционная advisory lock для области ключа. Она общая для всех реплик; возможная коллизия хеша лишь сериализует независимые запросы.
|
||||
3. При действующем результате сравнивается значение `text`, а не исходные JSON-байты. Совпадение возвращает прежний 201 и Message; другой текст даёт 409.
|
||||
4. Для нового или истёкшего ключа создаются сообщение и строка результата с TTL, затем выполняется COMMIT. Ответ отправляется после COMMIT.
|
||||
|
||||
Порядок/пробелы JSON и Unicode escaping не меняют результат. В контракте lab3 поле сообщения только `text`; вложения появляются с lab4. Ключи разных пользователей и чатов независимы. 5xx не сохраняется как результат; откат убирает и сообщение, и строку идемпотентности. При обрыве после COMMIT повтор на другой реплике читает прежнее сообщение. Результаты хранятся минимум 24 часа, переживают рестарт и замену API. Истёкшая строка заменяется при следующем использовании того же ключа; сообщения остаются в истории.
|
||||
|
||||
## Миграции и поочерёдная замена
|
||||
|
||||
`migrate` — один отдельный Compose-service, выполняющий SQL под общей advisory lock и сохраняющий SHA-256 версий. API только проверяют схему. Ручная команда — `./scripts/migrate.sh`; повтор безопасен и не создаёт повторных данных.
|
||||
|
||||
Миграция `001_initial.sql` не изменялась. `002_message_idempotency.sql` только добавляет таблицу и не изменяет существующие поля. Она совместима с уже работающей версией приложения. При последующих изменениях разрешены только обратно совместимые добавления перед rolling update; удаление/переименование полей потребует отдельного перехода или окна обслуживания. Автоматическая совместимость произвольных миграций не заявляется.
|
||||
|
||||
```sh
|
||||
./scripts/rolling-update.sh
|
||||
```
|
||||
|
||||
Скрипт сначала собирает образ и запускает миграции, затем для каждого исходного API-контейнера: проверяет наличие другой здоровой реплики, останавливает и удаляет выбранный контейнер, создаёт только недостающую реплику через `up --no-deps --no-recreate --scale`, ждёт её готовности через LB и переходит к следующей. PostgreSQL, Valkey и HAProxy не перезапускаются. Это поочерёдная замена с сохранением хотя бы одной готовой реплики; краткие переходные ошибки измеряются, нулевые ошибки не обещаются.
|
||||
|
||||
## Команды проверки и доказательства
|
||||
|
||||
```sh
|
||||
make check validate PYTHON=.venv/bin/python
|
||||
./scripts/check.sh
|
||||
make test-persistence PYTHON=.venv/bin/python ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover PYTHON=.venv/bin/python ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose start api
|
||||
./scripts/wait-ready.sh
|
||||
|
||||
# Полный воспроизводимый прогон в отдельном тестовом стенде:
|
||||
./scripts/check-docker.sh
|
||||
```
|
||||
|
||||
Для ручной остановки конкретной реплики задать `TARGET_INSTANCE_ID` из её `X-Instance-Id` и вызвать `./scripts/stop-one.sh`. Скрипт сопоставляет hostname контейнерам только текущего Compose project, требует минимум две работающие реплики, останавливает ровно выбранную и оставляет её остановленной. `docker compose ps -a` показывает фактическое состояние. Восстановление — `docker compose start api` и `./scripts/wait-ready.sh`. Полный сценарий последовательно повторяет отказ для каждой из двух реплик, восстанавливая предыдущую.
|
||||
|
||||
| Критерий ТЗ | Проверка | Доказательство |
|
||||
| --- | --- | --- |
|
||||
| Воспроизводимый стенд, две реальные API-реплики и единый вход | start.sh, Docker inspect, общий Compose-service api | compose.yaml; containers в lab3-checks.json |
|
||||
| Общая сессия, запросы через разные реплики | 20 параллельных повторов с одним Bearer-токеном | test_parallel_replay_across_replicas; lab3-checks.txt |
|
||||
| Публичный контракт, включая ошибки и идемпотентность | make test, 28 собственных тестов | lab3-checks.txt |
|
||||
| Рестарт всех компонентов, прежняя сессия и сообщения | make test-persistence, StartedAt до/после; повтор ключа после рестарта | persistence в lab3-checks.json |
|
||||
| Публичный отказ одной выбранной реплики, восстановление ≤10s | make test-failover, реально остановленный container ID | public_failover; lab3-checks.txt |
|
||||
| Отказ каждой API-реплики, чтения и записи под нагрузкой | Два отдельных load_action, восстановление предыдущей между ними | failovers в lab3-checks.json |
|
||||
| Параллельная общая идемпотентность, нет дублей | 20 одновременных запросов через ≥2 реплики; сверка истории после отказов | test_idempotency.py; duplicate_messages=0 |
|
||||
| Readiness, таймауты и SIGTERM | Отказ PostgreSQL/Valkey; незавершённый запрос + TERM | dependency_readiness и sigterm |
|
||||
| CPU/RAM-лимиты, отсутствие обхода LB и container_name | Проверки Docker inspect для всех контейнеров | containers; compose.yaml |
|
||||
| Поочерёдная замена под нагрузкой | rolling-update.sh, новые ID обоих API; неизменный StartedAt остальных | rolling_update в lab3-checks.json |
|
||||
| Отдельные согласованные миграции | Одноразовый сервис, повторный запуск дважды без изменения данных | lab3-checks.txt; миграции 001/002 |
|
||||
|
||||
Файлы текущего прогона: [evidence/lab3-checks.txt](evidence/lab3-checks.txt) и [evidence/lab3-checks.json](evidence/lab3-checks.json). Идентификаторы контейнеров, ресурсы, времена, ошибки и посекундные исходные счётчики сохранены без паролей и токенов. `evidence/docker-checks.txt`, `research.*`, `query-plans.json` и `REPORT.lab2.md` относятся ко второй лабораторной.
|
||||
|
||||
## Измерения
|
||||
|
||||
Дата прогона — 29.10.2026. Среда: macOS arm64, Docker VM Linux aarch64, 10 CPU, 8217448448 байт RAM. Лимиты контейнеров приведены выше. Профиль — четыре закрытых клиента: POST сообщения и GET истории с существующими сессиями, пауза 50ms между парами запросов. Для неопределённого POST сохраняются прежние ключ и тело. При отказе нагрузка длится 15 секунд после начала воздействия; при замене — весь action и минимум 3 секунды после. Перед воздействием есть 1 секунда прогрева, которая входит в общие счётчики.
|
||||
|
||||
Численные результаты последнего успешного прогона приведены ниже.
|
||||
|
||||
| Воздействие | Длительность, с | Успешные HTTP/с | Ошибки | Макс. пауза POST / GET, с | Потеря подтверждённых / дубли |
|
||||
| --- | ---: | ---: | ---: | --- | --- |
|
||||
| Остановка 7f6a80b69e32 | 16.009 | 98.44 | 4 | 1.957 / 2.004 | 0 / 0 |
|
||||
| Остановка f973eaec4d52 | 16.015 | 98.28 | 4 | 2.006 / 2.006 | 0 / 0 |
|
||||
| Поочерёдная замена обоих API | 23.774 | 89.64 | 11 | 1.059 / 2.034 | 0 / 0 |
|
||||
|
||||
SIGTERM с незавершённым POST: новые соединения перестали приниматься за 0.167 с, выход за 5.393 с, exit code 0, OOM отсутствует. При остановке Valkey и PostgreSQL по отдельности подтверждены API live=200, API ready=503 и LB ready=503; после восстановления прежний токен продолжил работать.
|
||||
|
||||
RPS считается по всем успешным HTTP-запросам чтения и записи за полную длительность сценария; ошибки считаются отдельно. «Первый успех» показывает продолжение обслуживания после начала action, а максимальный промежуток между успешными запросами дополнительно показывает паузы во всём сценарии. После каждого воздействия проверяются все подтверждённые сообщения, исходное сообщение до отказа, отсутствие повторяющихся ID/текстов и работа прежней сессии.
|
||||
|
||||
Это короткие проверки отказоустойчивости для оценки 4. Нагрузка закрытая, присутствует coordinated omission; p50/p95 относятся только к успешным ответам. Предельная производительность и масштабирование 1/2/4 здесь не исследуются.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Выдерживается отказ одной API-реплики при работающей другой. PostgreSQL, Valkey, HAProxy и сам хост остаются точками отказа; отказ узла и HA хранилищ не заявлены. Остановка БД или Valkey делает обязательный API неготовым. При полном рестарте допустимо окно недоступности, данные и действующие сессии сохраняются в volumes. Удаление volumes намеренно уничтожает данные.
|
||||
|
||||
Нет автоматического TTL-удаления всех давно неиспользуемых ключей идемпотентности: они удаляются при повторном использовании ключа. Срок сессий зависит от часов; keyset-пагинация сохраняет ограничения lab2 при конкурентных записях и переводе часов. Поочерёдная замена останавливается при отсутствии здоровой резервной реплики, автоматический rollback образа не реализован.
|
||||
|
||||
## Источники
|
||||
|
||||
- [Docker Compose services, replicas, secrets и depends_on](https://docs.docker.com/reference/compose-file/services/).
|
||||
- [Compose up: scale и no-recreate](https://docs.docker.com/reference/cli/docker/compose/up/).
|
||||
- [HAProxy: DNS и server-template](https://www.haproxy.com/documentation/haproxy-configuration-tutorials/proxying-essentials/dns-resolution/).
|
||||
- [HAProxy: active health checks, inter/fall/rise](https://www.haproxy.com/documentation/haproxy-configuration-tutorials/reliability/health-checks/).
|
||||
- [PostgreSQL: advisory locks](https://www.postgresql.org/docs/17/explicit-locking.html#ADVISORY-LOCKS).
|
||||
- [Uvicorn: graceful shutdown timeout](https://uvicorn.dev/settings/#timeouts).
|
||||
|
||||
Стек приложения и закреплённые зависимости перенесены из lab2 (`requirements.txt`): Python 3.11.15, FastAPI 0.142.4, Uvicorn 0.54.0, Psycopg 3.3.6, PostgreSQL 17.6, Valkey 8.1.3; добавлен HAProxy 3.2.6-alpine. README задания, OpenAPI и публичные tests не изменялись. CI запускает контрактные и Docker-проверки; успешный удалённый запуск GitHub Actions без отдельного результата не заявлен.
|
||||
|
||||
+35
-6
@@ -1,5 +1,12 @@
|
||||
name: mtusi-lab3
|
||||
|
||||
x-application: &application
|
||||
image: mtusi-messenger:lab3
|
||||
build: .
|
||||
env_file: .env
|
||||
cpus: 1
|
||||
mem_limit: 256m
|
||||
|
||||
x-postgres: &postgres
|
||||
image: postgres:17.6-bookworm
|
||||
environment:
|
||||
@@ -33,19 +40,41 @@ services:
|
||||
retries: 30
|
||||
|
||||
api:
|
||||
image: mtusi-messenger:lab3
|
||||
build: .
|
||||
env_file: .env
|
||||
<<: *application
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
environment:
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
secrets: [database_url, cache_url]
|
||||
ports: ["127.0.0.1:${HOST_PORT:-8080}:8080"]
|
||||
cpus: 1
|
||||
mem_limit: 256m
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
valkey: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
stop_grace_period: 8s
|
||||
|
||||
migrate:
|
||||
<<: *application
|
||||
command: ["python", "-m", "src.migrate"]
|
||||
secrets: [database_url]
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
|
||||
lb:
|
||||
image: haproxy:3.2.6-alpine
|
||||
ports: ["127.0.0.1:${HOST_PORT:-8080}:8080"]
|
||||
volumes: [./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
|
||||
cpus: 0.5
|
||||
mem_limit: 64m
|
||||
depends_on:
|
||||
api: {condition: service_healthy}
|
||||
stop_grace_period: 10s
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/health/ready"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
|
||||
postgres-restore:
|
||||
<<: *postgres
|
||||
|
||||
+8
-5
@@ -1,7 +1,7 @@
|
||||
# Схема и транзакции lab2
|
||||
# Схема и транзакции
|
||||
|
||||
Архитектура: HTTP → FastAPI → PostgreSQL; Bearer-сессии находятся в Valkey.
|
||||
Выбран трек 2 на оценку 5: план запроса и восстановление.
|
||||
Лабораторная 3, оценка 4: HTTP → HAProxy → FastAPI × 2 → PostgreSQL;
|
||||
Bearer-сессии находятся в общем Valkey. Схема lab2 сохранена.
|
||||
|
||||
| Таблица PostgreSQL | Назначение и ограничения |
|
||||
| --- | --- |
|
||||
@@ -10,13 +10,16 @@
|
||||
| chat_members | PK (chat_id, user_id); FK на chats и users |
|
||||
| messages | UUID PK; FK chat_id на chats; составной FK (chat_id, sender_id) на chat_members; text; created_at timestamptz |
|
||||
| schema_migrations | Имя и SHA-256 применённой SQL-миграции; время применения |
|
||||
| message_idempotency | PK (user_id, chat_id, key); FK на пользователя, чат и сообщение; request_text; expires_at |
|
||||
|
||||
Индексы: users(username) создаётся UNIQUE-ограничением; chat_members(user_id, chat_id) нужен для списка чатов пользователя; messages(chat_id, created_at, id) нужен для истории с keyset cursor. PK служат индексами поиска по UUID.
|
||||
|
||||
Каждая операция хранилища выполняется в одной транзакции: контекст соединения Psycopg делает COMMIT при успехе и ROLLBACK при исключении. Создание чата сначала вставляет chats, затем участников. Неизвестный участник вызывает FK violation и откатывает весь чат. Проверка уникальности username выполняется ограничением БД, включая конкурентные запросы. Создание сообщения проверяет доступ и записывает сообщение в одной транзакции; составной FK дополнительно запрещает автора вне чата.
|
||||
|
||||
Миграции выполняются под advisory transaction lock. Повторное применение пропускает уже записанную версию, изменение применённого SQL выявляется по checksum. Схема и запись версии фиксируются вместе.
|
||||
Идемпотентная отправка проверяет членство, берёт общую транзакционную advisory lock для пользователя/метода/пути/ключа и проверяет предыдущий результат. Тот же text даёт прежнее Message, другой — 409. Сообщение и строка message_idempotency фиксируются одной транзакцией; при откате не сохраняется ни одно. TTL не меньше 24 часов. Истёкшая строка заменяется при повторном использовании ключа; старое сообщение сохраняется.
|
||||
|
||||
Миграции выполняет отдельный одноразовый Compose-service migrate под advisory transaction lock. API только проверяют версии и checksum. Повторное применение пропускает уже записанную версию, изменение применённого SQL выявляется по checksum. Схема и запись версии фиксируются вместе. Миграция 002 только добавляет таблицу; существующая 001 не изменялась.
|
||||
|
||||
Valkey — источник истины только для сессий: ключ session:SHA256(token), значение — user_id и абсолютное expires_at, TTL задаётся SESSION_TTL_SECONDS. Сырой токен выдаётся клиенту один раз и не записывается в логи. Включены AOF, appendfsync always и именованный volume. Logout удаляет ключ; исчезнувшая или просроченная сессия даёт 401. При недоступности Valkey — 503 без обхода аутентификации. При потере PostgreSQL — 503. /health/live остаётся доступным, /health/ready проверяет оба сервиса.
|
||||
|
||||
Для трека 5 отдельно исследуются индекс только по chat_id и составной индекс на одинаковых 100000 сообщениях с распределением 70000/20000/9000/1000. Измеряются чтение страниц, стоимость записи и размер индекса. Backup восстанавливается в другой контейнер PostgreSQL с новым volume; сравниваются счётчики, выбранные записи и контрольная сумма всей истории.
|
||||
Исследование индекса и backup/restore в research/ перенесено из lab2. Для оценки 4 текущей лабораторной оно не требуется; результаты отказов и замены реплик описаны в [REPORT.md](../REPORT.md).
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,403 @@
|
||||
Command: ./scripts/check-docker.sh; project: lab3-check-a31f544685
|
||||
Docker: 29.0.1 aarch64 CPUs=10 RAM=8217448448
|
||||
Local .env and secrets are ready; values are not printed
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.05kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [migrate internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 733B done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [api internal] load metadata for docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [api internal] load .dockerignore
|
||||
#4 transferring context: 167B done
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [migrate internal] load build context
|
||||
#5 transferring context: 809B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [migrate 1/8] FROM docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3
|
||||
#6 resolve docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [migrate 2/8] WORKDIR /app
|
||||
#7 CACHED
|
||||
|
||||
#8 [migrate 3/8] COPY requirements.txt .
|
||||
#8 CACHED
|
||||
|
||||
#9 [migrate 4/8] RUN python -m pip install --no-cache-dir -r requirements.txt && python -m pip check
|
||||
#9 CACHED
|
||||
|
||||
#10 [migrate 6/8] COPY src/ ./src/
|
||||
#10 CACHED
|
||||
|
||||
#11 [migrate 7/8] COPY migrations/ ./migrations/
|
||||
#11 CACHED
|
||||
|
||||
#12 [migrate 5/8] RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home app
|
||||
#12 CACHED
|
||||
|
||||
#13 [migrate 8/8] COPY research/ ./research/
|
||||
#13 CACHED
|
||||
|
||||
#14 [api] exporting to image
|
||||
#14 exporting layers done
|
||||
#14 exporting manifest sha256:06163e45d3676c7cf4f7a1c7bfe108ed3b98559ebb485c7a09d1e87e6f418d17 done
|
||||
#14 exporting config sha256:3fed7460e9510eef7b2928f8d600d06d5d65329f74d820beac13809476b11398 done
|
||||
#14 exporting attestation manifest sha256:352319cde788733f2f237a2a78204630c542e7ca906cff14c902046e8c1d2e5b 0.0s done
|
||||
#14 exporting manifest list sha256:848e0c76f1678f35dd1b483e7c54552466999551ba7e77c0062bf346671e2902 done
|
||||
#14 naming to docker.io/library/mtusi-messenger:lab3 done
|
||||
#14 unpacking to docker.io/library/mtusi-messenger:lab3 done
|
||||
#14 DONE 0.1s
|
||||
|
||||
#15 [migrate] exporting to image
|
||||
#15 exporting layers done
|
||||
#15 exporting manifest sha256:a59568d34e2c5e8b4d23308342601fdaf8c07e78ec3065878679a067c082e952 done
|
||||
#15 exporting config sha256:b67b805ba1b7dd90f0a3e8444455488fe8c7f4118f14d671501dd63e85b59c97 done
|
||||
#15 exporting attestation manifest sha256:b1853c07ddac46c4b398b475052f334aa2753c2fe971e0e4fb2517b0e3e13656 0.0s done
|
||||
#15 exporting manifest list sha256:eff1abdd662eb60e2741e6ce6b8f364467d2817dafeef9754518247124a780eb done
|
||||
#15 naming to docker.io/library/mtusi-messenger:lab3 done
|
||||
#15 unpacking to docker.io/library/mtusi-messenger:lab3 done
|
||||
#15 DONE 0.1s
|
||||
|
||||
#16 [api] resolving provenance for metadata file
|
||||
#16 DONE 0.0s
|
||||
|
||||
#17 [migrate] resolving provenance for metadata file
|
||||
#17 DONE 0.0s
|
||||
mtusi-messenger:lab3 Built
|
||||
mtusi-messenger:lab3 Built
|
||||
Network lab3-check-a31f544685_default Creating
|
||||
Network lab3-check-a31f544685_default Created
|
||||
Volume lab3-check-a31f544685_postgres_data Creating
|
||||
Volume lab3-check-a31f544685_postgres_data Created
|
||||
Volume lab3-check-a31f544685_valkey_data Creating
|
||||
Volume lab3-check-a31f544685_valkey_data Created
|
||||
Container lab3-check-a31f544685-valkey-1 Creating
|
||||
Container lab3-check-a31f544685-postgres-1 Creating
|
||||
Container lab3-check-a31f544685-valkey-1 Created
|
||||
Container lab3-check-a31f544685-postgres-1 Created
|
||||
Container lab3-check-a31f544685-migrate-1 Creating
|
||||
Container lab3-check-a31f544685-migrate-1 Created
|
||||
Container lab3-check-a31f544685-api-2 Creating
|
||||
Container lab3-check-a31f544685-api-1 Creating
|
||||
Container lab3-check-a31f544685-api-1 Created
|
||||
Container lab3-check-a31f544685-api-2 Created
|
||||
Container lab3-check-a31f544685-lb-1 Creating
|
||||
Container lab3-check-a31f544685-lb-1 Created
|
||||
Container lab3-check-a31f544685-valkey-1 Starting
|
||||
Container lab3-check-a31f544685-postgres-1 Starting
|
||||
Container lab3-check-a31f544685-valkey-1 Started
|
||||
Container lab3-check-a31f544685-postgres-1 Started
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Starting
|
||||
Container lab3-check-a31f544685-migrate-1 Started
|
||||
Container lab3-check-a31f544685-migrate-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Healthy
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Exited
|
||||
Container lab3-check-a31f544685-api-2 Starting
|
||||
Container lab3-check-a31f544685-api-2 Started
|
||||
Container lab3-check-a31f544685-api-1 Starting
|
||||
Container lab3-check-a31f544685-api-1 Started
|
||||
Container lab3-check-a31f544685-api-2 Waiting
|
||||
Container lab3-check-a31f544685-api-1 Waiting
|
||||
Container lab3-check-a31f544685-api-2 Healthy
|
||||
Container lab3-check-a31f544685-api-1 Healthy
|
||||
Container lab3-check-a31f544685-lb-1 Starting
|
||||
Container lab3-check-a31f544685-lb-1 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
PASS: 2 real API containers, CPU/RAM limits, API non-root and no public ports; only LB published
|
||||
Проверяем сервер: http://127.0.0.1:58474
|
||||
/Users/vanek/Desktop/VNPlabs/VNPlab3/mtusi2026lab3/.venv/bin/python scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
/Users/vanek/Desktop/VNPlabs/VNPlab3/mtusi2026lab3/.venv/bin/python tests/smoke.py --base-url "http://127.0.0.1:58474"
|
||||
PASS: lab3 public API scenario; infrastructure and grading evidence remain separate.
|
||||
test_chat_access (test_api.ApiTests.test_chat_access) ... ok
|
||||
test_chat_pagination_and_cursor_owner (test_api.ApiTests.test_chat_pagination_and_cursor_owner) ... ok
|
||||
test_cursor_cannot_be_used_for_another_chat_or_changed (test_api.ApiTests.test_cursor_cannot_be_used_for_another_chat_or_changed) ... ok
|
||||
test_default_page_size (test_api.ApiTests.test_default_page_size) ... ok
|
||||
test_duplicate_username (test_api.ApiTests.test_duplicate_username) ... ok
|
||||
test_framework_errors_and_request_ids (test_api.ApiTests.test_framework_errors_and_request_ids) ... ok
|
||||
test_identification_and_authentication_order (test_api.ApiTests.test_identification_and_authentication_order) ... ok
|
||||
test_invalid_chat_members (test_api.ApiTests.test_invalid_chat_members) ... ok
|
||||
test_invalid_chat_title (test_api.ApiTests.test_invalid_chat_title) ... ok
|
||||
test_invalid_limits_and_cursors (test_api.ApiTests.test_invalid_limits_and_cursors) ... ok
|
||||
test_invalid_message_fields (test_api.ApiTests.test_invalid_message_fields) ... ok
|
||||
test_invalid_user_fields (test_api.ApiTests.test_invalid_user_fields) ... ok
|
||||
test_malformed_json_and_encoding (test_api.ApiTests.test_malformed_json_and_encoding) ... ok
|
||||
test_message_pagination_and_changing_limit (test_api.ApiTests.test_message_pagination_and_changing_limit) ... ok
|
||||
test_unicode_and_text_preservation (test_api.ApiTests.test_unicode_and_text_preservation) ... ok
|
||||
test_wrong_content_type (test_api.ApiTests.test_wrong_content_type) ... ok
|
||||
test_simultaneous_registration_of_one_username (test_concurrency.ConcurrencyTests.test_simultaneous_registration_of_one_username) ... ok
|
||||
test_ten_clients_send_one_hundred_messages (test_concurrency.ConcurrencyTests.test_ten_clients_send_one_hundred_messages) ... ok
|
||||
test_conflict_and_semantic_json_replay (test_idempotency.IdempotencyTests.test_conflict_and_semantic_json_replay) ... ok
|
||||
test_key_format_and_missing_key (test_idempotency.IdempotencyTests.test_key_format_and_missing_key) ... ok
|
||||
test_parallel_replay_across_replicas (test_idempotency.IdempotencyTests.test_parallel_replay_across_replicas) ... ok
|
||||
test_replay_rechecks_session_and_access (test_idempotency.IdempotencyTests.test_replay_rechecks_session_and_access) ... ok
|
||||
test_scope_is_user_and_chat (test_idempotency.IdempotencyTests.test_scope_is_user_and_chat) ... ok
|
||||
test_logout_revokes_only_one_session (test_sessions.SessionTests.test_logout_revokes_only_one_session) ... ok
|
||||
test_password_validation (test_sessions.SessionTests.test_password_validation) ... ok
|
||||
test_sql_like_message_is_plain_text (test_sessions.SessionTests.test_sql_like_message_is_plain_text) ... ok
|
||||
test_unicode_password_with_colon_and_private_response (test_sessions.SessionTests.test_unicode_password_with_colon_and_private_response) ... ok
|
||||
test_wrong_password_and_basic_only_for_login (test_sessions.SessionTests.test_wrong_password_and_basic_only_for_login) ... ok
|
||||
|
||||
----------------------------------------------------------------------
|
||||
Ran 28 tests in 6.783s
|
||||
|
||||
OK
|
||||
PASS: 10 clients sent 100 messages; history contains exactly 100 unique messages.
|
||||
Container lab3-check-a31f544685-postgres-1 Running
|
||||
Container lab3-check-a31f544685-postgres-1 Running
|
||||
PASS: migrations only in one-shot service; repeated execution preserves data
|
||||
/Users/vanek/Desktop/VNPlabs/VNPlab3/mtusi2026lab3/.venv/bin/python tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://127.0.0.1:58474"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
PASS: both API, LB, PostgreSQL, Valkey actually restarted; session and confirmed data preserved
|
||||
PASS: SIGTERM with unfinished request: {"instance": "7f6a80b69e32", "unfinished_request": true, "shutdown_seconds": 5.393, "new_connections_refused_seconds": 0.167, "exit_code": 0, "oom_killed": false}
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Starting
|
||||
Container lab3-check-a31f544685-migrate-1 Started
|
||||
Container lab3-check-a31f544685-valkey-1 Waiting
|
||||
Container lab3-check-a31f544685-migrate-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Healthy
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Exited
|
||||
Container lab3-check-a31f544685-api-1 Starting
|
||||
Container lab3-check-a31f544685-api-1 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
Container lab3-check-a31f544685-valkey-1 Stopping
|
||||
Container lab3-check-a31f544685-valkey-1 Stopped
|
||||
PASS: valkey outage: API live=200, ready=503, LB ready=503
|
||||
Container lab3-check-a31f544685-valkey-1 Starting
|
||||
Container lab3-check-a31f544685-valkey-1 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
Container lab3-check-a31f544685-postgres-1 Stopping
|
||||
Container lab3-check-a31f544685-postgres-1 Stopped
|
||||
PASS: postgres outage: API live=200, ready=503, LB ready=503
|
||||
Container lab3-check-a31f544685-postgres-1 Starting
|
||||
Container lab3-check-a31f544685-postgres-1 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
/Users/vanek/Desktop/VNPlabs/VNPlab3/mtusi2026lab3/.venv/bin/python tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://127.0.0.1:58474"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 113, "failed_attempts": 1, "first_recovery_seconds": 2.452}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Starting
|
||||
Container lab3-check-a31f544685-migrate-1 Started
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Waiting
|
||||
Container lab3-check-a31f544685-migrate-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-valkey-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Exited
|
||||
Container lab3-check-a31f544685-api-1 Starting
|
||||
Container lab3-check-a31f544685-api-1 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
Stopped API: 7f6a80b69e32 container=7f6a80b69e3297a4de72e756a6c9d867a108930c1ca0e57922b3821c26fd03e6
|
||||
{"label": "stop 7f6a80b69e32", "duration_seconds": 16.009, "successful_requests": 1576, "successful_writes": 788, "errors": 4, "successful_rps": 98.44, "first_success_after_action_seconds": {"POST": 0.014, "GET": 0.007}, "maximum_success_gap_seconds": {"POST": 1.957, "GET": 2.004}, "action_start_seconds": 1.003, "action_end_seconds": 1.666, "p50_ms": 7.813, "p95_ms": 16.393, "confirmed_data_preserved": true, "duplicate_messages": 0, "instances": ["7f6a80b69e32", "f973eaec4d52"]}
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Starting
|
||||
Container lab3-check-a31f544685-migrate-1 Started
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Waiting
|
||||
Container lab3-check-a31f544685-migrate-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Healthy
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Exited
|
||||
Container lab3-check-a31f544685-api-1 Starting
|
||||
Container lab3-check-a31f544685-api-1 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
Stopped API: f973eaec4d52 container=f973eaec4d5290eb73cd96949877ccb8df1213523fce0ec05c6b40c1136bb31b
|
||||
{"label": "stop f973eaec4d52", "duration_seconds": 16.015, "successful_requests": 1574, "successful_writes": 786, "errors": 4, "successful_rps": 98.28, "first_success_after_action_seconds": {"POST": 0.002, "GET": 0.008}, "maximum_success_gap_seconds": {"POST": 2.006, "GET": 2.006}, "action_start_seconds": 1.005, "action_end_seconds": 1.713, "p50_ms": 7.98, "p95_ms": 17.217, "confirmed_data_preserved": true, "duplicate_messages": 0, "instances": ["7f6a80b69e32", "f973eaec4d52"]}
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Starting
|
||||
Container lab3-check-a31f544685-migrate-1 Started
|
||||
Container lab3-check-a31f544685-postgres-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Waiting
|
||||
Container lab3-check-a31f544685-migrate-1 Waiting
|
||||
Container lab3-check-a31f544685-valkey-1 Healthy
|
||||
Container lab3-check-a31f544685-postgres-1 Healthy
|
||||
Container lab3-check-a31f544685-migrate-1 Exited
|
||||
Container lab3-check-a31f544685-api-2 Starting
|
||||
Container lab3-check-a31f544685-api-2 Started
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
Local .env and secrets are ready; values are not printed
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 1.03kB done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 733B done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [internal] load metadata for docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [internal] load .dockerignore
|
||||
#4 transferring context: 167B done
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [internal] load build context
|
||||
#5 transferring context: 809B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [1/8] FROM docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3
|
||||
#6 resolve docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 0.0s done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [4/8] RUN python -m pip install --no-cache-dir -r requirements.txt && python -m pip check
|
||||
#7 CACHED
|
||||
|
||||
#8 [3/8] COPY requirements.txt .
|
||||
#8 CACHED
|
||||
|
||||
#9 [5/8] RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home app
|
||||
#9 CACHED
|
||||
|
||||
#10 [6/8] COPY src/ ./src/
|
||||
#10 CACHED
|
||||
|
||||
#11 [2/8] WORKDIR /app
|
||||
#11 CACHED
|
||||
|
||||
#12 [7/8] COPY migrations/ ./migrations/
|
||||
#12 CACHED
|
||||
|
||||
#13 [8/8] COPY research/ ./research/
|
||||
#13 CACHED
|
||||
|
||||
#14 exporting to image
|
||||
#14 exporting layers done
|
||||
#14 exporting manifest sha256:06163e45d3676c7cf4f7a1c7bfe108ed3b98559ebb485c7a09d1e87e6f418d17 done
|
||||
#14 exporting config sha256:3fed7460e9510eef7b2928f8d600d06d5d65329f74d820beac13809476b11398 done
|
||||
#14 exporting attestation manifest sha256:3a88ce0975ddcbab53c3ecb185da08ef114e818e9db952983e997cd47add67bf done
|
||||
#14 exporting manifest list sha256:433a8a3293202a92f092574052b474e8373c0d58649cbcf1c7ebc1af17933d3c done
|
||||
#14 naming to docker.io/library/mtusi-messenger:lab3 done
|
||||
#14 unpacking to docker.io/library/mtusi-messenger:lab3 done
|
||||
#14 DONE 0.1s
|
||||
|
||||
#15 resolving provenance for metadata file
|
||||
#15 DONE 0.0s
|
||||
mtusi-messenger:lab3 Built
|
||||
Local .env and secrets are ready; values are not printed
|
||||
Container lab3-check-a31f544685-postgres-1 Running
|
||||
#1 [internal] load local bake definitions
|
||||
#1 reading from stdin 576B done
|
||||
#1 DONE 0.0s
|
||||
|
||||
#2 [internal] load build definition from Dockerfile
|
||||
#2 transferring dockerfile: 733B done
|
||||
#2 DONE 0.0s
|
||||
|
||||
#3 [internal] load metadata for docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3
|
||||
#3 DONE 0.0s
|
||||
|
||||
#4 [internal] load .dockerignore
|
||||
#4 transferring context: 167B done
|
||||
#4 DONE 0.0s
|
||||
|
||||
#5 [internal] load build context
|
||||
#5 transferring context: 809B done
|
||||
#5 DONE 0.0s
|
||||
|
||||
#6 [1/8] FROM docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3
|
||||
#6 resolve docker.io/library/python:3.11.15-slim-bookworm@sha256:d29f48a31a8b408ed19272ca1e7b10ebae13b240a27e862d3d4217c528e2e0c3 done
|
||||
#6 DONE 0.0s
|
||||
|
||||
#7 [3/8] COPY requirements.txt .
|
||||
#7 CACHED
|
||||
|
||||
#8 [4/8] RUN python -m pip install --no-cache-dir -r requirements.txt && python -m pip check
|
||||
#8 CACHED
|
||||
|
||||
#9 [5/8] RUN groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home app
|
||||
#9 CACHED
|
||||
|
||||
#10 [6/8] COPY src/ ./src/
|
||||
#10 CACHED
|
||||
|
||||
#11 [7/8] COPY migrations/ ./migrations/
|
||||
#11 CACHED
|
||||
|
||||
#12 [2/8] WORKDIR /app
|
||||
#12 CACHED
|
||||
|
||||
#13 [8/8] COPY research/ ./research/
|
||||
#13 CACHED
|
||||
|
||||
#14 exporting to image
|
||||
#14 exporting layers done
|
||||
#14 exporting manifest sha256:a59568d34e2c5e8b4d23308342601fdaf8c07e78ec3065878679a067c082e952 done
|
||||
#14 exporting config sha256:b67b805ba1b7dd90f0a3e8444455488fe8c7f4118f14d671501dd63e85b59c97 done
|
||||
#14 exporting attestation manifest sha256:25ff7934ca5161da9b6c345af61b6a10b452580e4d349b35939d32feb66664ea done
|
||||
#14 exporting manifest list sha256:3e102cd9a2c1e81e95aed4a0d4de1ac94352370595fced350257813f7a07bef8 done
|
||||
#14 naming to docker.io/library/mtusi-messenger:lab3 done
|
||||
#14 unpacking to docker.io/library/mtusi-messenger:lab3 done
|
||||
#14 DONE 0.0s
|
||||
|
||||
#15 resolving provenance for metadata file
|
||||
#15 DONE 0.0s
|
||||
Migrations: already applied
|
||||
API ready through LB: 7f6a80b69e32, f973eaec4d52
|
||||
Replacing API: 7f6a80b69e32
|
||||
Container lab3-check-a31f544685-api-2 Running
|
||||
Container lab3-check-a31f544685-api-3 Creating
|
||||
Container lab3-check-a31f544685-api-3 Created
|
||||
Container lab3-check-a31f544685-api-3 Starting
|
||||
Container lab3-check-a31f544685-api-3 Started
|
||||
API ready through LB: ca9c7a52da66, f973eaec4d52
|
||||
Replacing API: f973eaec4d52
|
||||
Container lab3-check-a31f544685-api-3 Running
|
||||
Container lab3-check-a31f544685-api-4 Creating
|
||||
Container lab3-check-a31f544685-api-4 Created
|
||||
Container lab3-check-a31f544685-api-4 Starting
|
||||
Container lab3-check-a31f544685-api-4 Started
|
||||
API ready through LB: 244bf0b910eb, ca9c7a52da66
|
||||
PASS: all API containers replaced sequentially; stores and LB kept running
|
||||
{"label": "sequential API replacement", "duration_seconds": 23.774, "successful_requests": 2131, "successful_writes": 1063, "errors": 11, "successful_rps": 89.64, "first_success_after_action_seconds": {"POST": 0.018, "GET": 0.004}, "maximum_success_gap_seconds": {"POST": 1.059, "GET": 2.034}, "action_start_seconds": 1.005, "action_end_seconds": 19.63, "p50_ms": 7.723, "p95_ms": 13.565, "confirmed_data_preserved": true, "duplicate_messages": 0, "instances": ["244bf0b910eb", "7f6a80b69e32", "ca9c7a52da66", "f973eaec4d52"]}
|
||||
PASS: all lab3 grade-4 checks completed
|
||||
Container lab3-check-a31f544685-lb-1 Stopping
|
||||
Container lab3-check-a31f544685-lb-1 Stopped
|
||||
Container lab3-check-a31f544685-lb-1 Removing
|
||||
Container lab3-check-a31f544685-lb-1 Removed
|
||||
Container lab3-check-a31f544685-api-3 Stopping
|
||||
Container lab3-check-a31f544685-api-4 Stopping
|
||||
Container lab3-check-a31f544685-api-4 Stopped
|
||||
Container lab3-check-a31f544685-api-4 Removing
|
||||
Container lab3-check-a31f544685-api-4 Removed
|
||||
Container lab3-check-a31f544685-api-3 Stopped
|
||||
Container lab3-check-a31f544685-api-3 Removing
|
||||
Container lab3-check-a31f544685-api-3 Removed
|
||||
Container lab3-check-a31f544685-migrate-1 Stopping
|
||||
Container lab3-check-a31f544685-valkey-1 Stopping
|
||||
Container lab3-check-a31f544685-migrate-1 Stopped
|
||||
Container lab3-check-a31f544685-migrate-1 Removing
|
||||
Container lab3-check-a31f544685-migrate-1 Removed
|
||||
Container lab3-check-a31f544685-postgres-1 Stopping
|
||||
Container lab3-check-a31f544685-valkey-1 Stopped
|
||||
Container lab3-check-a31f544685-valkey-1 Removing
|
||||
Container lab3-check-a31f544685-valkey-1 Removed
|
||||
Container lab3-check-a31f544685-postgres-1 Stopped
|
||||
Container lab3-check-a31f544685-postgres-1 Removing
|
||||
Container lab3-check-a31f544685-postgres-1 Removed
|
||||
Volume lab3-check-a31f544685_valkey_data Removing
|
||||
Network lab3-check-a31f544685_default Removing
|
||||
Volume lab3-check-a31f544685_postgres_data Removing
|
||||
Volume lab3-check-a31f544685_valkey_data Removed
|
||||
Volume lab3-check-a31f544685_postgres_data Removed
|
||||
Network lab3-check-a31f544685_default Removed
|
||||
Removed only temporary test containers and volumes: lab3-check-a31f544685
|
||||
@@ -1,5 +1,11 @@
|
||||
# Инфраструктура студента
|
||||
|
||||
Решение lab3: [HAProxy](haproxy.cfg) → масштабируемый сервис `api`
|
||||
(две реплики) → общие PostgreSQL и Valkey. Отдельный `migrate` выполняется
|
||||
до запуска API. Публичный порт имеет только HAProxy; round robin без
|
||||
sticky session, readiness раз в секунду, актуальные адреса из Docker DNS.
|
||||
Команды запуска, лимиты, таймауты и результаты проверок — в [REPORT.md](../REPORT.md).
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option dontlognull
|
||||
option http-server-close
|
||||
timeout connect 1s
|
||||
timeout client 10s
|
||||
timeout server 8s
|
||||
timeout http-request 5s
|
||||
timeout check 1s
|
||||
retries 1
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
accepted_payload_size 8192
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
hold nx 1s
|
||||
hold timeout 1s
|
||||
hold refused 1s
|
||||
hold other 1s
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost
|
||||
http-check expect status 200
|
||||
default-server inter 1s fastinter 1s downinter 1s fall 2 rise 2
|
||||
server-template replica 10 api:8080 check resolvers docker resolve-prefer ipv4 init-addr none
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Добавочная миграция: существующие данные и таблицы lab2 сохраняются.
|
||||
CREATE TABLE message_idempotency (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
key varchar(128) NOT NULL CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
request_text text NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, key)
|
||||
);
|
||||
@@ -8,4 +8,4 @@ if [[ ! -x .venv/bin/python ]]; then
|
||||
fi
|
||||
./scripts/build.sh
|
||||
mkdir -p evidence
|
||||
.venv/bin/python -u student-tests/docker_lifecycle.py 2>&1 | tee evidence/docker-checks.txt
|
||||
.venv/bin/python -u student-tests/docker_lifecycle.py 2>&1 | sed -E 's/[[:blank:]]+$//' | tee evidence/lab3-checks.txt
|
||||
|
||||
+2
-1
@@ -22,6 +22,7 @@ chat_id="$(jq -nc --arg a "$alice_id" --arg b "$bob_id" '{title:"Учебный
|
||||
--data-binary @- "$base_url/api/v1/chats" | jq -er '.id')"
|
||||
for token in "$alice_token" "$bob_token"; do
|
||||
curl -fsS -H "Authorization: Bearer $token" -H 'Content-Type: application/json' \
|
||||
-d '{"text":"Привет из lab2! 👋"}' "$base_url/api/v1/chats/$chat_id/messages" | jq .
|
||||
-H "Idempotency-Key: demo-$RANDOM-$RANDOM" \
|
||||
-d '{"text":"Привет из lab3! 👋"}' "$base_url/api/v1/chats/$chat_id/messages" | jq .
|
||||
done
|
||||
curl -fsS -H "Authorization: Bearer $bob_token" "$base_url/api/v1/chats/$chat_id/messages" | jq .
|
||||
|
||||
+2
-1
@@ -2,4 +2,5 @@
|
||||
set -euo pipefail
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$project_dir"
|
||||
docker compose exec -T api python -m src.migrate
|
||||
python3 scripts/init_local.py
|
||||
docker compose run --rm --build migrate
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Управление репликами только текущего Compose project через Docker CLI."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, timeout=120).strip()
|
||||
|
||||
|
||||
def replicas():
|
||||
ids = command("docker", "compose", "ps", "-q", "api").split()
|
||||
return json.loads(command("docker", "inspect", *ids)) if ids else []
|
||||
|
||||
|
||||
def base_url():
|
||||
config = json.loads(command("docker", "compose", "config", "--format", "json"))
|
||||
port = config["services"]["lb"]["ports"][0]["published"]
|
||||
return os.environ.get("BASE_URL", "http://127.0.0.1:" + str(port)).rstrip("/")
|
||||
|
||||
|
||||
def wait_ready():
|
||||
url = base_url() + "/health/ready"
|
||||
deadline = time.monotonic() + 90
|
||||
seen = set()
|
||||
while time.monotonic() < deadline:
|
||||
current = replicas()
|
||||
expected = {info["Config"]["Hostname"] for info in current}
|
||||
if expected and all(info["State"].get("Health", {}).get("Status") == "healthy" for info in current):
|
||||
try:
|
||||
with urlopen(url, timeout=2) as response:
|
||||
if response.status == 200:
|
||||
seen.add(response.headers.get("X-Instance-Id"))
|
||||
if expected <= seen:
|
||||
print("API ready through LB:", ", ".join(sorted(expected)), flush=True)
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError("Не все работающие API-реплики готовы через LB за 90 секунд")
|
||||
|
||||
|
||||
def stop_one():
|
||||
target = os.environ.get("TARGET_INSTANCE_ID")
|
||||
if not target:
|
||||
raise RuntimeError("Задайте TARGET_INSTANCE_ID из X-Instance-Id")
|
||||
current = replicas()
|
||||
matches = [info for info in current if info["Config"]["Hostname"] == target]
|
||||
if len(current) < 2 or len(matches) != 1:
|
||||
raise RuntimeError("Нужны минимум две работающие реплики и ровно одна выбранная")
|
||||
selected = matches[0]
|
||||
command("docker", "stop", "--time", "8", selected["Id"])
|
||||
print("Stopped API:", target, "container=" + selected["Id"], flush=True)
|
||||
|
||||
|
||||
def rolling():
|
||||
wait_ready()
|
||||
originals = replicas()
|
||||
count = len(originals)
|
||||
if count < 2:
|
||||
raise RuntimeError("Для поочерёдной замены нужны минимум две API-реплики")
|
||||
for old in originals:
|
||||
active = replicas()
|
||||
healthy = [info for info in active if info["Id"] != old["Id"]
|
||||
and info["State"].get("Health", {}).get("Status") == "healthy"]
|
||||
if not healthy:
|
||||
raise RuntimeError("Нет готовой реплики, которая продолжит обслуживать запросы")
|
||||
print("Replacing API:", old["Config"]["Hostname"], flush=True)
|
||||
command("docker", "stop", "--time", "8", old["Id"])
|
||||
command("docker", "rm", old["Id"])
|
||||
# --no-recreate сохраняет остальные процессы; Compose создаёт только недостающий.
|
||||
command("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={count}", "api")
|
||||
wait_ready()
|
||||
assert len(replicas()) == count
|
||||
final = replicas()
|
||||
assert not ({info["Id"] for info in originals} & {info["Id"] for info in final})
|
||||
print("PASS: all API containers replaced sequentially; stores and LB kept running", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=["wait", "stop", "rolling"])
|
||||
action = parser.parse_args().action
|
||||
{"wait": wait_ready, "stop": stop_one, "rolling": rolling}[action]()
|
||||
+1
-1
@@ -2,5 +2,5 @@
|
||||
set -euo pipefail
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$project_dir"
|
||||
docker compose restart --timeout 10 postgres valkey api
|
||||
docker compose restart --timeout 8 postgres valkey api lb
|
||||
./scripts/wait-ready.sh
|
||||
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$project_dir"
|
||||
# Сначала собираем образ и применяем только обратно совместимые миграции.
|
||||
./scripts/build.sh
|
||||
./scripts/migrate.sh
|
||||
exec python3 scripts/replicas.py rolling
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
# В lab2 локальный запуск включает API, PostgreSQL и Valkey.
|
||||
# Локальный стенд: HAProxy, две API-реплики, PostgreSQL и Valkey.
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
exec "$project_dir/scripts/start.sh"
|
||||
|
||||
+1
-1
@@ -3,5 +3,5 @@ set -euo pipefail
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$project_dir"
|
||||
python3 scripts/init_local.py
|
||||
docker compose up -d --build api
|
||||
docker compose up -d --build lb
|
||||
./scripts/wait-ready.sh
|
||||
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$project_dir"
|
||||
exec python3 scripts/replicas.py stop
|
||||
@@ -2,12 +2,4 @@
|
||||
set -euo pipefail
|
||||
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$project_dir"
|
||||
for ((attempt = 0; attempt < 60; attempt++)); do
|
||||
if docker compose exec -T api python -m src.healthcheck >/dev/null 2>&1; then
|
||||
echo "API ready"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "API не готов за 60 секунд. Проверь docker compose logs api" >&2
|
||||
exit 1
|
||||
exec python3 scripts/replicas.py wait
|
||||
|
||||
+8
-2
@@ -3,6 +3,7 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from time import perf_counter
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
@@ -14,13 +15,14 @@ from starlette.exceptions import HTTPException
|
||||
from src import auth, db, migrate, passwords, storage
|
||||
from src.errors import ApiError, error_response
|
||||
from src.models import CreateChat, CreateMessage, CreateUser
|
||||
from src.config import INSTANCE_ID
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
await run_in_threadpool(db.pool.open, wait=True, timeout=15)
|
||||
try:
|
||||
await run_in_threadpool(migrate.apply)
|
||||
await run_in_threadpool(migrate.check)
|
||||
yield
|
||||
finally:
|
||||
await run_in_threadpool(db.pool.close)
|
||||
@@ -60,6 +62,7 @@ async def handle_request(request: Request, call_next):
|
||||
logger.error("%s request_id=%s", type(error).__name__, request.state.request_id)
|
||||
response = error_response(request, ApiError(500, "internal_error", "Внутренняя ошибка сервера"))
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
logger.info(
|
||||
"%s %s status=%s duration_ms=%.2f request_id=%s",
|
||||
request.method, path, response.status_code,
|
||||
@@ -129,7 +132,10 @@ def get_chat(request: Request, chat_id: UUID):
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(request: Request, chat_id: UUID, data: CreateMessage):
|
||||
return storage.create_message(request.state.user["id"], str(chat_id), data.text)
|
||||
keys = request.headers.getlist("Idempotency-Key")
|
||||
if len(keys) != 1 or re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", keys[0]) is None:
|
||||
raise ApiError(400, "invalid_request", "Нужен Idempotency-Key: 1–128 символов ASCII [A-Za-z0-9._:-]")
|
||||
return storage.create_message(request.state.user["id"], str(chat_id), data.text, keys[0])
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Настройки и чтение локальных Docker secrets."""
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -12,3 +13,8 @@ if SESSION_TTL < 1:
|
||||
raise ValueError("SESSION_TTL_SECONDS должен быть положительным")
|
||||
if os.environ.get("SESSION_STORE", "valkey") != "valkey":
|
||||
raise ValueError("В этой реализации SESSION_STORE=valkey")
|
||||
|
||||
INSTANCE_ID = socket.gethostname()
|
||||
IDEMPOTENCY_TTL = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if IDEMPOTENCY_TTL < 86400:
|
||||
raise ValueError("IDEMPOTENCY_TTL_SECONDS должен быть не меньше 86400")
|
||||
|
||||
@@ -8,6 +8,15 @@ from src import db
|
||||
DIRECTORY = Path(__file__).resolve().parents[1] / "migrations"
|
||||
|
||||
|
||||
def check():
|
||||
"""API только проверяет схему; DDL выполняет отдельный migrate-service."""
|
||||
with db.connection() as conn:
|
||||
for path in sorted(DIRECTORY.glob("*.sql")):
|
||||
row = conn.execute("SELECT checksum FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
||||
if row is None or row["checksum"] != hashlib.sha256(path.read_bytes()).hexdigest():
|
||||
raise RuntimeError("Сначала выполните миграции: " + path.name)
|
||||
|
||||
|
||||
def apply():
|
||||
applied = []
|
||||
with db.connection() as conn:
|
||||
|
||||
+19
-1
@@ -5,6 +5,7 @@ from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
||||
|
||||
from src import db, pagination
|
||||
from src.errors import ApiError
|
||||
from src.config import IDEMPOTENCY_TTL
|
||||
|
||||
|
||||
def utc(value):
|
||||
@@ -97,11 +98,28 @@ def list_chats(user_id, limit, cursor):
|
||||
return pagination.page([public_chat(row) for row in rows], size, scope)
|
||||
|
||||
|
||||
def create_message(user_id, chat_id, text):
|
||||
def create_message(user_id, chat_id, text, key):
|
||||
with db.connection() as conn:
|
||||
require_member(conn, user_id, chat_id)
|
||||
# Одна блокировка на область ключа во всех API-процессах.
|
||||
# Побочный эффект и результат повтора фиксируются одной транзакцией.
|
||||
scope = user_id + ":POST:/api/v1/chats/" + chat_id + "/messages:" + key
|
||||
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
|
||||
previous = conn.execute("""SELECT m.*, i.request_text FROM message_idempotency i
|
||||
JOIN messages m ON m.id=i.message_id
|
||||
WHERE i.user_id=%s AND i.chat_id=%s AND i.key=%s AND i.expires_at>clock_timestamp()""",
|
||||
(UUID(user_id), UUID(chat_id), key)).fetchone()
|
||||
if previous:
|
||||
if previous["request_text"] != text:
|
||||
raise ApiError(409, "conflict", "Этот ключ уже использован с другим сообщением")
|
||||
return public_message(previous)
|
||||
conn.execute("DELETE FROM message_idempotency WHERE user_id=%s AND chat_id=%s AND key=%s",
|
||||
(UUID(user_id), UUID(chat_id), key))
|
||||
row = conn.execute("""INSERT INTO messages(id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s)
|
||||
RETURNING *""", (uuid4(), UUID(chat_id), UUID(user_id), text)).fetchone()
|
||||
conn.execute("""INSERT INTO message_idempotency(user_id, chat_id, key, request_text, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, clock_timestamp() + %s * interval '1 second')""",
|
||||
(UUID(user_id), UUID(chat_id), key, text, row["id"], IDEMPOTENCY_TTL))
|
||||
result = public_message(row)
|
||||
return result
|
||||
|
||||
|
||||
+282
-169
@@ -1,4 +1,5 @@
|
||||
"""Полный прогон lab2 в собственном Compose project; основные данные не затрагивает."""
|
||||
"""Проверки уровня 4 в отдельном Compose project с синтетическими данными."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
@@ -6,195 +7,307 @@ import platform
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.error import URLError
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import Client, ROOT
|
||||
from client import Failure
|
||||
from resilience import history
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(["docker", *args], check=True, capture_output=True, text=True, timeout=120).stdout.strip()
|
||||
|
||||
|
||||
def inspect(container):
|
||||
return json.loads(docker("inspect", container))[0]
|
||||
|
||||
|
||||
def check_shutdown(container, base_url, port):
|
||||
with socket.create_connection(("127.0.0.1", port), timeout=2) as pending:
|
||||
pending.sendall(
|
||||
b"POST /api/v1/users HTTP/1.1\r\nHost: localhost\r\n"
|
||||
b"Content-Type: application/json\r\nContent-Length: 1000\r\n"
|
||||
b"Expect: 100-continue\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
assert b"100 Continue" in pending.recv(1024), "Сервер не начал читать тело запроса"
|
||||
pending.sendall(b'{"username":')
|
||||
started = time.monotonic()
|
||||
docker("kill", "--signal=TERM", container)
|
||||
first_refusal = None
|
||||
while inspect(container)["State"]["Running"]:
|
||||
assert time.monotonic() - started < 10, "SIGTERM: превышены 10 секунд"
|
||||
try:
|
||||
with urlopen(base_url + "/health/live", timeout=0.3):
|
||||
pass
|
||||
except (URLError, OSError):
|
||||
if first_refusal is None:
|
||||
first_refusal = time.monotonic() - started
|
||||
time.sleep(0.05)
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
assert elapsed < 10, "SIGTERM: превышены 10 секунд"
|
||||
assert first_refusal is not None and first_refusal < elapsed, "Не показан отказ новых запросов при остановке"
|
||||
state = inspect(container)["State"]
|
||||
assert not state["OOMKilled"] and state["ExitCode"] in (0, 143), state
|
||||
|
||||
result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, check=True, timeout=10)
|
||||
logs = result.stdout + result.stderr
|
||||
assert "Application shutdown complete" in logs, "Нет подтверждения корректного завершения"
|
||||
try:
|
||||
with urlopen(base_url + "/health/live", timeout=0.5):
|
||||
raise AssertionError("Остановленный сервер отвечает")
|
||||
except (URLError, OSError):
|
||||
pass
|
||||
print(f"PASS: SIGTERM with unfinished request: {elapsed:.2f}s; new requests refused after {first_refusal:.2f}s; exit={state['ExitCode']}; OOM=false")
|
||||
return subprocess.check_output(["docker", *args], text=True, timeout=180).strip()
|
||||
|
||||
|
||||
def main():
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
port = sock.getsockname()[1]
|
||||
project = "lab2-check-" + uuid4().hex[:10]
|
||||
env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port), SESSION_TTL_SECONDS="3600")
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
project = "lab3-check-" + uuid4().hex[:10]
|
||||
base = f"http://127.0.0.1:{port}"
|
||||
env = dict(os.environ, COMPOSE_PROJECT_NAME=project, HOST_PORT=str(port),
|
||||
API_REPLICAS="2", SESSION_TTL_SECONDS="3600", BASE_URL=base)
|
||||
result = {"utc": datetime.now(timezone.utc).isoformat(), "project": project,
|
||||
"base_url": base, "host": platform.system() + " " + platform.machine(),
|
||||
"docker": docker("info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}"),
|
||||
"commit": docker("compose", "version", "--short"),
|
||||
"profile": {"workers": 4, "pause_seconds": 0.05, "operation": "POST message then GET history, same-key retry after uncertain POST"}}
|
||||
result["compose_version"] = result.pop("commit")
|
||||
result["source_commit"] = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
|
||||
result["working_tree"] = True
|
||||
|
||||
def compose(*args, capture=True, stdin=None):
|
||||
return subprocess.run(["docker", "compose", *args], cwd=ROOT, env=env, input=stdin,
|
||||
text=True, capture_output=capture, check=True, timeout=180)
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, env=env, text=True, timeout=180).strip()
|
||||
|
||||
def ready():
|
||||
subprocess.run([str(ROOT / "scripts/start.sh")], cwd=ROOT, env=env,
|
||||
check=True, capture_output=True, text=True, timeout=180)
|
||||
print("PASS: start.sh built and started the stack, readiness reached")
|
||||
def script(name):
|
||||
subprocess.run([str(ROOT / "scripts" / name)], cwd=ROOT, env=env, check=True, timeout=240)
|
||||
|
||||
def states():
|
||||
return {service: inspect(compose("ps", "-q", service).stdout.strip()) for service in ("api", "postgres", "valkey")}
|
||||
def inspect_all():
|
||||
ids = compose("ps", "-a", "-q").split()
|
||||
return json.loads(docker("inspect", *ids))
|
||||
|
||||
def scalar(query, params=()):
|
||||
code = """import json,sys
|
||||
from src import db
|
||||
data=json.load(sys.stdin)
|
||||
db.pool.open(wait=True,timeout=15)
|
||||
try:
|
||||
with db.connection() as conn:
|
||||
row=conn.execute(data['query'], data['params']).fetchone()
|
||||
print(json.dumps(next(iter(row.values()))))
|
||||
finally:
|
||||
db.pool.close()
|
||||
def apis():
|
||||
return [i for i in inspect_all() if i["Config"]["Labels"]["com.docker.compose.service"] == "api"]
|
||||
|
||||
def metadata(info):
|
||||
return {"id": info["Id"], "instance": info["Config"]["Hostname"],
|
||||
"service": info["Config"]["Labels"]["com.docker.compose.service"],
|
||||
"image": info["Image"], "started_at": info["State"]["StartedAt"],
|
||||
"running": info["State"]["Running"], "exit_code": info["State"]["ExitCode"],
|
||||
"memory_bytes": info["HostConfig"]["Memory"], "nano_cpus": info["HostConfig"]["NanoCpus"],
|
||||
"published_ports": info["HostConfig"]["PortBindings"],
|
||||
"mounts": [{"type": m["Type"], "destination": m["Destination"], "name": m.get("Name")} for m in info["Mounts"]]}
|
||||
|
||||
def sql(query):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query)
|
||||
|
||||
def check_shutdown():
|
||||
info = apis()[0]
|
||||
# Внутреннее подключение через docker exec не публикует порт API на хост.
|
||||
pending_code = """import socket,time
|
||||
s=socket.create_connection(('127.0.0.1',8080),timeout=2)
|
||||
s.sendall(b'POST /api/v1/users HTTP/1.1\\r\\nHost: localhost\\r\\nContent-Type: application/json\\r\\nContent-Length: 1000\\r\\nExpect: 100-continue\\r\\n\\r\\n')
|
||||
assert b'100 Continue' in s.recv(1024)
|
||||
s.sendall(b'{"username":')
|
||||
print('pending',flush=True)
|
||||
time.sleep(30)
|
||||
"""
|
||||
return json.loads(compose("exec", "-T", "api", "python", "-c", code,
|
||||
stdin=json.dumps({"query": query, "params": params})).stdout)
|
||||
|
||||
print("UTC:", datetime.now(timezone.utc).isoformat())
|
||||
print("Host:", platform.system(), platform.machine(), "Python", platform.python_version())
|
||||
print("Docker:", docker("info", "--format", "{{.ServerVersion}} {{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}"))
|
||||
print("Commit:", subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True, text=True).stdout.strip(), "+ working tree")
|
||||
print("Command: ./scripts/check-docker.sh; project:", project)
|
||||
try:
|
||||
ready()
|
||||
before = states()
|
||||
for service, info in before.items():
|
||||
print(service, "image=" + info["Image"], "started=" + info["State"]["StartedAt"],
|
||||
"memory=" + str(info["HostConfig"]["Memory"]), "nano_cpus=" + str(info["HostConfig"]["NanoCpus"]))
|
||||
api = compose("ps", "-q", "api").stdout.strip()
|
||||
assert docker("exec", api, "id", "-u") == "10001"
|
||||
assert before["api"]["Config"]["Cmd"] == ["python", "-m", "src"]
|
||||
for service in ("postgres", "valkey"):
|
||||
assert any(mount["Type"] == "volume" for mount in before[service]["Mounts"])
|
||||
assert all(mount["Destination"].startswith("/run/secrets/") for mount in before["api"]["Mounts"])
|
||||
bad_health = subprocess.run(["docker", "exec", "-e", "APP_PORT=1", api, "python", "-m", "src.healthcheck"], capture_output=True)
|
||||
assert bad_health.returncode == 1
|
||||
print("PASS: non-root UID 10001; Python PID 1; healthcheck; named volumes; no API data volume")
|
||||
|
||||
subprocess.run([str(ROOT / "scripts/check.sh")], cwd=ROOT, env=dict(env, BASE_URL=base_url), check=True, timeout=240)
|
||||
demo = subprocess.run([str(ROOT / "scripts/demo.sh")], cwd=ROOT, env=dict(env, BASE_URL=base_url),
|
||||
check=True, capture_output=True, text=True, timeout=30)
|
||||
assert "Привет из lab2!" in demo.stdout
|
||||
print("PASS: demo.sh registered users, logged in and read two messages")
|
||||
client = Client(base_url)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
marker = "private-" + uuid4().hex
|
||||
client.message(alice, chat, marker)
|
||||
logs = docker("logs", api)
|
||||
assert marker not in logs and alice["token"] not in logs and alice["registration"]["password"] not in logs
|
||||
logs_result = subprocess.run(["docker", "logs", api], capture_output=True, text=True, check=True)
|
||||
assert "request_id=" in logs_result.stderr + logs_result.stdout
|
||||
assert marker not in logs_result.stderr + logs_result.stdout
|
||||
assert alice["token"] not in logs_result.stderr + logs_result.stdout
|
||||
assert alice["registration"]["password"] not in logs_result.stderr + logs_result.stdout
|
||||
assert scalar("SELECT bool_and(password_hash LIKE %s) FROM users", ("$argon2id$%",))
|
||||
print("PASS: Argon2id in PostgreSQL; logs do not contain message text, passwords or session tokens")
|
||||
|
||||
title = "rollback_" + uuid4().hex
|
||||
client.call("POST", "/api/v1/chats", 400, actor=alice,
|
||||
body={"title": title, "member_ids": [alice["id"], str(uuid4())]})
|
||||
assert scalar("SELECT count(*) FROM chats WHERE title=%s", (title,)) == 0
|
||||
count = scalar("SELECT count(*) FROM messages")
|
||||
compose("exec", "-T", "api", "python", "-m", "src.migrate")
|
||||
compose("exec", "-T", "api", "python", "-m", "src.migrate")
|
||||
assert scalar("SELECT count(*) FROM schema_migrations") == 1
|
||||
assert scalar("SELECT count(*) FROM messages") == count
|
||||
print("PASS: failed membership insert rolled back chat; migrations run twice without duplicate data")
|
||||
|
||||
before = states()
|
||||
subprocess.run(["make", "test-persistence", "PYTHON=" + sys.executable,
|
||||
"ACTION_SCRIPT=scripts/restart.sh", "BASE_URL=" + base_url], cwd=ROOT, env=env, check=True, timeout=240)
|
||||
after = states()
|
||||
for service in before:
|
||||
assert before[service]["State"]["StartedAt"] != after[service]["State"]["StartedAt"]
|
||||
print("Restart", service, before[service]["State"]["StartedAt"], "->", after[service]["State"]["StartedAt"])
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
print("PASS: API, PostgreSQL and Valkey really restarted; previous token still works")
|
||||
|
||||
for service in ("valkey", "postgres"):
|
||||
try:
|
||||
compose("stop", "--timeout", "10", service)
|
||||
started = time.monotonic()
|
||||
client.call("GET", "/api/v1/users/me", 503, actor=alice)
|
||||
elapsed = time.monotonic() - started
|
||||
assert elapsed < 6, elapsed
|
||||
client.call("GET", "/api/v1/users/me", 401)
|
||||
client.call("GET", "/health/ready", 503)
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
print(f"PASS: {service} unavailable -> 503 in {elapsed:.2f}s; anonymous -> 401; readiness 503, liveness 200")
|
||||
finally:
|
||||
compose("start", service)
|
||||
subprocess.run([str(ROOT / "scripts/wait-ready.sh")], cwd=ROOT, env=env, check=True, timeout=90)
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
print("PASS:", service, "recovered without a new login")
|
||||
|
||||
env["SESSION_TTL_SECONDS"] = "2"
|
||||
compose("up", "-d", "--force-recreate", "api")
|
||||
subprocess.run([str(ROOT / "scripts/wait-ready.sh")], cwd=ROOT, env=env, check=True, timeout=90)
|
||||
short = client.user("short_ttl")
|
||||
client.call("GET", "/api/v1/users/me", actor=short, schema="User")
|
||||
time.sleep(2.2)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=short)
|
||||
print("PASS: SESSION_TTL_SECONDS=2; valid token expires without logout")
|
||||
api = compose("ps", "-q", "api").stdout.strip()
|
||||
check_shutdown(api, base_url, port)
|
||||
print("PASS: all lab2 Docker checks completed")
|
||||
finally:
|
||||
pending = subprocess.Popen(["docker", "exec", info["Id"], "python", "-u", "-c", pending_code],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
||||
try:
|
||||
subprocess.run([str(ROOT / "scripts/stop.sh")], cwd=ROOT, env=env,
|
||||
check=True, capture_output=True, text=True, timeout=90)
|
||||
volumes = docker("volume", "ls", "--quiet", "--filter", "label=com.docker.compose.project=" + project)
|
||||
if volumes:
|
||||
print("PASS: stop.sh removed containers and preserved named volumes")
|
||||
assert pending.stdout.readline().strip() == "pending"
|
||||
started = time.monotonic()
|
||||
docker("kill", "--signal=TERM", info["Id"])
|
||||
first_refusal = None
|
||||
while True:
|
||||
state = json.loads(docker("inspect", info["Id"]))[0]["State"]
|
||||
if not state["Running"]:
|
||||
break
|
||||
assert time.monotonic() - started < 8
|
||||
probe = subprocess.run(["docker", "exec", info["Id"], "python", "-c",
|
||||
"import socket; s=socket.socket(); s.settimeout(.2); raise SystemExit(s.connect_ex(('127.0.0.1',8080)))"],
|
||||
capture_output=True, timeout=3)
|
||||
if probe.returncode and first_refusal is None:
|
||||
first_refusal = time.monotonic() - started
|
||||
time.sleep(0.1)
|
||||
elapsed = time.monotonic() - started
|
||||
assert first_refusal is not None and first_refusal < elapsed < 8
|
||||
assert state["ExitCode"] == 0 and not state["OOMKilled"]
|
||||
logs = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True)
|
||||
assert "Application shutdown complete" in logs.stdout + logs.stderr
|
||||
result["sigterm"] = {"instance": info["Config"]["Hostname"], "unfinished_request": True,
|
||||
"shutdown_seconds": round(elapsed, 3), "new_connections_refused_seconds": round(first_refusal, 3),
|
||||
"exit_code": state["ExitCode"], "oom_killed": state["OOMKilled"]}
|
||||
print("PASS: SIGTERM with unfinished request:", json.dumps(result["sigterm"]), flush=True)
|
||||
finally:
|
||||
compose("down", "--volumes", "--timeout", "10")
|
||||
print("Removed only temporary Compose project and its test volumes:", project)
|
||||
pending.communicate(timeout=10)
|
||||
compose("start", "api")
|
||||
script("wait-ready.sh")
|
||||
|
||||
def load_action(label, action, target=None):
|
||||
client = Client(base, timeout=2)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
original = client.message(alice, chat, "До воздействия")["json"]
|
||||
stop = threading.Event()
|
||||
lock = threading.Lock()
|
||||
successes, errors, confirmed = [], [], {}
|
||||
started = time.monotonic()
|
||||
|
||||
def worker(index):
|
||||
c = Client(base, timeout=2)
|
||||
key = uuid4().hex
|
||||
while not stop.is_set():
|
||||
for method in ("POST", "GET"):
|
||||
try:
|
||||
if method == "POST":
|
||||
response = c.message(alice, chat, "load-" + key, key=key)
|
||||
with lock:
|
||||
confirmed[response["json"]["id"]] = response["json"]
|
||||
key = uuid4().hex
|
||||
else:
|
||||
response = c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=bob, schema="MessagePage")
|
||||
with lock:
|
||||
successes.append((time.monotonic() - started, method,
|
||||
response["headers"]["X-Instance-Id"], response["elapsed"]))
|
||||
except Failure as exc:
|
||||
with lock:
|
||||
errors.append((time.monotonic() - started, method, str(exc)))
|
||||
stop.wait(0.05)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
futures = [pool.submit(worker, i) for i in range(4)]
|
||||
time.sleep(1)
|
||||
action_start = time.monotonic() - started
|
||||
try:
|
||||
action_info = action()
|
||||
action_end = time.monotonic() - started
|
||||
# Охватывает обнаружение отказа и устойчивую работу после него.
|
||||
time.sleep(max(3, 15 - (action_end - action_start)))
|
||||
finally:
|
||||
stop.set()
|
||||
for future in futures:
|
||||
future.result()
|
||||
elapsed = time.monotonic() - started
|
||||
items = history(client, bob, chat)
|
||||
by_id = {m["id"]: m for m in items}
|
||||
assert len(items) == len(by_id) == len({m["text"] for m in items}), "Повтор создал дубль"
|
||||
assert by_id.get(original["id"]) == original
|
||||
assert all(by_id.get(mid) == msg for mid, msg in confirmed.items()), "Потеря подтверждённого сообщения"
|
||||
after = [s for s in successes if s[0] >= action_end]
|
||||
assert {s[1] for s in after} == {"POST", "GET"}, "Нет чтений/записей после воздействия"
|
||||
recovery = {method: round(min(s[0] for s in successes if s[0] >= action_start and s[1] == method) - action_start, 3)
|
||||
for method in ("POST", "GET")}
|
||||
assert max(recovery.values()) <= 10, recovery
|
||||
max_gap = {}
|
||||
for method in ("POST", "GET"):
|
||||
moments = sorted(s[0] for s in successes if s[1] == method)
|
||||
max_gap[method] = round(max(b - a for a, b in zip(moments, moments[1:])), 3)
|
||||
assert max(max_gap.values()) <= 10, max_gap
|
||||
if target:
|
||||
assert target not in {s[2] for s in after[-20:]}, "Остановленная реплика ещё отвечает"
|
||||
buckets = []
|
||||
for second in range(int(elapsed) + 1):
|
||||
buckets.append({"second": second, "successes": sum(second <= s[0] < second + 1 for s in successes),
|
||||
"errors": sum(second <= e[0] < second + 1 for e in errors)})
|
||||
latencies = sorted(s[3] * 1000 for s in successes)
|
||||
summary = {"label": label, "duration_seconds": round(elapsed, 3), "successful_requests": len(successes),
|
||||
"successful_writes": len(confirmed), "errors": len(errors), "successful_rps": round(len(successes) / elapsed, 2),
|
||||
"first_success_after_action_seconds": recovery, "maximum_success_gap_seconds": max_gap,
|
||||
"action_start_seconds": round(action_start, 3), "action_end_seconds": round(action_end, 3),
|
||||
"p50_ms": round(latencies[len(latencies) // 2], 3),
|
||||
"p95_ms": round(latencies[int(len(latencies) * .95)], 3),
|
||||
"confirmed_data_preserved": True, "duplicate_messages": 0,
|
||||
"instances": sorted({s[2] for s in successes}), "per_second": buckets,
|
||||
"error_samples": errors[:5], "action": action_info}
|
||||
print(json.dumps({k: v for k, v in summary.items() if k not in ("per_second", "error_samples", "action")}, ensure_ascii=False), flush=True)
|
||||
return summary
|
||||
|
||||
print("Command: ./scripts/check-docker.sh; project:", project, flush=True)
|
||||
print("Docker:", result["docker"], flush=True)
|
||||
try:
|
||||
script("start.sh")
|
||||
initial = inspect_all()
|
||||
result["containers"] = [metadata(info) for info in initial]
|
||||
assert len(apis()) == 2
|
||||
for info in initial:
|
||||
assert info["HostConfig"]["Memory"] > 0 and info["HostConfig"]["NanoCpus"] > 0
|
||||
if info["Config"]["Labels"]["com.docker.compose.service"] != "lb":
|
||||
assert not info["HostConfig"]["PortBindings"]
|
||||
for info in apis():
|
||||
assert docker("exec", info["Id"], "id", "-u") == "10001"
|
||||
assert all(m["Destination"].startswith("/run/secrets/") for m in info["Mounts"])
|
||||
print("PASS: 2 real API containers, CPU/RAM limits, API non-root and no public ports; only LB published", flush=True)
|
||||
subprocess.run([str(ROOT / "scripts/check.sh")], cwd=ROOT, env=env, check=True, timeout=240)
|
||||
result["api_tests"] = "public smoke + 28 student tests passed"
|
||||
subprocess.run([str(ROOT / "scripts/demo.sh")], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, timeout=30)
|
||||
assert sql("SELECT count(*) FROM schema_migrations") == "2"
|
||||
count = sql("SELECT count(*) FROM messages")
|
||||
for _ in range(2):
|
||||
compose("run", "--rm", "migrate")
|
||||
assert sql("SELECT count(*) FROM schema_migrations") == "2"
|
||||
assert sql("SELECT count(*) FROM messages") == count
|
||||
print("PASS: migrations only in one-shot service; repeated execution preserves data", flush=True)
|
||||
|
||||
replay_client = Client(base)
|
||||
replay_actor, _, _, replay_chat = replay_client.bootstrap()
|
||||
replay_key = uuid4().hex
|
||||
saved_message = replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"]
|
||||
before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
subprocess.run(["make", "test-persistence", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/restart.sh"],
|
||||
cwd=ROOT, env=env, check=True, timeout=180)
|
||||
after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
assert before.keys() == after.keys()
|
||||
assert all(before[cid]["started_at"] != after[cid]["started_at"] for cid in before)
|
||||
assert replay_client.message(replay_actor, replay_chat, "Повтор после рестарта", key=replay_key)["json"] == saved_message
|
||||
result["persistence"] = {"before": list(before.values()), "after": list(after.values()), "passed": True,
|
||||
"idempotency_replay_after_restart": True}
|
||||
print("PASS: both API, LB, PostgreSQL, Valkey actually restarted; session and confirmed data preserved", flush=True)
|
||||
|
||||
check_shutdown()
|
||||
|
||||
dependency_client = Client(base)
|
||||
actor = dependency_client.user("deps")
|
||||
result["dependency_readiness"] = []
|
||||
for dependency in ("valkey", "postgres"):
|
||||
try:
|
||||
compose("stop", "--timeout", "8", dependency)
|
||||
probe_id = apis()[0]["Id"]
|
||||
readiness = subprocess.run(["docker", "exec", probe_id, "python", "-m", "src.healthcheck"], capture_output=True, timeout=10)
|
||||
assert readiness.returncode == 1
|
||||
live = docker("exec", probe_id, "python", "-c",
|
||||
"from urllib.request import urlopen; print(urlopen('http://127.0.0.1:8080/health/live').status)")
|
||||
assert live == "200"
|
||||
deadline = time.monotonic() + 8
|
||||
while True:
|
||||
try:
|
||||
urlopen(base + "/health/ready", timeout=2).close()
|
||||
except HTTPError as error:
|
||||
if error.code == 503:
|
||||
break
|
||||
raise
|
||||
except OSError:
|
||||
# Уже отправленный запрос может истечь до исключения backend.
|
||||
pass
|
||||
assert time.monotonic() < deadline
|
||||
time.sleep(0.1)
|
||||
result["dependency_readiness"].append({"dependency": dependency, "api_live": 200, "api_ready": 503, "lb_ready": 503})
|
||||
print("PASS:", dependency, "outage: API live=200, ready=503, LB ready=503", flush=True)
|
||||
finally:
|
||||
compose("start", dependency)
|
||||
script("wait-ready.sh")
|
||||
dependency_client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
|
||||
subprocess.run(["make", "test-failover", "PYTHON=" + sys.executable, "ACTION_SCRIPT=scripts/stop-one.sh"],
|
||||
cwd=ROOT, env=env, check=True, timeout=90)
|
||||
assert sum(i["State"]["Running"] for i in apis()) == 1
|
||||
result["public_failover"] = {"passed": True, "containers_after": [metadata(i) for i in apis()]}
|
||||
compose("start", "api")
|
||||
script("wait-ready.sh")
|
||||
|
||||
result["failovers"] = []
|
||||
for info in apis():
|
||||
target = info["Config"]["Hostname"]
|
||||
|
||||
def stop_target():
|
||||
subprocess.run([str(ROOT / "scripts/stop-one.sh")], cwd=ROOT,
|
||||
env=dict(env, TARGET_INSTANCE_ID=target), check=True, timeout=10)
|
||||
stopped = json.loads(docker("inspect", info["Id"]))[0]
|
||||
assert not stopped["State"]["Running"]
|
||||
assert not stopped["State"]["OOMKilled"] and stopped["State"]["ExitCode"] == 0
|
||||
# Uvicorn пишет в stderr; получаем оба потока без вывода запросов.
|
||||
logs_result = subprocess.run(["docker", "logs", info["Id"]], capture_output=True, text=True, check=True)
|
||||
assert "Application shutdown complete" in logs_result.stdout + logs_result.stderr
|
||||
return metadata(stopped)
|
||||
|
||||
result["failovers"].append(load_action("stop " + target, stop_target, target))
|
||||
compose("start", "api")
|
||||
script("wait-ready.sh")
|
||||
|
||||
before = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
|
||||
def replace():
|
||||
script("rolling-update.sh")
|
||||
after = {i["Id"]: metadata(i) for i in inspect_all() if i["State"]["Running"]}
|
||||
old_api = {i["id"] for i in before.values() if i["service"] == "api"}
|
||||
new_api = {i["id"] for i in after.values() if i["service"] == "api"}
|
||||
assert len(new_api) == 2 and not old_api & new_api
|
||||
for cid, info in before.items():
|
||||
if info["service"] != "api":
|
||||
assert after[cid]["started_at"] == info["started_at"]
|
||||
return {"before": list(before.values()), "after": list(after.values())}
|
||||
|
||||
result["rolling_update"] = load_action("sequential API replacement", replace)
|
||||
result["passed"] = True
|
||||
print("PASS: all lab3 grade-4 checks completed", flush=True)
|
||||
finally:
|
||||
output = ROOT / "evidence" / "lab3-checks.json"
|
||||
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
compose("down", "--volumes", "--timeout", "8")
|
||||
print("Removed only temporary test containers and volumes:", project, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -2,6 +2,7 @@ from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -16,6 +17,8 @@ class ApiTestCase(unittest.TestCase):
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def assert_error(self, method, path, status, code, **kwargs):
|
||||
if method == "POST" and path.endswith("/messages"):
|
||||
kwargs["headers"] = {"Idempotency-Key": uuid4().hex, **kwargs.get("headers", {})}
|
||||
result = self.client.call(method, path, status, **kwargs)
|
||||
self.assertEqual(result["json"]["error"]["code"], code)
|
||||
return result["json"]["error"]
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import threading
|
||||
from uuid import uuid4
|
||||
|
||||
from helpers import ApiTestCase, Client
|
||||
|
||||
|
||||
class IdempotencyTests(ApiTestCase):
|
||||
def test_parallel_replay_across_replicas(self):
|
||||
key = uuid4().hex
|
||||
barrier = threading.Barrier(20)
|
||||
|
||||
def send(_):
|
||||
client = Client()
|
||||
barrier.wait(timeout=10)
|
||||
return client.message(self.alice, self.chat, "Одно сообщение 👋", key=key)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
responses = list(pool.map(send, range(20)))
|
||||
self.assertGreaterEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
|
||||
self.assertTrue(all(r["json"] == responses[0]["json"] for r in responses))
|
||||
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [responses[0]["json"]])
|
||||
|
||||
def test_key_format_and_missing_key(self):
|
||||
for key in (None, "", " ", "a b", "a/b", "a" * 129):
|
||||
with self.subTest(key=key):
|
||||
headers = {} if key is None else {"Idempotency-Key": key}
|
||||
self.client.call("POST", self.path + "/messages", 400, actor=self.alice,
|
||||
body={"text": "Текст"}, headers=headers)
|
||||
for key in ("A", "a" * 128, "ABCdef012._:-"):
|
||||
self.client.message(self.alice, self.chat, key, key=key)
|
||||
|
||||
def test_conflict_and_semantic_json_replay(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "Текст 👋", key=key)["json"]
|
||||
replay = self.client.call("POST", self.path + "/messages", 201, actor=self.alice,
|
||||
raw=json.dumps({"text": "Текст 👋"}, ensure_ascii=True, indent=2).encode(),
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": key},
|
||||
schema="Message")["json"]
|
||||
self.assertEqual(first, replay)
|
||||
self.assert_error("POST", self.path + "/messages", 409, "conflict", actor=self.alice,
|
||||
body={"text": "Другой"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.read_all(self.path + "/messages", self.bob, "MessagePage"), [first])
|
||||
|
||||
def test_scope_is_user_and_chat(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "Алиса", key=key)["json"]
|
||||
second = self.client.message(self.bob, self.chat, "Боб", key=key)["json"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "Другой чат", "member_ids": [self.alice["id"]]})["json"]
|
||||
third = self.client.message(self.alice, other, "Другой чат", key=key)["json"]
|
||||
self.assertEqual(len({first["id"], second["id"], third["id"]}), 3)
|
||||
|
||||
def test_replay_rechecks_session_and_access(self):
|
||||
key = uuid4().hex
|
||||
self.client.message(self.alice, self.chat, "Текст", key=key)
|
||||
self.client.call("POST", self.path + "/messages", 404, actor=self.eve,
|
||||
body={"text": "Текст"}, headers={"Idempotency-Key": key})
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
|
||||
self.client.call("POST", self.path + "/messages", 401, actor=self.alice,
|
||||
body={"text": "Текст"}, headers={"Idempotency-Key": key})
|
||||
Reference in New Issue
Block a user