ЛР 5 — асинхронная обработка и версии pipeline
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
# Как воспроизводятся отказы ЛР 5
|
||||
|
||||
`compose.fault.test.yaml` подключается только к изолированному Compose-проекту.
|
||||
В нём API, relay и worker получают общий тестовый каталог. Реализация атомарно
|
||||
переименовывает `POINT.arm` в `POINT.used`, записывает идентификатор в `POINT.hit`
|
||||
и ждёт `POINT.release` или своего дедлайна. Адаптер сверяет job ID с PostgreSQL
|
||||
перед остановкой процесса. Job, версия и исходный upload остаются прежними.
|
||||
|
||||
| Имя сценария | Marker | Что проверяем |
|
||||
| --- | --- | --- |
|
||||
| `commit-before-publish` | `before_publish.hit` | Принятая job и единственная unsent запись outbox переживают SIGKILL relay. После запуска исходная job доходит до ready. |
|
||||
| `publish-before-mark` | `after_publish.hit` | RabbitMQ подтвердил publish, а outbox ещё не помечен. Первый и повторный publish не создают два эффекта. Worker остановлен до обоих действий. |
|
||||
| `object-before-ack` | `after_objects.hit` | Файлы уже в S3, а job ещё processing. SIGKILL worker оставляет lease. После его истечения новая попытка завершает ту же job. |
|
||||
| `ready-before-ack` | `before_ack.hit` | Ready и варианты уже закоммичены. SIGKILL worker до ack проверяет повторную доставку без новой попытки. |
|
||||
| `bounded-processing-timeout-and-prefetch` | `after_objects.hit` | Точку оставляем удержанной до дедлайна. Проверка требует `processing_timeout`, новую попытку, тот же job ID и фактический prefetch из RabbitMQ. |
|
||||
| `retry-transient` | Изоляция только worker от S3 | RabbitMQ и PostgreSQL остаются доступны. Ожидаются retry в заданных пределах jitter, терминальный failed, явный replay после восстановления S3. |
|
||||
| `fail-permanent` | Тестовая порча SHA синтетического staging | Worker видит mismatch, пишет failed за одну попытку. Тест восстанавливает SHA и проверяет replay через настоящую операторскую команду. Ранее принятый Message по тому же ключу остаётся доступен, новый POST с failed-вложением возвращает 409. |
|
||||
| `mismatched-broker-envelope-DLQ` | Доставки с неверным job ID, attachment ID или pipeline version | RabbitMQ принимает и доставляет сообщения. Все три уходят в DLQ. Опубликованный результат остаётся прежним. |
|
||||
|
||||
Сценарий сохранности брокера останавливает worker, проверяет наличие доставки в
|
||||
durable очереди, останавливает relay перед рестартом RabbitMQ и сверяет число
|
||||
сообщений после запуска. Так relay не может скрыть утрату повторной публикацией.
|
||||
Повтор идёт через настоящую очередь. S3 проверяется фактическим listing, а
|
||||
PostgreSQL показывает опубликованное поколение, попытки, outbox и аудит replay.
|
||||
|
||||
## Интерфейс адаптера
|
||||
|
||||
`pipeline_action.py` использует текущую схему Compose и `/app/jobs` в
|
||||
`attachment-cleanup`. Базовые переменные передаёт `acceptance.py`. Оператор
|
||||
задаёт `LAB5_TEST_FAULT_HOST_DIR`, содержащий `.lab5-test-project` с именем
|
||||
изолированного проекта. Аргументы запускаются как argv:
|
||||
|
||||
- `reset`, `worker-stop`, `worker-start`, `relay-start`, `broker-restart`, `restart-apis`.
|
||||
- `arm POINT`, `await POINT ATTACHMENT_ID`, `crash POINT ATTACHMENT_ID`. `await` возвращает
|
||||
JSON с точкой, attachment ID и job ID из маркера. `crash` считывает
|
||||
статус задания и посылает SIGKILL в пределах окна точки одним вызовом.
|
||||
- `activate POINT ATTACHMENT_ID` и `clear POINT ATTACHMENT_ID` для retry/failed.
|
||||
- `inspect ATTACHMENT_ID`, `worker-limits`, `drain`, `failed ATTACHMENT_ID`,
|
||||
`replay ATTACHMENT_ID`, `redeliver ATTACHMENT_ID`, `invalid-job ATTACHMENT_ID`.
|
||||
|
||||
Код 78 сообщает, что необходимый компонент ещё не подключён. Другой ненулевой
|
||||
код показывает ошибку адаптера или невыполненное условие. Если сценарий остановлен
|
||||
вручную, можно вызвать `reset` в том же контексте проекта. HTTP-клиенты и вывод
|
||||
runner не сохраняют учётные данные.
|
||||
@@ -0,0 +1,91 @@
|
||||
# Приёмка лабораторной 5 на «4»
|
||||
|
||||
Это студенческие проверки. Обязательные документы: [рубрика ЛР 5](../../README.md),
|
||||
[накопительность и совместимость](../../COURSE.md), [семантика HTTP](../../contracts/README.md),
|
||||
[OpenAPI и примеры](../../contracts/), [инфраструктурный контракт](../../contracts/infrastructure.json),
|
||||
[публичные проверки](../../tests/README.md). Порядок защиты и доказательства сверяются с
|
||||
[REPORT.md](../../REPORT.md), [CONTRIBUTING.md](../../CONTRIBUTING.md), [MAINTAINERS.md](../../MAINTAINERS.md),
|
||||
[infra](../../infra/README.md), [examples](../../examples/requests.http) и [.env.example](../../.env.example).
|
||||
|
||||
| Сценарий | Что требует контракт или задание | Где доказательство |
|
||||
| --- | --- | --- |
|
||||
| Сохранённый HTTP и тексты | Ключ 1–128 ASCII, отсутствующий/неверный → 400, конфликт → 409 без эффекта. область пользователя/чата. семантическое равенство JSON. конкурентные повторы. отозванный токен. timeout после подтверждённого commit | `http` / `idempotency-lb`, история чата. timeout на реальном клиентском сокете, прокси пересылает POST в LB и не отдаёт ответ клиенту |
|
||||
| Проверка отзыва доступа на replay | Публичный API не меняет membership. В отдельной PostgreSQL-схеме тест имитирует отзыв уже выданного доступа, повторяет тот же POST и проверяет 404, состояние БД и неизменный replay после восстановления доступа | `TestMessageReplayRechecksCurrentChatMembership`. временное снятие FK ограничено тестовой схемой |
|
||||
| LB и отказ процесса | ≥2 живых API за опубликованным адресом LB, одинаковый токен. каждый API по очереди получает SIGTERM и остаётся остановленным до проверки. чтение подтверждённых данных и запись ≤10 с. старый Message воспроизводится другой репликой | `idempotency-lb`, `failover`. Docker state, X-Instance-Id, запросы и время восстановления |
|
||||
| Сохранность | Сессия, запись и ключ переживают реальный перезапуск API и хранилищ | `persistence`. StartedAt каждого процесса и прежний токен |
|
||||
| Readiness, hard limits, rolling | Live/ready с контрактными телами. неготовый API доступен из сети LB и отвечает 503, публичные запросы идут мимо него. CPU/RAM API заданы и нет обхода LB. мигратор один. обновление ровно одной реплики за шаг | `http`, `unready`, `resources`, `migrations`, `rolling`. Для rolling требуется операторский hook с образом кандидата |
|
||||
| ЛР 5, уровень 3 | Upload 202 после коммита метаданных, job и outbox. queued можно прикрепить, download → 409, worker остановлен. API и broker действительно перезапускаются, дубли не размножают запись. thumbnail и original | `TestAttachmentTxHTTP`, `pipeline-http`, `durable-broker-worker-stop-and-redelivery`, публичные make-цели |
|
||||
| ЛР 5, уровень 4 | Crop и WebP: измерения из данных, checksum, MIME, bytes. лимиты bytes/pixels и невалидный PNG. fault после COMMIT / до publish, после записи объекта / до ack, после ready / до ack. lease, retries/jitter/terminal failed и операторский replay. staging cleanup | `pipeline-http`, `pipeline-faults`. маркеры процесса, PostgreSQL, S3 list, аудит replay, RabbitMQ DLQ, HTTP |
|
||||
| Доказательства и рекомендации | Прогрев, интенсивность, длительность, RPS, ошибки, p50/95/99 и CPU/RAM, временная шкала и число записей. полный decode через установленный ImageMagick можно добавить флагом `--magick` | JSONL + логи make. Closed-loop даёт результаты конкретного стенда. проходного RPS нет |
|
||||
|
||||
Readiness и отсутствие опубликованных портов API обязательны по инфраструктурному контракту.
|
||||
CPU/RAM API, проверка SIGTERM с clean exit, Go проверка устаревшего доступа и rolling относятся к
|
||||
дополнительным условиям этого прогона. Для rolling установлен дополнительный критерий: запросы
|
||||
под нагрузкой не теряют подтверждённые сообщения и не возвращают ошибок во время обоих шагов.
|
||||
Сценарий нельзя объявить пройденным по одному заголовку. Исследовательский трек «5» не входит в прогон.
|
||||
|
||||
## Запуск
|
||||
|
||||
Для итогового прогона использовали Python 3.14.6, Go из `go.mod` и Docker Compose.
|
||||
У публичного клиента на Python 3.9 возможен отказ разбора дробных секунд
|
||||
RFC 3339, которые выдаёт Go. Для локального HTTP используйте
|
||||
изолированный учебный стенд. Команды из отдельной копии репозитория:
|
||||
|
||||
```sh
|
||||
./scripts/init-local.sh
|
||||
export LAB5_HTTP_PORT=18085 LAB5_POSTGRES_PORT=25485
|
||||
export LAB5_TEST_FAULT_HOST_DIR="$(mktemp -d)"
|
||||
printf '%s\n' highload-lab5-student > "$LAB5_TEST_FAULT_HOST_DIR/.lab5-test-project"
|
||||
chmod 777 "$LAB5_TEST_FAULT_HOST_DIR" # только новый тестовый каталог, чтобы UID контейнера мог писать маркеры
|
||||
export COMPOSE_PROJECT_NAME=highload-lab5-student
|
||||
cpfiles() {
|
||||
docker compose -p "$COMPOSE_PROJECT_NAME" -f compose.yaml \
|
||||
-f student-tests/lab5/compose.readiness.test.yaml \
|
||||
-f student-tests/lab5/compose.fault.test.yaml "$@"
|
||||
}
|
||||
cpfiles config --quiet
|
||||
cpfiles up -d --build
|
||||
make check
|
||||
go test ./... # интеграционные Go-тесты показывают SKIP без их переменных окружения
|
||||
|
||||
python3 student-tests/lab5/acceptance.py --scenario all \
|
||||
--base-url "http://127.0.0.1:$LAB5_HTTP_PORT" --project "$COMPOSE_PROJECT_NAME" --exercise \
|
||||
--compose-file compose.yaml --compose-file student-tests/lab5/compose.readiness.test.yaml \
|
||||
--compose-file student-tests/lab5/compose.fault.test.yaml \
|
||||
--store redis --store s3 --store rabbitmq --output /tmp/lab5-acceptance.jsonl
|
||||
# После прогона при необходимости: cpfiles stop
|
||||
```
|
||||
|
||||
Для быстрого профиля сохраняйте в **отдельной копии** `.env`:
|
||||
`JOB_TIMEOUT_SECONDS=14`, `JOB_LEASE_SECONDS=18`, `JOB_MAX_ATTEMPTS=3`,
|
||||
`JOB_RETRY_BASE_SECONDS=2`, `CLEANUP_GRACE_SECONDS=1`, `CLEANUP_INTERVAL_SECONDS=1`,
|
||||
`STAGING_RETENTION_SECONDS=600`, `WORKER_CONCURRENCY=1`, `WORKER_PREFETCH=1`.
|
||||
Учитывайте задержку Docker Desktop при физических рестартах. Миграциям нужно пустое окружение
|
||||
для проверки полного чистого bootstrap. Итоговый runner включает
|
||||
`make test`, `make test-persistence`, `make test-failover`. Вывод каждой цели сохраняется отдельно.
|
||||
Тестовый хук получает то же имя проекта и те же Compose-файлы.
|
||||
|
||||
При одной реплике можно отдельно запустить `--scenario http --base-url http://127.0.0.1:8080 --output ...`:
|
||||
Этот режим проверяет контрактный HTTP. Для LB и failover нужна топология из двух реплик.
|
||||
Флаги `--scenario` и `--compose-file` можно повторять. Для точечного повтора
|
||||
укажите `--case` с именем проверки из вывода runner. Смена сервисных имён,
|
||||
портов и диагностического образа curl задаётся в `--help`. Приёмка заменила
|
||||
временный `baseline.py` из начала ЛР 5, ожидавший upload `201 ready`.
|
||||
Ожидаемая отсутствующая инфраструктура/хук → **PENDING**, системная ошибка/невыполненное условие →
|
||||
**FAIL**, только наблюдавшееся условие → **PASS**. Коды запуска: 0 — все выбранные проверки
|
||||
прошли, 1 — есть FAIL, 2 — есть PENDING и нет FAIL. Строки без результатов не засчитываются.
|
||||
|
||||
`--roll-hook /abs/path/to/hook` вызывается один раз на каждый исходный контейнер, с
|
||||
`TARGET_CONTAINER_ID`, `TARGET_INSTANCE_ID`, `COMPOSE_PROJECT_NAME`, `BASE_URL`. Хук сам заменяет
|
||||
контейнер образом кандидата, сохраняет остальное и возвращает 0 после подключения кандидата;
|
||||
runner проверяет новый digest, связь с тем же LB, выдерживает окно нагрузки и проверяет,
|
||||
что мигратор не запускался снова. Пока такого хука нет, сценарий **PENDING**.
|
||||
Подробнее о fault hooks: [FAULT-HOOKS.md](FAULT-HOOKS.md).
|
||||
|
||||
Переменные Go-проверок: `LAB4_TEST_DATABASE_URL` (историческое имя fixture),
|
||||
`AUTH_TEST_DATABASE_URL`, `AUTH_TEST_REDIS_ADDR`, `MIGRATE_TEST_DATABASE_URL`. используйте
|
||||
изолированные БД/Redis. Для опциональных прежних сценариев auth/restart см. их SKIP-строки.
|
||||
Повторный прогон должен писать в новый файл. Не сохраняйте токены, env, секреты, содержимое БД
|
||||
или полные логи контейнеров.
|
||||
|
||||
Эксперимент на «5» описан в [VERSIONED.md](VERSIONED.md). Для него есть отдельный сценарий `pipeline-versioned`.
|
||||
@@ -0,0 +1,53 @@
|
||||
# ЛР 5. Трек 2: версия pipeline и повторная доставка
|
||||
|
||||
Гипотеза. Если worker публикует результат только для текущей версии и
|
||||
действующего поколения lease, валидные старые сообщения и опоздавшая попытка
|
||||
не изменят готовый результат v2. В S3 версии и поколения имеют разные ключи.
|
||||
Подтверждённое задание текущей версии переживает сбой worker и доходит до ready.
|
||||
|
||||
| Сценарий | Воздействие и критерий |
|
||||
| --- | --- |
|
||||
| Дубль v2 и устаревшая v1 | Довести v1 и v2 до ready. По очереди повторно опубликовать байты сохранённых валидных envelopе v2 и v1 в RabbitMQ. Очередь опустела, DLQ не выросла, длина истории попыток, ключи и опубликованные SHA не изменились. |
|
||||
| Reorder v2 → v1 | Остановить relay перед upload. Отложить исходную запись outbox v1 через `available_at`, поставить v2 штатным `jobs upgrade`. Дождаться ready v2 и только тогда отпустить исходную v1. Сверить идентичность envelope и порядок `sent_at`. У v1 ноль попыток. |
|
||||
| Crash до и после S3 | На v2 удержать worker перед первым PUT или сразу после записи всех объектов. Снять фактический listing (0 или 4 ключа поколения), послать SIGKILL до дедлайна и вернуть контейнер. Первая попытка истекает, новое поколение той же job завершает обработку. Исторический набор v1 остаётся целым, сироты и staging исчезают. |
|
||||
| Запоздавший worker v1 | Удержать живой процесс после записи объектов v1. Запустить второго worker и довести v2 до ready, затем отпустить прежний процесс до исходных deadline и lease. Получить его лог `job finalization rejected`, проверить ACK, ноль новых попыток v2, прежние ключи v2 и удаление четырёх неопубликованных объектов v1. |
|
||||
|
||||
При каждом переходе повторный `jobs upgrade` обязан вернуть тот же job ID и
|
||||
`queued=false`. Проверяется один outbox для новой job до инъекции дополнительных
|
||||
доставок. Используется один и тот же исходный PNG. Варианты проверяются через HTTP
|
||||
и повторным чтением S3 по сохранённым ключам. Сравниваются SHA-256, размеры,
|
||||
метаданные, номера версий и поколения, исходные байты. Опубликованные результаты
|
||||
v1 и v2 различимы по SHA, а v2 воспроизводится на одинаковом исходнике во всей серии.
|
||||
|
||||
Автоматизация подтверждает идемпотентность эффекта в наблюдавшихся окнах отказа.
|
||||
Брокер может доставить payload несколько раз, рабочий процесс может повторно
|
||||
вычислить и записать объекты. Успешным считается один опубликованный набор
|
||||
текущей версии. Измерения относятся к одному Docker-хосту и одному размеру файла.
|
||||
|
||||
## Запуск
|
||||
|
||||
Поднимите отдельный учебный проект с чистыми томами по [основной инструкции](README.md),
|
||||
с `compose.readiness.test.yaml` и `compose.fault.test.yaml`. Установите миграцию
|
||||
с `attachment_jobs.published_original_key` и текущий образ, поддерживающий `jobs upgrade`.
|
||||
В начале нужен один worker с `WORKER_CONCURRENCY=1` и `WORKER_PREFETCH=1`.
|
||||
Тест временно масштабирует его до двух процессов в последнем сценарии каждой серии.
|
||||
Фиксируйте фактические лимиты в локальной копии `.env`; профиль прогона использует
|
||||
`JOB_TIMEOUT_SECONDS=30`, `JOB_LEASE_SECONDS=36`, `CLEANUP_GRACE_SECONDS=1` и
|
||||
`CLEANUP_INTERVAL_SECONDS=1`. На медленном хосте окно старого worker можно увеличить,
|
||||
с теми же контрольными условиями по времени относительно исходного lease.
|
||||
|
||||
```sh
|
||||
python3 student-tests/lab5/acceptance.py --scenario pipeline-versioned --repetitions 3 \
|
||||
--base-url "http://127.0.0.1:$LAB5_HTTP_PORT" --project "$COMPOSE_PROJECT_NAME" --exercise \
|
||||
--compose-file compose.yaml --compose-file student-tests/lab5/compose.readiness.test.yaml \
|
||||
--compose-file student-tests/lab5/compose.fault.test.yaml --output /tmp/lab5-versioned.jsonl
|
||||
```
|
||||
|
||||
Выбор `--scenario all` по-прежнему запускает приёмку уровня 4. Трек добавляется
|
||||
явно через `--scenario pipeline-versioned`. При отсутствии миграции или
|
||||
каталога fault ожидается PENDING. Провал отдельного повтора сохраняется в
|
||||
строке `versioned_trial` и даёт ненулевой код запуска. Итоговая строка
|
||||
`versioned_summary` хранит число попыток эксперимента, min/median/max
|
||||
наблюдаемого времени до ready и стабильные SHA-256 результата v2.
|
||||
Для crash секундомер начинается перед SIGKILL. В остальных случаях он
|
||||
охватывает ожидание ready после ответа штатной команды upgrade или запуска relay.
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run Lab 5 checks against an isolated Compose stand and write JSONL evidence."""
|
||||
import argparse
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from checks import ROOT, Evidence, Failure, Pending, Probe, check, health, idempotency
|
||||
from pipeline import Pipeline, make_decoder, upload_rejects, variants
|
||||
from stand import Stand
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
TEST_HOOK = HERE / "compose_action.py"
|
||||
|
||||
|
||||
def arguments():
|
||||
cases = ("http", "idempotency-lb", "resources", "persistence", "failover",
|
||||
"unready", "rolling", "migrations", "pipeline-http", "pipeline-faults", "pipeline-versioned", "public", "all")
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--scenario", choices=cases, action="append", required=True)
|
||||
p.add_argument("--case", action="append", help="run only the named case within the selected scenario(s)")
|
||||
p.add_argument("--base-url", default=os.environ.get("BASE_URL"))
|
||||
p.add_argument("--ca-file", default=os.environ.get("CA_FILE"))
|
||||
p.add_argument("--output", required=True, help="new JSONL file; no overwrite")
|
||||
p.add_argument("--project", help="explicit disposable Compose project required for fault scenarios")
|
||||
p.add_argument("--exercise", action="store_true", help="allow fault actions on this isolated project")
|
||||
p.add_argument("--compose-file", action="append", default=[])
|
||||
for k, default in (("api", "api"), ("lb", "lb"), ("db", "postgres"), ("migrate", "migrate"),
|
||||
("db-user", "messenger"), ("db-name", "messenger")):
|
||||
p.add_argument("--" + k, default=default)
|
||||
p.add_argument("--store", action="append", help="additional persistence stores; repeat per service")
|
||||
p.add_argument("--api-port", type=int, default=8080)
|
||||
p.add_argument("--network", help="shared API/LB Docker network for diagnostics")
|
||||
p.add_argument("--probe-image", default="rustfs/rustfs:1.0.4",
|
||||
help="local image with curl, for direct health diagnostics from the LB namespace")
|
||||
p.add_argument("--workers", type=int, default=6)
|
||||
p.add_argument("--timeout", type=float, default=2)
|
||||
p.add_argument("--window", type=float, default=3)
|
||||
p.add_argument("--warmup", type=float, default=2)
|
||||
p.add_argument("--pipeline-timeout", type=int, default=120)
|
||||
p.add_argument("--repetitions", type=int, default=3, help="number of complete versioned experiment series")
|
||||
p.add_argument("--magick", help="optional path to ImageMagick 7 for full image decode")
|
||||
for k in ("restart", "stop", "unready", "ready", "roll", "pipeline"):
|
||||
p.add_argument("--" + k + "-hook", type=str)
|
||||
a = p.parse_args()
|
||||
if not a.base_url:
|
||||
p.error("--base-url (or BASE_URL) is required")
|
||||
url = urlsplit(a.base_url)
|
||||
if (url.scheme not in ("http", "https") or not url.hostname or url.username or url.password
|
||||
or url.query or url.fragment or url.path not in ("", "/")):
|
||||
p.error("use an HTTP(S) origin without credentials, query, path, or fragment")
|
||||
if not 2 <= a.workers <= 64 or not 0 < a.timeout <= 5 or not 2 <= a.window <= 30 or not 0 < a.warmup <= 30:
|
||||
p.error("workers=2..64, timeout=(0,5], window=2..30, warmup=(0,30]")
|
||||
if not 1 <= a.pipeline_timeout <= 600:
|
||||
p.error("pipeline timeout must be 1..600 s")
|
||||
if not 1 <= a.repetitions <= 10:
|
||||
p.error("repetitions must be 1..10")
|
||||
if a.store is None:
|
||||
a.store = ["redis", "s3", "rabbitmq"]
|
||||
if a.exercise and (not a.project or a.project == "highload-lab5"):
|
||||
p.error("--exercise requires --project for a disposable stand (not highload-lab5)")
|
||||
return a
|
||||
|
||||
|
||||
def control_env(a):
|
||||
import json
|
||||
return dict(os.environ, COMPOSE_PROJECT_NAME=a.project or "",
|
||||
LAB5_TEST_COMPOSE_FILES=json.dumps([str(Path(f).resolve()) for f in a.compose_file]),
|
||||
LAB5_TEST_API=a.api, LAB5_TEST_DB=a.db, LAB5_TEST_LB=a.lb,
|
||||
LAB5_TEST_DB_USER=a.db_user, LAB5_TEST_DB_NAME=a.db_name,
|
||||
LAB5_TEST_STORES=" ".join(a.store), PYTHONDONTWRITEBYTECODE="1")
|
||||
|
||||
|
||||
def safe_to_exercise(args):
|
||||
if not args.exercise:
|
||||
raise Pending("requires --exercise and a dedicated --project")
|
||||
|
||||
|
||||
def public_case(stand, mode, out):
|
||||
a, e = stand.a, stand.e
|
||||
if mode != "test":
|
||||
safe_to_exercise(a)
|
||||
apis = stand.public_topology()
|
||||
env = control_env(a)
|
||||
cmd = ["make", mode, "BASE_URL=" + stand.c.base, "PYTHON=" + sys.executable]
|
||||
if a.ca_file:
|
||||
cmd.append("CA_FILE=" + a.ca_file)
|
||||
if mode != "test":
|
||||
hook = a.restart_hook if mode == "test-persistence" else a.stop_hook
|
||||
# The default test-only hook is scoped to the explicit project and uses
|
||||
# the same scope passed to the student scenarios.
|
||||
hook = hook or str(TEST_HOOK)
|
||||
check(Path(hook).is_file() and os.access(hook, os.X_OK), "public action hook is not executable")
|
||||
cmd.append("ACTION_SCRIPT=" + str(Path(hook).resolve()))
|
||||
env["LAB5_HOOK_MODE"] = "restart" if mode == "test-persistence" else "stop-one"
|
||||
path = Path(out).with_suffix(f".{mode}.log")
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with path.open("xb") as log:
|
||||
result = subprocess.run(cmd, cwd=ROOT, env=env, stdout=log, stderr=subprocess.STDOUT, timeout=300)
|
||||
e.event("public_run", command=mode, exit_code=result.returncode, log=path.name,
|
||||
elapsed_s=time.monotonic() - start)
|
||||
check(result.returncode == 0, f"make {mode} returned {result.returncode}; see {path.name}")
|
||||
except subprocess.TimeoutExpired:
|
||||
raise Failure(f"make {mode} exceeded its timeout; see {path.name}") from None
|
||||
finally:
|
||||
if mode == "test-failover":
|
||||
before = {r["id"] for r in apis}
|
||||
rows = [r for r in stand.containers(a.api) if r["id"] in before and r["state"] == "exited"]
|
||||
if rows:
|
||||
stand.command("restore after teacher failover", ["docker", "start", *[r["id"] for r in rows]])
|
||||
|
||||
|
||||
def main():
|
||||
a = arguments()
|
||||
e = Evidence(a.output)
|
||||
e.event("environment", base=a.base_url, project=a.project, workers=a.workers, timeout=a.timeout,
|
||||
fault_window=a.window, warmup=a.warmup, python=platform.python_version(),
|
||||
host=platform.machine(), os=platform.system(), logical_cpus=os.cpu_count())
|
||||
c = Probe(a.base_url, a.ca_file, a.timeout, e)
|
||||
s = Stand(a, c)
|
||||
decoder = make_decoder(s, a.magick)
|
||||
if not a.pipeline_hook and "compose.fault.test.yaml" in [Path(f).name for f in a.compose_file]:
|
||||
a.pipeline_hook = str(HERE / "pipeline_action.py")
|
||||
pipeline = Pipeline(s, decoder)
|
||||
|
||||
def exercise(f):
|
||||
def wrapper():
|
||||
safe_to_exercise(a)
|
||||
f()
|
||||
return wrapper
|
||||
|
||||
def idem_lb():
|
||||
s.public_topology()
|
||||
idempotency(c, a.workers, known_instances=s.a_ids)
|
||||
|
||||
def readiness():
|
||||
# Use the bundled hook only with its explicit edge network override.
|
||||
explicit = [Path(f).name for f in a.compose_file]
|
||||
if "compose.readiness.test.yaml" in explicit:
|
||||
a.unready_hook = a.unready_hook or str(TEST_HOOK)
|
||||
a.ready_hook = a.ready_hook or str(TEST_HOOK)
|
||||
s.unready()
|
||||
|
||||
def persist():
|
||||
previous = a.restart_hook
|
||||
a.restart_hook = previous or str(TEST_HOOK)
|
||||
try:
|
||||
s.persistence()
|
||||
finally:
|
||||
a.restart_hook = previous
|
||||
|
||||
def versioned():
|
||||
from versioned import series
|
||||
series(pipeline, a.repetitions)
|
||||
|
||||
# The test-only restart hook uses the same Compose file/service selection.
|
||||
os.environ.update(control_env(a))
|
||||
os.environ["LAB5_HOOK_MODE"] = "restart"
|
||||
groups = {
|
||||
"http": [("health", lambda: health(c)), ("idempotency", lambda: idempotency(c, a.workers))],
|
||||
"idempotency-lb": [("idempotency-across-LB", idem_lb)],
|
||||
"resources": [("CPU-RAM-ports", s.resources)],
|
||||
"migrations": [("single-migration-start", lambda: (s.public_topology(), s.migration_snapshot()))],
|
||||
"persistence": [("persistent-idempotency", exercise(persist))],
|
||||
"failover": [("each-SIGTERM-read-write-with-load", exercise(s.failover))],
|
||||
"unready": [("LB-excludes-unready-API", exercise(readiness))],
|
||||
"rolling": [("one-API-at-a-time-under-load", exercise(s.rolling))],
|
||||
"pipeline-http": [("upload-byte-pixel-media-limits", lambda: upload_rejects(c)),
|
||||
("async-output-variants", lambda: variants(c, min(60, a.pipeline_timeout), decoder))],
|
||||
"pipeline-faults": [
|
||||
("durable-broker-worker-stop-and-redelivery", exercise(pipeline.durable)),
|
||||
("crash-COMMIT-before-publish", exercise(lambda: pipeline.crash("commit-before-publish"))),
|
||||
("crash-relay-after-confirm-before-mark", exercise(lambda: pipeline.crash("publish-before-mark"))),
|
||||
("crash-object-before-ack-lease", exercise(lambda: pipeline.crash("object-before-ack"))),
|
||||
("crash-ready-before-ack", exercise(lambda: pipeline.crash("ready-before-ack"))),
|
||||
("bounded-processing-timeout-and-prefetch", exercise(pipeline.bounded_processing)),
|
||||
("mismatched-broker-envelope-DLQ", exercise(pipeline.malformed_job)),
|
||||
("backoff-jitter-permanent-failed-replay", exercise(pipeline.retry_replay)),
|
||||
],
|
||||
"pipeline-versioned": [("pipeline-versioned-series", exercise(versioned))],
|
||||
"public": [(f"make-{m}", lambda m=m: public_case(s, m, a.output))
|
||||
for m in ("test", "test-persistence", "test-failover")],
|
||||
}
|
||||
if "all" in a.scenario:
|
||||
selectors = [name for name in groups if name != "pipeline-versioned" or name in a.scenario]
|
||||
# The LB case covers HTTP idempotency as well; avoid a duplicate run.
|
||||
groups["http"] = groups["http"][:1]
|
||||
else:
|
||||
selectors = list(dict.fromkeys(a.scenario))
|
||||
if "idempotency-lb" in selectors and "http" in selectors:
|
||||
groups["http"] = groups["http"][:1]
|
||||
selected = [(label, fn) for group in selectors for label, fn in groups[group]]
|
||||
if a.case:
|
||||
check(set(a.case) <= {label for label, _ in selected}, "--case is outside the selected scenarios")
|
||||
selected = [(label, fn) for label, fn in selected if label in a.case]
|
||||
results = []
|
||||
try:
|
||||
for label, fn in selected:
|
||||
results.append(e.case(label, fn))
|
||||
e.event("summary", **{k: results.count(k) for k in ("PASS", "FAIL", "PENDING")})
|
||||
return 1 if "FAIL" in results else (2 if "PENDING" in results else 0)
|
||||
finally:
|
||||
e.file.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (Failure, OSError) as exc:
|
||||
print("FAIL:", exc if isinstance(exc, Failure) else type(exc).__name__, file=sys.stderr)
|
||||
raise SystemExit(1) from None
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Shared assertions and safe evidence for Lab 5 acceptance."""
|
||||
import base64
|
||||
from collections import Counter
|
||||
import concurrent.futures
|
||||
import http.client
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check
|
||||
from resilience import history
|
||||
|
||||
IO_ERRORS = (OSError, http.client.HTTPException)
|
||||
|
||||
|
||||
class Pending(Exception):
|
||||
"""A scenario has no configured infrastructure; exit status is not zero."""
|
||||
|
||||
|
||||
class Evidence:
|
||||
def __init__(self, path):
|
||||
self.started = time.monotonic()
|
||||
self.lock = threading.Lock()
|
||||
self.phase = "setup"
|
||||
self.file = Path(path).open("x", encoding="utf-8", buffering=1)
|
||||
|
||||
def event(self, event, **fields):
|
||||
with self.lock:
|
||||
line = {"event": event, "t_s": round(time.monotonic() - self.started, 6),
|
||||
"phase": self.phase, **fields}
|
||||
self.file.write(json.dumps(line, ensure_ascii=False) + "\n")
|
||||
return line
|
||||
|
||||
def case(self, name, fn):
|
||||
self.phase = name
|
||||
print(f"RUN: {name}", flush=True)
|
||||
try:
|
||||
fn()
|
||||
except Pending as exc:
|
||||
status, note = "PENDING", str(exc)
|
||||
except (Failure, ValueError, OSError, http.client.HTTPException) as exc:
|
||||
status, note = "FAIL", str(exc) if isinstance(exc, Failure) else type(exc).__name__
|
||||
else:
|
||||
status, note = "PASS", ""
|
||||
self.event("result", status=status, note=note)
|
||||
print(f"{status}: {name}" + (f" — {note}" if note else ""), flush=True)
|
||||
return status
|
||||
|
||||
|
||||
class ObservedOpener:
|
||||
def __init__(self, opener, capture):
|
||||
self.opener = opener
|
||||
self.capture = capture
|
||||
|
||||
def open(self, request, **kwargs):
|
||||
from urllib.error import HTTPError
|
||||
try:
|
||||
response = self.opener.open(request, **kwargs)
|
||||
except HTTPError as response:
|
||||
self.capture(response)
|
||||
raise
|
||||
self.capture(response)
|
||||
return response
|
||||
|
||||
|
||||
class Probe(Client):
|
||||
def __init__(self, base, ca, timeout, evidence):
|
||||
super().__init__(base, ca, timeout=timeout)
|
||||
self.ca = ca
|
||||
self.evidence = evidence
|
||||
self.local = threading.local()
|
||||
self.opener = ObservedOpener(self.opener, self.capture)
|
||||
|
||||
def capture(self, response):
|
||||
self.local.status = response.code
|
||||
self.local.instance = response.headers.get("X-Instance-Id")
|
||||
self.local.request_id = response.headers.get("X-Request-Id")
|
||||
|
||||
def call(self, method, path, *args, **kwargs):
|
||||
self.local.status = self.local.instance = self.local.request_id = None
|
||||
started = time.monotonic()
|
||||
result = None
|
||||
try:
|
||||
result = super().call(method, path, *args, **kwargs)
|
||||
return result
|
||||
except IO_ERRORS as exc:
|
||||
raise Failure(f"{method}: {type(exc).__name__} while reading response") from None
|
||||
finally:
|
||||
self.evidence.event("http", method=method, path=path.split("?")[0],
|
||||
status=self.local.status, instance=self.local.instance,
|
||||
request_id=self.local.request_id, ok=result is not None,
|
||||
elapsed_s=time.monotonic() - started)
|
||||
|
||||
|
||||
def key():
|
||||
return uuid.uuid4().hex
|
||||
|
||||
|
||||
def message_path(chat):
|
||||
return f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
|
||||
def post(c, actor, chat, k, text, *, status=201, body=None, code=None):
|
||||
r = c.call("POST", message_path(chat), status, actor=actor,
|
||||
headers={} if k is None else {"Idempotency-Key": k},
|
||||
body={"text": text} if body is None else body, schema="Message")
|
||||
if status == 201:
|
||||
m = r["json"]
|
||||
check((m["chat_id"], m["sender_id"], m["text"], m["attachment_ids"]) ==
|
||||
(chat["id"], actor["id"], text, (body or {}).get("attachment_ids", [])),
|
||||
"Message fields differ from POST")
|
||||
elif code:
|
||||
check(r["json"]["error"]["code"] == code, f"expected error code {code}")
|
||||
if status == 401:
|
||||
check(r["headers"].get("WWW-Authenticate") == 'Bearer realm="messenger"',
|
||||
"incorrect Bearer challenge")
|
||||
return r
|
||||
|
||||
|
||||
def health(c):
|
||||
for endpoint in ("live", "ready"):
|
||||
r = c.call("GET", f"/health/{endpoint}", schema="Health")
|
||||
check(r["json"] == {"status": "ok"}, f"/health/{endpoint}: unexpected payload")
|
||||
|
||||
|
||||
def assert_history(c, actor, chat, expected):
|
||||
actual = history(c, actor, chat)
|
||||
check(len(actual) == len(expected) and {m["id"]: m for m in actual} ==
|
||||
{m["id"]: m for m in expected}, "history has a missing, changed or extra Message")
|
||||
|
||||
|
||||
def idempotency(c, workers, known_instances=None):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
|
||||
body={"title": "Independent key scope", "member_ids": [alice["id"]]})["json"]
|
||||
for bad in (None, "", "a" * 129, "a b", "a/b", "a@b", "nonASCII-é"):
|
||||
post(c, alice, chat, bad, "must not persist", status=400, code="invalid_request")
|
||||
assert_history(c, bob, chat, [])
|
||||
|
||||
k, upper = "A", ("AZaz09._:-" * 13)[:128]
|
||||
check(len(upper) == 128, "length-128 fixture")
|
||||
first = post(c, alice, chat, k, "Сообщение")["json"]
|
||||
for body in (None, {"attachment_ids": [], "text": "Сообщение"},
|
||||
{"text": "Сообщение", "attachment_ids": []}):
|
||||
check(post(c, alice, chat, k, "Сообщение", body=body)["json"] == first,
|
||||
"same semantic JSON must return the same 201 Message")
|
||||
post(c, alice, chat, k, "different text", status=409, code="conflict")
|
||||
assert_history(c, bob, chat, [first])
|
||||
boundary = post(c, alice, chat, upper, "128-byte key")["json"]
|
||||
check(post(c, alice, chat, upper, "128-byte key")["json"] == boundary, "max-key replay changed")
|
||||
user_scope = post(c, bob, chat, k, "another user")["json"]
|
||||
chat_scope = post(c, alice, other, k, "another chat")["json"]
|
||||
check(len({first["id"], user_scope["id"], chat_scope["id"]}) == 3, "key leaked across scopes")
|
||||
assert_history(c, alice, other, [chat_scope])
|
||||
post(c, eve, chat, k, "Сообщение", status=404, code="not_found")
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
post(c, alice, chat, k, "Сообщение", status=401, code="unauthorized")
|
||||
reg = alice["registration"]
|
||||
basic = base64.b64encode(f'{reg["username"]}:{reg["password"]}'.encode()).decode()
|
||||
session = c.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||||
headers={"Authorization": "Basic " + basic})["json"]
|
||||
alice = {**alice, "token": session["token"]}
|
||||
check(post(c, alice, chat, k, "Сообщение")["json"] == first, "key unexpectedly scoped to session")
|
||||
|
||||
concurrent_key = key()
|
||||
barrier = threading.Barrier(workers, timeout=10)
|
||||
|
||||
def race(_):
|
||||
barrier.wait()
|
||||
return post(c, alice, chat, concurrent_key, "same concurrent request")
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(race, range(workers)))
|
||||
m = responses[0]["json"]
|
||||
check(all(r["json"] == m for r in responses), "concurrent requests returned different Messages")
|
||||
instances = {r["headers"]["X-Instance-Id"] for r in responses}
|
||||
c.evidence.event("concurrent_posts", attempts=workers, instances=sorted(instances), message=m["id"])
|
||||
assert_history(c, bob, chat, [first, boundary, user_scope, m])
|
||||
|
||||
lost_key, lost_text = key(), "commit with response unobserved by sender"
|
||||
recorded = timeout_after_commit(c, alice, bob, chat, lost_key, lost_text)
|
||||
check(post(c, alice, chat, lost_key, lost_text)["json"] == recorded,
|
||||
"retry after loss of response changed Message")
|
||||
assert_history(c, bob, chat, [first, boundary, user_scope, m, recorded])
|
||||
if known_instances is not None:
|
||||
check(len(instances) >= 2 and instances <= known_instances,
|
||||
"concurrent POSTs did not reach two API replicas of this project")
|
||||
|
||||
|
||||
def timeout_after_commit(c, actor, reader, chat, k, text):
|
||||
# One shot loopback relay. The caller times out waiting for a response
|
||||
# which the relay intentionally withholds after forwarding through the LB.
|
||||
target = urlsplit(c.base)
|
||||
cls = http.client.HTTPConnection if target.scheme == "http" else http.client.HTTPSConnection
|
||||
opts = {} if target.scheme == "http" else {"context": ssl.create_default_context(cafile=c.ca)}
|
||||
received = {}
|
||||
finished, release = threading.Event(), threading.Event()
|
||||
|
||||
class DropResponse(BaseHTTPRequestHandler):
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_POST(self):
|
||||
upstream = cls(target.hostname, target.port, timeout=c.timeout, **opts)
|
||||
try:
|
||||
payload = self.rfile.read(int(self.headers["Content-Length"]))
|
||||
headers = {h: self.headers[h] for h in ("Content-Type", "Idempotency-Key", "Authorization")}
|
||||
upstream.request("POST", self.path, body=payload, headers=headers)
|
||||
with upstream.getresponse() as response:
|
||||
received["status"] = response.status
|
||||
received["instance"] = response.getheader("X-Instance-Id")
|
||||
if response.status == 201:
|
||||
received["message"] = json.loads(response.read(1024 * 1024))
|
||||
except (ValueError, OSError, http.client.HTTPException):
|
||||
received["error"] = "upstream connection or invalid response"
|
||||
finally:
|
||||
upstream.close()
|
||||
finished.set()
|
||||
release.wait(8)
|
||||
|
||||
with HTTPServer(("127.0.0.1", 0), DropResponse) as relay:
|
||||
relay.timeout = 3
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as jobs:
|
||||
served = jobs.submit(relay.handle_request)
|
||||
downstream = http.client.HTTPConnection(*relay.server_address, timeout=0.5)
|
||||
timed_out = False
|
||||
try:
|
||||
downstream.request("POST", message_path(chat), body=json.dumps({"text": text}),
|
||||
headers={"Content-Type": "application/json",
|
||||
"Idempotency-Key": k, "Authorization": "Bearer " + actor["token"]})
|
||||
try:
|
||||
downstream.getresponse().close()
|
||||
except TimeoutError:
|
||||
timed_out = True
|
||||
check(timed_out, "client did not actually time out on the dropped response")
|
||||
check(finished.wait(6) and received.get("status") == 201 and received.get("instance"),
|
||||
"relay did not observe committed upstream 201")
|
||||
outcome = received["message"]
|
||||
check(outcome in history(c, reader, chat), "original timed-out invocation did not durably commit")
|
||||
c.evidence.event("lost_response", downstream="TimeoutError", upstream_status=201,
|
||||
instance=received["instance"], message=outcome["id"])
|
||||
return outcome
|
||||
finally:
|
||||
release.set()
|
||||
downstream.close()
|
||||
served.result(timeout=10)
|
||||
|
||||
|
||||
def wait(fn, seconds, label):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = fn()
|
||||
except Failure:
|
||||
value = None
|
||||
if value and time.monotonic() <= deadline:
|
||||
return value
|
||||
time.sleep(0.1)
|
||||
raise Failure(label)
|
||||
|
||||
|
||||
def summarize(evidence, records, elapsed, window="full"):
|
||||
times = sorted(r["elapsed_s"] for r in records if r["ok"])
|
||||
percentiles = {f"p{p}_ms": round(times[math.ceil(len(times)*p/100)-1]*1000, 3) if times else None
|
||||
for p in (50, 95, 99)}
|
||||
evidence.event("load_summary", window=window, elapsed_s=elapsed, attempts=len(records), successes=len(times),
|
||||
successful_rps=len(times) / elapsed, failures=len(records)-len(times),
|
||||
error_ratio=(len(records)-len(times))/len(records) if records else None,
|
||||
statuses=dict(Counter(str(r["status"]) for r in records)), **percentiles)
|
||||
@@ -0,0 +1,40 @@
|
||||
# Optional only on the isolated Lab 5 acceptance project.
|
||||
# The worker can lose S3 while retaining its database and broker connections.
|
||||
x-fault-env: &fault-env
|
||||
LAB5_FAULT_DIR: /lab5-test-faults
|
||||
x-fault-mount: &fault-mount
|
||||
type: bind
|
||||
source: ${LAB5_TEST_FAULT_HOST_DIR:?create a fresh writable fault directory}
|
||||
target: /lab5-test-faults
|
||||
|
||||
services:
|
||||
api:
|
||||
environment: *fault-env
|
||||
volumes: [*fault-mount]
|
||||
networks:
|
||||
default: {}
|
||||
lab5_edge: {}
|
||||
lab5_object: {}
|
||||
relay:
|
||||
environment: *fault-env
|
||||
volumes: [*fault-mount]
|
||||
worker:
|
||||
environment: *fault-env
|
||||
volumes: [*fault-mount]
|
||||
networks:
|
||||
default: {}
|
||||
lab5_object: {}
|
||||
attachment-cleanup:
|
||||
networks:
|
||||
default: {}
|
||||
lab5_object: {}
|
||||
s3:
|
||||
networks:
|
||||
lab5_object: {}
|
||||
s3-init:
|
||||
networks:
|
||||
default: {}
|
||||
lab5_object: {}
|
||||
|
||||
networks:
|
||||
lab5_object: {}
|
||||
@@ -0,0 +1,13 @@
|
||||
# Optional on a dedicated test project. The LB can still reach API when a
|
||||
# single API is disconnected from the private dependency network.
|
||||
services:
|
||||
api:
|
||||
networks:
|
||||
default: {}
|
||||
lab5_edge: {}
|
||||
lb:
|
||||
networks:
|
||||
lab5_edge: {}
|
||||
|
||||
networks:
|
||||
lab5_edge: {}
|
||||
Executable
+94
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Student hook for teacher tests: explicit disposable Compose project only."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROJECT = os.environ.get("COMPOSE_PROJECT_NAME")
|
||||
API = os.environ.get("LAB5_TEST_API", "api")
|
||||
LB = os.environ.get("LAB5_TEST_LB", "lb")
|
||||
DB = os.environ.get("LAB5_TEST_DB", "postgres")
|
||||
STORES = os.environ.get("LAB5_TEST_STORES", "redis s3").split()
|
||||
|
||||
|
||||
def run(argv, timeout=30):
|
||||
result = subprocess.run(argv, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||||
if result.returncode:
|
||||
raise RuntimeError("Docker command failed")
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
|
||||
def main():
|
||||
if not PROJECT or PROJECT == "highload-lab5":
|
||||
raise RuntimeError("disposable COMPOSE_PROJECT_NAME is required")
|
||||
compose = ["docker", "compose", "--project-name", PROJECT]
|
||||
for file in json.loads(os.environ.get("LAB5_TEST_COMPOSE_FILES", "[]")):
|
||||
compose.extend(["--file", file])
|
||||
|
||||
def ids(service):
|
||||
return run(compose + ["ps", "-q", service]).split()
|
||||
|
||||
mode = os.environ.get("LAB5_HOOK_MODE")
|
||||
if mode in ("unready", "ready"):
|
||||
cid = os.environ.get("TARGET_CONTAINER_ID")
|
||||
if cid not in ids(API):
|
||||
# Compose ps abbreviates IDs whereas inspect returns the full ID.
|
||||
if not cid or not any(cid.startswith(i) for i in ids(API)):
|
||||
raise RuntimeError("selected API is not in the disposable project")
|
||||
net = PROJECT + "_default"
|
||||
if mode == "unready":
|
||||
run(["docker", "network", "disconnect", net, cid])
|
||||
else:
|
||||
current = json.loads(run(["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", cid]))
|
||||
if net not in current:
|
||||
run(["docker", "network", "connect", "--alias", API, net, cid])
|
||||
return
|
||||
if mode == "stop-one":
|
||||
alias = os.environ.get("TARGET_INSTANCE_ID")
|
||||
matches = [i for i in ids(API) if run(["docker", "inspect", "-f", "{{.Config.Hostname}}", i]) == alias]
|
||||
if len(matches) != 1:
|
||||
raise RuntimeError("could not resolve exactly one running API alias")
|
||||
run(["docker", "stop", "--signal", "SIGTERM", "--time", "5", matches[0]], 10)
|
||||
return
|
||||
if os.environ.get("LAB5_HOOK_MODE") != "restart":
|
||||
raise RuntimeError("LAB5_HOOK_MODE must be restart or stop-one")
|
||||
|
||||
def restart(selected, budget):
|
||||
if not selected:
|
||||
raise RuntimeError("selected service is not running")
|
||||
run(["docker", "restart", "--time", "8", *selected], budget)
|
||||
|
||||
def healthy(selected):
|
||||
deadline = time.monotonic() + 25
|
||||
for cid in selected:
|
||||
while time.monotonic() < deadline:
|
||||
state = run(["docker", "inspect", "-f",
|
||||
"{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}", cid])
|
||||
if state in ("healthy", "running"):
|
||||
break
|
||||
time.sleep(0.25)
|
||||
else:
|
||||
raise RuntimeError("container did not become healthy")
|
||||
|
||||
stores = [ids(s) for s in (DB, *STORES)]
|
||||
if any(not g for g in stores):
|
||||
raise RuntimeError("missing configured persistence store")
|
||||
store_ids = [cid for group in stores for cid in group]
|
||||
apis = ids(API)
|
||||
restart(store_ids, 30)
|
||||
healthy(store_ids)
|
||||
restart(apis, 24)
|
||||
healthy(apis)
|
||||
restart(ids(LB), 12)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
print("Compose hook failed:", exc if isinstance(exc, RuntimeError) else type(exc).__name__, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,115 @@
|
||||
// imageprobe exercises the ImageMagick runtime in its Docker image.
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func magick(args ...string) string {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, "magick", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
log.Fatalf("magick %v: %v\n%s", args, err, out)
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
|
||||
func checkImage(path, expected string, signature []byte, offset int) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if len(raw) < offset+len(signature) || !bytes.Equal(raw[offset:offset+len(signature)], signature) {
|
||||
log.Fatalf("%s has an unexpected header", path)
|
||||
}
|
||||
if got := magick("identify", "+ping", "-regard-warnings", "-format", "%m %wx%h", path); got != expected {
|
||||
log.Fatalf("unexpected output format or dimensions: %s", got)
|
||||
}
|
||||
fmt.Printf("PASS: decoded %s\n", expected)
|
||||
}
|
||||
|
||||
func checkDeadline(dir string) error {
|
||||
fifo := filepath.Join(dir, "incomplete.png")
|
||||
if err := syscall.Mkfifo(fifo, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "magick", "identify", "png:"+fifo)
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stderr = &stderr
|
||||
start := time.Now()
|
||||
if err := cmd.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
var writer *os.File
|
||||
for ctx.Err() == nil {
|
||||
file, err := os.OpenFile(fifo, os.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
if err == nil {
|
||||
writer = file
|
||||
break
|
||||
}
|
||||
if !errors.Is(err, syscall.ENXIO) {
|
||||
cancel()
|
||||
_ = cmd.Wait()
|
||||
return err
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
if writer == nil {
|
||||
return fmt.Errorf("magick never opened the input FIFO: %v: %s", cmd.Wait(), stderr.String())
|
||||
}
|
||||
defer writer.Close()
|
||||
if _, err := writer.Write([]byte("\x89PNG\r\n\x1a\n")); err != nil {
|
||||
cancel()
|
||||
_ = cmd.Wait()
|
||||
return err
|
||||
}
|
||||
err := cmd.Wait()
|
||||
elapsed := time.Since(start)
|
||||
var exit *exec.ExitError
|
||||
if !errors.Is(ctx.Err(), context.DeadlineExceeded) || !errors.As(err, &exit) ||
|
||||
exit.ProcessState.Sys().(syscall.WaitStatus).Signal() != syscall.SIGKILL || elapsed > 3*time.Second {
|
||||
return fmt.Errorf("expected deadline and SIGKILL, got %v, %v after %s: %s", ctx.Err(), err, elapsed, stderr.String())
|
||||
}
|
||||
fmt.Printf("PASS: CommandContext killed and reaped blocked magick after %s (deadline 1s)\n", elapsed.Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
log.SetFlags(0)
|
||||
if len(os.Args) != 2 {
|
||||
log.Fatal("usage: imageprobe /path/to/sample.png")
|
||||
}
|
||||
dir, err := os.MkdirTemp("", "imageprobe-")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
|
||||
fmt.Println(strings.SplitN(magick("-version"), "\n", 2)[0])
|
||||
input := os.Args[1]
|
||||
if got := magick("identify", "-format", "%m %wx%h", input); got != "PNG 320x200" {
|
||||
log.Fatalf("unexpected fixture: %s", got)
|
||||
}
|
||||
jpeg := filepath.Join(dir, "sample.jpg")
|
||||
webp := filepath.Join(dir, "sample.webp")
|
||||
magick(input, "-auto-orient", "-resize", "256x256>", "-background", "white", "-alpha", "remove", "-alpha", "off", "-strip", "-quality", "85", jpeg)
|
||||
magick(input, "-auto-orient", "-resize", "1280x1280>", "-strip", "-quality", "80", webp)
|
||||
checkImage(jpeg, "JPEG 256x160", []byte{0xff, 0xd8, 0xff}, 0)
|
||||
checkImage(webp, "WEBP 320x200", []byte("WEBP"), 8)
|
||||
if err := checkDeadline(dir); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Lab 5 grade 3+4: HTTP outputs and deterministic operator-injected faults."""
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import os
|
||||
import struct
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
from checks import ROOT, Failure, Pending, check, post, key, assert_history, wait
|
||||
from image_probe import jpeg_size
|
||||
|
||||
STAGING = ("queued", "processing")
|
||||
VARIANTS = {
|
||||
"thumbnail": ("image/jpeg", 256, 160),
|
||||
"crop": ("image/jpeg", 128, 128),
|
||||
"optimized": ("image/webp", 320, 200),
|
||||
}
|
||||
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def attachment_path(att):
|
||||
return f"/api/v1/attachments/{att['id']}"
|
||||
|
||||
|
||||
def metadata(c, actor, att):
|
||||
return c.call("GET", attachment_path(att), actor=actor, schema="Attachment")["json"]
|
||||
|
||||
|
||||
def until_status(c, actor, att, desired, timeout):
|
||||
started = time.monotonic()
|
||||
while time.monotonic()-started < timeout:
|
||||
current = metadata(c, actor, att)
|
||||
state = current["status"]
|
||||
if state == desired:
|
||||
check(time.monotonic()-started <= timeout, f"{desired} observed after deadline")
|
||||
c.evidence.event("attachment_state", attachment=att["id"], status=state,
|
||||
seconds=time.monotonic()-started)
|
||||
return current
|
||||
check(state in STAGING, f"wanted {desired}, reached terminal state {state}")
|
||||
time.sleep(0.25)
|
||||
raise Failure(f"attachment never reached {desired} within {timeout} seconds")
|
||||
|
||||
|
||||
def png_chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
|
||||
|
||||
|
||||
def oversized_pixels():
|
||||
# 40,010,000 pixels, but a small valid PNG; never allocate the decoded image.
|
||||
width, height = 10000, 4001
|
||||
enc = zlib.compressobj()
|
||||
row = bytes(width+1)
|
||||
compressed = b"".join(enc.compress(row) for _ in range(height)) + enc.flush()
|
||||
return (SAMPLE[:8] + png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0))
|
||||
+ png_chunk(b"IDAT", compressed) + png_chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def upload_rejects(c):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=limits.png"
|
||||
n = 10 * 1024 * 1024
|
||||
padded = SAMPLE[:-12] + png_chunk(b"npAD", bytes(n + 1 - len(SAMPLE) - 12)) + SAMPLE[-12:]
|
||||
check(len(padded) == n + 1, "invalid bytes-boundary fixture")
|
||||
for data, status, code in (
|
||||
(padded, 413, "payload_too_large"),
|
||||
(oversized_pixels(), 413, "payload_too_large"),
|
||||
(b"not a PNG", 415, "unsupported_media_type"),
|
||||
(SAMPLE[:30], 415, "unsupported_media_type"),
|
||||
):
|
||||
r = c.call("POST", path, status, actor=alice, raw=data, headers={"Content-Type": "image/png"})
|
||||
check(r["json"]["error"]["code"] == code, f"upload must return {code}")
|
||||
|
||||
|
||||
def decoded_webp_size(data):
|
||||
# Read actual bitstream dimensions. Check the complete RIFF framing, not
|
||||
# metadata or filename alone; full pixel decode can also run via ImageMagick.
|
||||
check(len(data) >= 20 and data[:4] == b"RIFF" and data[8:12] == b"WEBP"
|
||||
and int.from_bytes(data[4:8], "little") + 8 == len(data), "invalid WebP RIFF")
|
||||
i, canvas, image = 12, None, None
|
||||
while i < len(data):
|
||||
check(i + 8 <= len(data), "truncated WebP chunk")
|
||||
size = int.from_bytes(data[i+4:i+8], "little")
|
||||
name, start = data[i:i+4], i+8
|
||||
i = start+size+(size % 2)
|
||||
check(i <= len(data), "truncated WebP chunk body")
|
||||
if name == b"VP8X":
|
||||
check(size == 10, "invalid WebP canvas")
|
||||
canvas = tuple(1 + int.from_bytes(data[start+x:start+x+3], "little") for x in (4, 7))
|
||||
elif name == b"VP8 ":
|
||||
check(size >= 10 and data[start+3:start+6] == b"\x9d\x01\x2a", "invalid VP8 bitstream")
|
||||
image = tuple(int.from_bytes(data[start+x:start+x+2], "little") & 0x3fff for x in (6, 8))
|
||||
elif name == b"VP8L":
|
||||
check(size >= 5 and data[start] == 0x2f, "invalid VP8L bitstream")
|
||||
bits = int.from_bytes(data[start+1:start+5], "little")
|
||||
image = (1+(bits & 0x3fff), 1+((bits >> 14) & 0x3fff))
|
||||
check(image and (canvas is None or canvas == image), "WebP missing image or inconsistent canvas")
|
||||
return image
|
||||
|
||||
|
||||
def verify_ready(c, reader, queued, ready, *, decoder=None):
|
||||
stable = ("id", "chat_id", "owner_id", "filename", "content_type", "sha256", "size_bytes", "created_at")
|
||||
check(all(ready[k] == queued[k] for k in stable), "original metadata changed from queued to ready")
|
||||
check(ready["status"] == "ready" and ready["error_code"] is None, "invalid ready state")
|
||||
entries = {v["name"]: v for v in ready["variants"]}
|
||||
check(len(ready["variants"]) == len(entries) and set(entries) >= set(VARIANTS),
|
||||
"ready requires exactly one thumbnail, crop and optimized variant each")
|
||||
path = attachment_path(ready) + "/content"
|
||||
original = c.call("GET", path, actor=reader)
|
||||
check(original["bytes"] == SAMPLE and original["headers"].get_content_type() == "image/png",
|
||||
"published original changed")
|
||||
for name, (mime, w, h) in VARIANTS.items():
|
||||
v = entries[name]
|
||||
r = c.call("GET", f"{path}?variant={name}", actor=reader)
|
||||
data = r["bytes"]
|
||||
check((v["content_type"], v["width"], v["height"]) == (mime, w, h), f"{name}: metadata differs")
|
||||
check(r["headers"].get_content_type() == mime and len(data) == v["size_bytes"]
|
||||
and hashlib.sha256(data).hexdigest() == v["sha256"], f"{name}: MIME/size/hash mismatch")
|
||||
size = jpeg_size(data) if mime == "image/jpeg" else decoded_webp_size(data)
|
||||
check(size == (w, h), f"{name}: wrong dimensions in image bytes")
|
||||
if decoder:
|
||||
decoder(data, mime, w, h)
|
||||
c.evidence.event("variant", name=name, width=w, height=h, bytes=len(data), sha256=v["sha256"])
|
||||
return ready
|
||||
|
||||
|
||||
def variants(c, timeout, decoder):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
que, _ = c.attachment(alice, chat)
|
||||
check(que["variants"] == [] and que["error_code"] is None, "queued upload disclosed a result or error")
|
||||
ready = until_status(c, bob, que, "ready", timeout)
|
||||
verify_ready(c, bob, que, ready, decoder=decoder)
|
||||
c.call("GET", attachment_path(que), 404, actor=eve)
|
||||
c.call("GET", attachment_path(que) + "/content?variant=crop", 404, actor=eve)
|
||||
|
||||
|
||||
class Pipeline:
|
||||
def __init__(self, stand, decoder):
|
||||
self.stand, self.c, self.a = stand, stand.c, stand.a
|
||||
self.decoder = decoder
|
||||
|
||||
def action(self, command, *args):
|
||||
if not self.a.pipeline_hook:
|
||||
raise Pending("awaiting worker, broker, relay and app-specific fault adapter")
|
||||
path = Path(self.a.pipeline_hook).resolve()
|
||||
check(path.is_file() and os.access(path, os.X_OK), "pipeline hook is not executable")
|
||||
env = dict(os.environ, BASE_URL=self.c.base)
|
||||
if self.a.project:
|
||||
env["COMPOSE_PROJECT_NAME"] = self.a.project
|
||||
result = self.stand.command("pipeline " + command + (" " + args[0] if command in
|
||||
("arm", "await", "clear", "crash") else ""),
|
||||
[str(path), command, *args], env=env, timeout=self.a.pipeline_timeout,
|
||||
allow_failure=True)
|
||||
if result.returncode == 78:
|
||||
raise Pending(f"pipeline adapter prerequisite unavailable for {command}")
|
||||
if result.returncode and path == Path(__file__).with_name("pipeline_action.py"):
|
||||
# The bundled adapter emits bounded, whitelisted action labels.
|
||||
self.c.evidence.event("adapter_diagnostic", action=command, note=result.stderr.decode()[:300].strip())
|
||||
check(result.returncode == 0, f"pipeline adapter rejected {command} (exit {result.returncode})")
|
||||
if command in ("inspect", "await", "crash", "broker-restart", "restart-apis",
|
||||
"replay", "invalid-job", "worker-limits", "drain"):
|
||||
data = json.loads(result.stdout)
|
||||
check(isinstance(data, dict), "pipeline hook did not return an object")
|
||||
if command in ("broker-restart", "restart-apis", "invalid-job", "replay", "worker-limits", "drain"):
|
||||
self.c.evidence.event(command, evidence=data)
|
||||
return data
|
||||
return None
|
||||
|
||||
def snapshot(self, att):
|
||||
o = self.action("inspect", att["id"])
|
||||
fields = ("job_id", "jobs", "outbox", "staging_exists", "variant_objects", "failed_registered",
|
||||
"attempts", "max_attempts", "lease_seconds", "prefetch", "concurrency",
|
||||
"job_timeout_seconds", "worker_memory_bytes", "retry_base_seconds",
|
||||
"published", "generation", "result_count", "original_exists", "audit_replays", "envelope_valid",
|
||||
"scheduled_delays_ms")
|
||||
check(set(fields) <= o.keys(), "incomplete durable pipeline observation")
|
||||
check(isinstance(o["job_id"], str), "observation has no job ID")
|
||||
uuid.UUID(o["job_id"])
|
||||
attempts = [{k: row[k] for k in ("attempt", "kind", "delay_seconds", "error_code")} for row in o["attempts"]
|
||||
if isinstance(row, dict) and {"attempt", "kind", "delay_seconds", "error_code"} <= row.keys()]
|
||||
check(len(attempts) == len(o["attempts"]), "malformed attempt history")
|
||||
rows = {k: o[k] for k in fields}
|
||||
rows["attempts"] = attempts
|
||||
self.c.evidence.event("pipeline_state", attachment=att["id"], **rows)
|
||||
check(o["jobs"] == 1 and o["outbox"] >= 1 and o["envelope_valid"] is True,
|
||||
"lost, duplicated or invalid durable processing intent")
|
||||
check(all(isinstance(o[k], (int, float)) and o[k] > 0 for k in
|
||||
("max_attempts", "lease_seconds", "prefetch", "concurrency",
|
||||
"job_timeout_seconds", "worker_memory_bytes", "retry_base_seconds")),
|
||||
"unbounded worker/process configuration")
|
||||
check(o["job_timeout_seconds"] < o["lease_seconds"] and o["prefetch"] >= o["concurrency"],
|
||||
"worker lease/prefetch do not cover work admitted by worker")
|
||||
return o
|
||||
|
||||
def accepted(self, uploader, reader, chat):
|
||||
att, _ = self.c.attachment(uploader, chat)
|
||||
check(metadata(self.c, reader, att)["status"] in STAGING, "processed while worker must be held")
|
||||
fail = self.c.call("GET", attachment_path(att) + "/content", 409, actor=reader)
|
||||
check(fail["json"]["error"]["code"] == "conflict", "non-ready content must be a conflict")
|
||||
before = self.snapshot(att)
|
||||
check(before["staging_exists"] is True, "202 returned without durable staging")
|
||||
return att, before
|
||||
|
||||
def finished(self, reader, att, previous):
|
||||
ready = until_status(self.c, reader, att, "ready", self.a.pipeline_timeout)
|
||||
verify_ready(self.c, reader, att, ready, decoder=self.decoder)
|
||||
|
||||
def cleaned():
|
||||
row = self.snapshot(att)
|
||||
check(row["job_id"] == previous["job_id"], "job identity changed during recovery")
|
||||
if row["staging_exists"] or row["result_count"] != len(VARIANTS) + 1:
|
||||
return None
|
||||
check(row["original_exists"] is True and sorted(row["variant_objects"]) == sorted(VARIANTS),
|
||||
"S3 must contain the original and one published object per required variant")
|
||||
return row
|
||||
|
||||
current = wait(cleaned, self.a.pipeline_timeout, "staging or orphan results were not cleaned")
|
||||
return ready, current
|
||||
|
||||
def durable(self):
|
||||
self.action("reset")
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
try:
|
||||
self.action("worker-stop")
|
||||
att, previous = self.accepted(alice, bob, chat)
|
||||
msg = post(self.c, alice, chat, key(), "", body={"text": "", "attachment_ids": [att["id"]]})["json"]
|
||||
wait(lambda: self.snapshot(att)["published"] > 0, 30, "original job was not published")
|
||||
self.action("restart-apis")
|
||||
self.action("broker-restart")
|
||||
wait(lambda: self.c.call("GET", "/health/ready", schema="Health"), 60, "API not ready after restart")
|
||||
check(metadata(self.c, bob, att)["status"] == "queued", "job did not stay queued without worker")
|
||||
assert_history(self.c, bob, chat, [msg])
|
||||
self.action("worker-start")
|
||||
ready, prior = self.finished(bob, att, previous)
|
||||
self.action("relay-start")
|
||||
self.action("redeliver", att["id"])
|
||||
after, row = self.finished(bob, att, previous)
|
||||
check(after == ready and row["attempts"] == prior["attempts"],
|
||||
"duplicate broker event changed published effect or executed again")
|
||||
finally:
|
||||
self.action("reset")
|
||||
|
||||
def crash(self, point):
|
||||
self.action("reset")
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
try:
|
||||
if point == "publish-before-mark":
|
||||
self.action("worker-stop")
|
||||
self.action("arm", point)
|
||||
att, _ = self.c.attachment(alice, chat)
|
||||
mark = self.action("crash", point, att["id"])
|
||||
check(mark.get("point") == point and mark.get("attachment_id") == att["id"]
|
||||
and mark.get("signal") == "SIGKILL", "fault did not identify and kill the expected process")
|
||||
self.c.evidence.event("fault_reached", evidence=mark)
|
||||
if point == "publish-before-mark":
|
||||
self.action("worker-start")
|
||||
_, current = self.finished(bob, att, mark)
|
||||
self.action("drain")
|
||||
if point == "object-before-ack":
|
||||
check([row["kind"] for row in current["attempts"]] == ["lease_expired", "success"]
|
||||
and current["generation"] > mark["generation"], "lost processing lease was not recovered")
|
||||
if point == "ready-before-ack":
|
||||
check(current["generation"] == mark["generation"] and current["attempts"] == mark["attempts"],
|
||||
"redelivery started a new attempt after durable completion")
|
||||
finally:
|
||||
self.action("reset")
|
||||
|
||||
def bounded_processing(self):
|
||||
self.action("reset")
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
settings = wait(lambda: settings_with_consumer(self), 20, "no active worker consumer observed")
|
||||
limits = settings["image_limits"]
|
||||
check(all(value and value not in ("0", "unlimited", "0 seconds") for value in limits.values())
|
||||
and settings["worker_memory_bytes"] > 0, "worker or ImageMagick has unbounded resources")
|
||||
consumers = settings["consumers"]
|
||||
check(len(consumers) == settings["concurrency"] and all(
|
||||
row["active"] and row["ack_required"] and row["prefetch"] == settings["prefetch"] > 0
|
||||
for row in consumers), "broker consumer count, ack or prefetch differs from worker configuration")
|
||||
try:
|
||||
self.action("arm", "object-before-ack")
|
||||
att, _ = self.c.attachment(alice, chat)
|
||||
marker = self.action("await", "object-before-ack", att["id"])
|
||||
# Leave the worker paused. Its own work deadline must end the
|
||||
# attempt, record a temporary failure and permit automatic retry.
|
||||
_, recovered = self.finished(bob, att, {"job_id": marker["job_id"]})
|
||||
observed = [(x["kind"], x["error_code"]) for x in recovered["attempts"]]
|
||||
check(observed == [("temporary", "processing_timeout"), ("success", None)],
|
||||
"worker did not time out and finish the same job on retry")
|
||||
finally:
|
||||
self.action("reset")
|
||||
|
||||
def malformed_job(self):
|
||||
self.action("reset")
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
try:
|
||||
att, _ = self.c.attachment(alice, chat)
|
||||
ready = until_status(self.c, bob, att, "ready", self.a.pipeline_timeout)
|
||||
original, prior = self.finished(bob, att, self.snapshot(att))
|
||||
self.action("invalid-job", att["id"])
|
||||
later, after = self.finished(bob, att, prior)
|
||||
check(ready == original == later and prior["attempts"] == after["attempts"],
|
||||
"invalid broker message changed a ready result or created a new delivery effect")
|
||||
finally:
|
||||
self.action("reset")
|
||||
|
||||
def retry_replay(self):
|
||||
self.action("reset")
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
schedules = []
|
||||
try:
|
||||
for point in ("retry-transient", "retry-transient", "fail-permanent"):
|
||||
self.action("arm", point)
|
||||
att, _ = self.c.attachment(alice, chat)
|
||||
linked_key = key()
|
||||
linked_body = {"text": "", "attachment_ids": [att["id"]]}
|
||||
linked = None
|
||||
if point == "fail-permanent":
|
||||
linked = post(self.c, alice, chat, linked_key, "", body=linked_body)["json"]
|
||||
self.action("activate", point, att["id"])
|
||||
failed = until_status(self.c, bob, att, "failed", self.a.pipeline_timeout)
|
||||
code = "invalid_image" if point == "fail-permanent" else "retry_exhausted"
|
||||
check(failed["error_code"] == code and not failed["variants"], "wrong terminal error code/metadata")
|
||||
row = self.snapshot(att)
|
||||
self.action("failed", att["id"])
|
||||
check(row["failed_registered"] and row["staging_exists"], "failed job not registered or replay input lost")
|
||||
unavailable = self.c.call("GET", attachment_path(att) + "/content", 409, actor=bob)
|
||||
check(unavailable["json"]["error"]["code"] == "conflict", "failed attachment content is not a conflict")
|
||||
post(self.c, alice, chat, key(), "", body=linked_body, status=409, code="conflict")
|
||||
if linked:
|
||||
check(post(self.c, alice, chat, linked_key, "", body=linked_body)["json"] == linked,
|
||||
"prior accepted Message must remain replayable after its attachment fails")
|
||||
assert_history(self.c, bob, chat, [linked])
|
||||
attempts = row["attempts"]
|
||||
if point == "fail-permanent":
|
||||
check(len(attempts) == 1 and attempts[0]["kind"] == "permanent"
|
||||
and attempts[0]["delay_seconds"] is None, "permanent fault was retried")
|
||||
else:
|
||||
check(len(attempts) == row["max_attempts"] and len(attempts) >= 2
|
||||
and all(x["kind"] == "temporary" for x in attempts),
|
||||
"transient failure did not stop at configured attempt bound")
|
||||
delays = row["scheduled_delays_ms"]
|
||||
check(len(delays) == len(attempts)-1, "retry offsets were not recorded for each retry")
|
||||
for i, (ms, attempt) in enumerate(zip(delays, attempts[:-1])):
|
||||
upper = min(30, row["retry_base_seconds"] * (2 ** min(i, 4)))
|
||||
observed = attempt["delay_seconds"]
|
||||
check(1000 <= ms <= 1000 * upper and isinstance(observed, (int, float))
|
||||
and 0 < observed <= upper, "retry outside documented backoff and jitter bounds")
|
||||
schedules.append(delays)
|
||||
self.action("clear", point, att["id"])
|
||||
self.action("replay", att["id"])
|
||||
# A checksum fault changed metadata only within this test; replay
|
||||
# must serve the original fixture's data and checksum.
|
||||
ready, current = self.finished(bob, att, row)
|
||||
check(current["audit_replays"] == row["audit_replays"] + 1,
|
||||
"operator replay did not leave exactly one audit record")
|
||||
self.action("replay", att["id"])
|
||||
snapshot = self.snapshot(att)
|
||||
check(metadata(self.c, bob, att) == ready and snapshot["attempts"] == current["attempts"]
|
||||
and snapshot["outbox"] == current["outbox"], "replay of ready job was not a no-op")
|
||||
check(len(schedules) == 2 and schedules[0] != schedules[1], "identical retry schedules: jitter not observed")
|
||||
finally:
|
||||
self.action("reset")
|
||||
|
||||
|
||||
def settings_with_consumer(pipeline):
|
||||
settings = pipeline.action("worker-limits")
|
||||
return settings if settings["consumers"] else None
|
||||
|
||||
|
||||
def make_decoder(stand, executable):
|
||||
if not executable:
|
||||
return None
|
||||
|
||||
def decode(data, mime, w, h):
|
||||
# Bytes are synthetic and the command sees only a temporary file.
|
||||
suffix = ".jpg" if mime == "image/jpeg" else ".webp"
|
||||
with tempfile.NamedTemporaryFile(suffix=suffix) as file:
|
||||
file.write(data)
|
||||
file.flush()
|
||||
result = stand.command("decode downloaded " + mime, [
|
||||
executable, "identify", "+ping", "-regard-warnings", "-format", "%wx%h", file.name,
|
||||
], timeout=10)
|
||||
check(result.stdout.decode().strip() == f"{w}x{h}", "full image decode has wrong dimensions")
|
||||
return decode
|
||||
Executable
+477
@@ -0,0 +1,477 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fault adapter for the Lab 5 Compose implementation, only on an isolated project."""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from compose_action import API, DB, PROJECT, ROOT
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
BROKER = os.environ.get("LAB5_TEST_BROKER", "rabbitmq")
|
||||
WORKER = os.environ.get("LAB5_TEST_WORKER", "worker")
|
||||
RELAY = os.environ.get("LAB5_TEST_RELAY", "relay")
|
||||
CLEANER = os.environ.get("LAB5_TEST_CLEANUP", "attachment-cleanup")
|
||||
POINTS = {"commit-before-publish": ("before_publish", RELAY),
|
||||
"publish-before-mark": ("after_publish", RELAY),
|
||||
"object-before-ack": ("after_objects", WORKER),
|
||||
"ready-before-ack": ("before_ack", WORKER)}
|
||||
ORIGINAL = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
S3_SETUP = """set -eu
|
||||
rc=/usr/bin/rc
|
||||
"$rc" alias set app http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" \
|
||||
"$(cat /run/secrets/s3_secret_access_key)" --bucket-lookup path \
|
||||
--region "$S3_REGION" >/dev/null
|
||||
"""
|
||||
S3_RC = S3_SETUP + """for prefix do
|
||||
"$rc" bucket list --recursive --json "app/$S3_BUCKET/$prefix"
|
||||
done
|
||||
"""
|
||||
|
||||
|
||||
class Unsupported(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def require(ok, message):
|
||||
if not ok:
|
||||
raise RuntimeError(message)
|
||||
|
||||
|
||||
def run(argv, label, timeout=30, allow_fail=False):
|
||||
try:
|
||||
r = subprocess.run(argv, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
raise RuntimeError(f"{label}: exceeded {timeout}s") from None
|
||||
require(allow_fail or r.returncode == 0, f"{label}: exit {r.returncode}")
|
||||
return r
|
||||
|
||||
|
||||
def until(fn, label, seconds=24):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
value = fn()
|
||||
except (RuntimeError, ValueError):
|
||||
value = None
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError(label)
|
||||
|
||||
|
||||
def compose(*args, label=None, timeout=30, allow_fail=False):
|
||||
files = json.loads(os.environ.get("LAB5_TEST_COMPOSE_FILES", "[]"))
|
||||
cmd = ["docker", "compose", "--project-name", PROJECT]
|
||||
for file in files:
|
||||
cmd += ["-f", file]
|
||||
return run(cmd + list(args), label or "compose " + args[0], timeout, allow_fail)
|
||||
|
||||
|
||||
def sql(query):
|
||||
return compose("exec", "-T", DB, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-At",
|
||||
"-U", os.environ["LAB5_TEST_DB_USER"], "-d", os.environ["LAB5_TEST_DB_NAME"],
|
||||
"-c", query, label="fixture SQL").stdout.decode().strip()
|
||||
|
||||
|
||||
def one_container(service):
|
||||
rows = compose("ps", "-aq", service).stdout.decode().split()
|
||||
require(len(rows) == 1, f"expected one {service} in isolated project")
|
||||
return rows[0]
|
||||
|
||||
|
||||
def start(*services):
|
||||
# Start the existing containers only. Compose start can also rerun a finished
|
||||
# one-shot dependency, which would invalidate the migration experiment.
|
||||
ids = [one_container(service) for service in services]
|
||||
run(["docker", "start", *ids], "start selected containers")
|
||||
|
||||
|
||||
def set_storage_net(attached):
|
||||
cid = one_container(WORKER)
|
||||
net = PROJECT + "_lab5_object"
|
||||
current = json.loads(run(["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", cid],
|
||||
"worker networks").stdout)
|
||||
if attached and net not in current:
|
||||
run(["docker", "network", "connect", "--alias", WORKER, net, cid], "restore worker S3 network")
|
||||
if not attached and net in current:
|
||||
run(["docker", "network", "disconnect", net, cid], "isolate worker S3 network")
|
||||
|
||||
|
||||
def marker_dir():
|
||||
path = Path(os.environ.get("LAB5_TEST_FAULT_HOST_DIR", "/nonexistent")).resolve()
|
||||
if not path.is_dir() or not (path / ".lab5-test-project").is_file():
|
||||
raise Unsupported("set a dedicated fault directory with .lab5-test-project marker")
|
||||
require((path / ".lab5-test-project").read_text().strip() == PROJECT, "fault directory belongs to another project")
|
||||
return path
|
||||
|
||||
|
||||
def clean_point(point):
|
||||
for suffix in ("arm", "used", "hit", "release"):
|
||||
p = marker_dir() / f"{point}.{suffix}"
|
||||
if p.exists():
|
||||
p.unlink()
|
||||
|
||||
|
||||
def broker_ctl(command, *columns):
|
||||
return compose("exec", "-T", "-e", "RABBITMQ_CTL_ERL_ARGS=+S 1:1 +A 1", BROKER,
|
||||
"rabbitmqctl", command, "-p", "messenger", "--quiet", "--formatter", "json",
|
||||
*columns, label="RabbitMQ " + command, timeout=20)
|
||||
|
||||
|
||||
def queue(name="image.jobs"):
|
||||
r = broker_ctl("list_queues", "name", "durable", "messages_ready", "messages_unacknowledged", "consumers").stdout
|
||||
rows = json.loads(r)
|
||||
image = [row for row in rows if row["name"] == name]
|
||||
require(len(image) == 1 and image[0]["durable"] is True, "expected durable queue not found")
|
||||
return image[0]
|
||||
|
||||
|
||||
def snapshot(att):
|
||||
row = sql(f"""
|
||||
SELECT json_build_object(
|
||||
'job_id', j.id, 'jobs', (SELECT count(*) FROM attachment_jobs WHERE attachment_id=a.id),
|
||||
'outbox', (SELECT count(*) FROM outbox WHERE job_id=j.id),
|
||||
'published', (SELECT count(*) FROM outbox WHERE job_id=j.id AND sent_at IS NOT NULL),
|
||||
'status', a.status, 'max_attempts', j.max_attempts,
|
||||
'failed_registered', a.status='failed' AND a.error_code IS NOT NULL,
|
||||
'generation', j.lease_generation, 'original_key', a.object_key,
|
||||
'has_staging_ref', a.staging_key IS NOT NULL,
|
||||
'processing_age_seconds', (SELECT extract(epoch FROM clock_timestamp()-r.started_at)
|
||||
FROM attachment_attempts r WHERE r.job_id=j.id AND r.lease_generation=j.lease_generation),
|
||||
'variant_keys', COALESCE((SELECT json_object_agg(name, object_key) FROM attachment_variants
|
||||
WHERE attachment_id = a.id AND pipeline_version = j.pipeline_version), '{{}}'),
|
||||
'audit_replays', (SELECT count(*) FROM attachment_replays WHERE job_id=j.id),
|
||||
'envelope_valid', EXISTS (SELECT 1 FROM outbox o WHERE o.job_id=j.id AND
|
||||
o.payload->>'schema_version'='1' AND o.payload->>'type'='attachment.process.v1'
|
||||
AND o.payload->>'job_id'=j.id::text AND o.payload->>'attachment_id'=a.id::text
|
||||
AND o.payload->>'attempt'='1' AND o.payload->>'pipeline_version'=j.pipeline_version::text
|
||||
AND (o.payload - ARRAY['schema_version','type','job_id','attachment_id','attempt','pipeline_version',
|
||||
'created_at','traceparent','tracestate']) = '{{}}'::jsonb),
|
||||
'attempts', COALESCE((SELECT json_agg(json_build_object(
|
||||
'attempt', r.attempt,
|
||||
'kind', CASE r.outcome WHEN 'ready' THEN 'success' WHEN 'retry' THEN 'temporary'
|
||||
WHEN 'failed' THEN CASE WHEN r.error_code='retry_exhausted' THEN 'temporary' ELSE 'permanent' END
|
||||
WHEN 'lease_expired' THEN 'lease_expired' ELSE 'processing' END,
|
||||
'delay_seconds', extract(epoch FROM o.available_at-r.finished_at), 'error_code', r.error_code
|
||||
) ORDER BY r.attempt) FROM attachment_attempts r LEFT JOIN outbox o
|
||||
ON o.dedup_key = 'retry/' || j.id || '/' || (r.attempt + 1) WHERE r.job_id=j.id), '[]')
|
||||
)
|
||||
FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id AND j.pipeline_version=a.pipeline_version
|
||||
WHERE a.id='{att}';
|
||||
""")
|
||||
require(row and "\n" not in row, "expected exactly one pipeline observation")
|
||||
return json.loads(row)
|
||||
|
||||
|
||||
def list_key_sets(*prefixes):
|
||||
r = compose("run", "--no-deps", "--rm", "-T", "--entrypoint", "/bin/sh", "s3-init",
|
||||
"-c", S3_RC, "lab5-test", *prefixes, label="list synthetic S3 prefixes", timeout=20)
|
||||
source = r.stdout.decode().lstrip()
|
||||
decoder = json.JSONDecoder()
|
||||
sets = []
|
||||
for prefix in prefixes:
|
||||
page, offset = decoder.raw_decode(source)
|
||||
source = source[offset:].lstrip()
|
||||
require(page.get("truncated") is False and isinstance(page.get("items"), list),
|
||||
"S3 prefix listing is incomplete")
|
||||
keys = {entry["key"] for entry in page["items"] if not entry["is_dir"]}
|
||||
require(all(key.startswith(prefix) for key in keys), "S3 response escaped the fixture prefix")
|
||||
sets.append(keys)
|
||||
require(not source, "unexpected S3 output after the requested listings")
|
||||
return sets
|
||||
|
||||
|
||||
def runtime():
|
||||
cid = one_container(WORKER)
|
||||
fields = run(["docker", "inspect", "-f", "{{json .Config.Env}}\t{{.HostConfig.Memory}}", cid],
|
||||
"worker limits").stdout.decode().strip().split("\t")
|
||||
env, mem = json.loads(fields[0]), int(fields[1])
|
||||
settings = dict(x.split("=", 1) for x in env if "=" in x)
|
||||
|
||||
def value(names, default):
|
||||
return next((int(settings[n]) for n in names if n in settings), default)
|
||||
|
||||
return {"worker_memory_bytes": mem,
|
||||
"concurrency": value(("WORKER_CONCURRENCY",), 1),
|
||||
"prefetch": value(("WORKER_PREFETCH", "JOB_PREFETCH"), 1),
|
||||
"lease_seconds": value(("JOB_LEASE_SECONDS", "WORKER_LEASE_SECONDS"), 90),
|
||||
"job_timeout_seconds": value(("JOB_TIMEOUT_SECONDS", "WORKER_TIMEOUT_SECONDS"), 60),
|
||||
"retry_base_seconds": value(("JOB_RETRY_BASE_SECONDS", "WORKER_RETRY_BASE_SECONDS"), 2)}
|
||||
|
||||
|
||||
def worker_limits():
|
||||
settings = runtime()
|
||||
r = compose("exec", "-T", WORKER, "magick", "-list", "resource", label="ImageMagick policy")
|
||||
limits = dict((name.strip(), val.strip()) for line in r.stdout.decode().splitlines()
|
||||
if ":" in line for name, val in [line.split(":", 1)])
|
||||
settings["image_limits"] = {key: limits.get(key, "") for key in ("Memory", "Map", "Disk", "Thread", "Time")}
|
||||
r = broker_ctl("list_consumers")
|
||||
rows = json.loads(r.stdout)
|
||||
settings["consumers"] = [
|
||||
{"prefetch": row["prefetch_count"], "ack_required": row["ack_required"], "active": row["active"]}
|
||||
for row in rows if row["queue_name"] == "image.jobs"
|
||||
]
|
||||
return settings
|
||||
|
||||
|
||||
def retry_delays_ms(job_id):
|
||||
cid = one_container(WORKER)
|
||||
# Preserve only the observed scheduling values, never container logs.
|
||||
output = run(["docker", "logs", cid], "worker retry delay evidence")
|
||||
delays = []
|
||||
for line in (output.stderr + output.stdout).decode().splitlines():
|
||||
if "job retry scheduled" not in line:
|
||||
continue
|
||||
if line.startswith("{"):
|
||||
item = json.loads(line)
|
||||
if item.get("job_id") == job_id and item.get("msg") == "job retry scheduled":
|
||||
delays.append(int(item["delay_ms"]))
|
||||
elif f"job_id={job_id}" in line:
|
||||
match = re.search(r"\bdelay_ms=(\d+)", line)
|
||||
require(match is not None, "worker retry log did not record jitter")
|
||||
delays.append(int(match.group(1)))
|
||||
return delays
|
||||
|
||||
|
||||
def inspect(att):
|
||||
row = snapshot(att)
|
||||
staging, results = list_key_sets(f"staging/{att}/", f"results/{att}/")
|
||||
keys = row.pop("variant_keys")
|
||||
original = row.pop("original_key")
|
||||
row["staging_exists"] = f"staging/{att}/original" in staging
|
||||
row["variant_objects"] = sorted(name for name in keys if keys[name] in results)
|
||||
row["original_exists"] = original in results
|
||||
row["result_count"] = len(results)
|
||||
row["scheduled_delays_ms"] = retry_delays_ms(row["job_id"]) if any(
|
||||
attempt["delay_seconds"] is not None for attempt in row["attempts"]) else []
|
||||
row.update(runtime())
|
||||
return row
|
||||
|
||||
|
||||
def restart_broker_with_pending():
|
||||
# Stop the relay so it cannot republish a lost message during recovery.
|
||||
compose("stop", "-t", "4", RELAY)
|
||||
before = until(lambda: (q if (q := queue())["messages_ready"] > 0 and q["consumers"] == 0 else None),
|
||||
"expected a durable broker delivery before restart")
|
||||
cid = one_container(BROKER)
|
||||
run(["docker", "restart", "--time", "8", cid], "physical RabbitMQ restart", timeout=70)
|
||||
after = until(queue, "durable queue did not reappear", seconds=45)
|
||||
require(after["messages_ready"] == before["messages_ready"] and after["consumers"] == 0,
|
||||
"accepted broker deliveries did not survive restart")
|
||||
return {"broker_before": before, "broker_after": after}
|
||||
|
||||
|
||||
def drained():
|
||||
def empty():
|
||||
value = queue()
|
||||
return value if value["consumers"] > 0 and value["messages_ready"] == 0 and value["messages_unacknowledged"] == 0 else None
|
||||
return until(empty, "broker delivery was not acknowledged/drained", seconds=45)
|
||||
|
||||
|
||||
|
||||
def await_publication(outbox_id):
|
||||
until(lambda: sql(f"SELECT sent_at IS NOT NULL FROM outbox WHERE id='{outbox_id}'") == "t",
|
||||
"fixture delivery not confirmed")
|
||||
return drained()
|
||||
|
||||
|
||||
def publish_fixture(att, field=None, *, version=None):
|
||||
dedup = "test_delivery/" + str(uuid.uuid4())
|
||||
payload = "o.payload"
|
||||
if field in ("attachment_id", "job_id"):
|
||||
payload = f"jsonb_set(o.payload, '{{{field}}}', to_jsonb('{uuid.uuid4()}'::text))"
|
||||
elif field == "pipeline_version":
|
||||
payload = "jsonb_set(o.payload, '{pipeline_version}', to_jsonb(j.pipeline_version+1))"
|
||||
version_filter = "" if version is None else f" AND j.pipeline_version={int(version)}"
|
||||
row = sql(f"""INSERT INTO outbox(job_id,payload,available_at,dedup_key)
|
||||
SELECT o.job_id,{payload}, clock_timestamp(), '{dedup}' FROM outbox o
|
||||
JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='{att}'{version_filter}
|
||||
ORDER BY o.created_at, o.id LIMIT 1 RETURNING id""").splitlines()
|
||||
require(len(row) == 2 and row[1] == "INSERT 0 1", "unable to insert fixture delivery")
|
||||
outbox_id = str(uuid.UUID(row[0]))
|
||||
await_publication(outbox_id)
|
||||
return outbox_id
|
||||
|
||||
|
||||
def invalid_job(att):
|
||||
before = queue("image.invalid")["messages_ready"]
|
||||
for field in ("attachment_id", "job_id", "pipeline_version"):
|
||||
publish_fixture(att, field)
|
||||
after = until(lambda: (n if (n := queue("image.invalid")["messages_ready"]) == before+3 else None),
|
||||
"invalid delivery was not rejected to DLQ")
|
||||
return {"dead_letters_before": before, "dead_letters_after": after}
|
||||
|
||||
|
||||
def failed(att):
|
||||
row = snapshot(att)
|
||||
result = compose("exec", "-T", CLEANER, "/app/jobs", "failed", label="list failed via operator CLI")
|
||||
values = json.loads(result.stdout)
|
||||
require(isinstance(values, list) and any(r["job_id"] == row["job_id"] and r["attachment_id"] == att
|
||||
for r in values),
|
||||
"failed job absent from operator registry")
|
||||
|
||||
|
||||
def replay(att):
|
||||
default = [CLEANER, "/app/jobs", "replay", "-job-id", "{job_id}", "-request-id", "{request_id}",
|
||||
"-operator", "test", "-reason", "acceptance", "-extra-attempts", "1"]
|
||||
# JSON argv with explicitly recognized substitutions; shell is never used.
|
||||
cmd = json.loads(os.environ["LAB5_TEST_REPLAY_CMD"]) if os.environ.get("LAB5_TEST_REPLAY_CMD") else default
|
||||
row = snapshot(att)
|
||||
mapping = {"{job_id}": row["job_id"], "{attachment_id}": att, "{request_id}": str(uuid.uuid4())}
|
||||
argv = [mapping.get(x, x) for x in cmd]
|
||||
result = compose("exec", "-T", *argv, label="operator replay")
|
||||
data = json.loads(result.stdout)
|
||||
require(data["job_id"] == row["job_id"] and data["replayed"] is (row["status"] == "failed"),
|
||||
"operator replay did not report the expected status")
|
||||
return {"accepted": data["replayed"], "request_id": mapping["{request_id}"], "job_id": row["job_id"]}
|
||||
|
||||
|
||||
def wait_marker(label, att):
|
||||
point, _ = POINTS[label]
|
||||
job = snapshot(att)["job_id"]
|
||||
hit = marker_dir() / (point + ".hit")
|
||||
matched = until(lambda: hit.read_text().strip() if hit.is_file() else None,
|
||||
"instrumented process did not reach intended fault")
|
||||
require(matched == job, "fault marker matched a different job")
|
||||
return hit, {"point": label, "attachment_id": att, "job_id": matched}
|
||||
|
||||
|
||||
def crash_observed(label, att):
|
||||
point, service = POINTS[label]
|
||||
cid = one_container(service)
|
||||
hit, evidence = wait_marker(label, att)
|
||||
row = snapshot(att)
|
||||
expected = {"commit-before-publish": "queued", "publish-before-mark": "queued",
|
||||
"object-before-ack": "processing", "ready-before-ack": "ready"}[label]
|
||||
require(row["status"] == expected, "attachment state does not match held crash boundary")
|
||||
if expected == "queued":
|
||||
require(row["published"] == 0 and row["outbox"] == 1, "outbox is not committed and unsent")
|
||||
if expected != "ready":
|
||||
require(row["has_staging_ref"], "staging reference removed before safe completion")
|
||||
if expected == "processing":
|
||||
age_limit = runtime()["job_timeout_seconds"] - row["processing_age_seconds"]
|
||||
else:
|
||||
age_limit = None
|
||||
marker_mtime = hit.stat().st_mtime
|
||||
started = time.monotonic()
|
||||
# Read state and signal consecutively, within the actual fault window.
|
||||
# The relay timeout starts slightly before the marker (transaction setup).
|
||||
limit = 6 if expected == "queued" else 25
|
||||
if expected == "processing":
|
||||
require(age_limit > 0.3, "worker deadline expired before the crash")
|
||||
else:
|
||||
require(time.time() - marker_mtime < limit, "fault marker expired before the crash")
|
||||
require(not (marker_dir() / (point + ".release")).exists(), "fault point was released")
|
||||
run(["docker", "kill", "--signal", "KILL", cid], "kill at held fault marker", timeout=5)
|
||||
elapsed = time.monotonic() - started
|
||||
if expected == "processing":
|
||||
require(elapsed < age_limit, "worker deadline elapsed before SIGKILL")
|
||||
else:
|
||||
require(time.time() - marker_mtime < limit, "fault window elapsed before SIGKILL")
|
||||
stored = None
|
||||
try:
|
||||
if expected == "processing":
|
||||
stored = len(list_key_sets(f"results/{att}/")[0])
|
||||
require(stored >= 4, "S3 did not contain the written output set at worker crash")
|
||||
finally:
|
||||
clean_point(point)
|
||||
start(service)
|
||||
evidence.update(container=cid, signal="SIGKILL", status=expected, generation=row["generation"],
|
||||
attempts=row["attempts"], outbox=row["outbox"], published=row["published"],
|
||||
result_count=stored, kill_elapsed_s=elapsed)
|
||||
return evidence
|
||||
|
||||
|
||||
def main():
|
||||
require(bool(PROJECT) and PROJECT != "highload-lab5", "explicit disposable project required")
|
||||
marker_dir()
|
||||
command, *args = sys.argv[1:]
|
||||
if command == "reset":
|
||||
services = set(compose("config", "--services").stdout.decode().split())
|
||||
if not {WORKER, RELAY, BROKER} <= services:
|
||||
raise Unsupported("worker, relay and broker are not configured")
|
||||
for point, _ in POINTS.values():
|
||||
hit = marker_dir() / (point + ".hit")
|
||||
if hit.exists():
|
||||
(marker_dir() / (point + ".release")).touch()
|
||||
(marker_dir() / (point + ".arm")).unlink(missing_ok=True)
|
||||
start(BROKER, RELAY, WORKER)
|
||||
set_storage_net(True)
|
||||
return None
|
||||
if command == "worker-limits":
|
||||
return worker_limits()
|
||||
if command == "drain":
|
||||
return drained()
|
||||
if command == "worker-stop":
|
||||
compose("stop", "-t", "5", WORKER)
|
||||
elif command == "worker-start":
|
||||
start(WORKER)
|
||||
elif command == "relay-start":
|
||||
start(RELAY)
|
||||
elif command == "restart-apis":
|
||||
old = compose("ps", "-q", API).stdout.decode().split()
|
||||
require(len(old) >= 2, "need two real API containers to restart")
|
||||
def starts():
|
||||
return {i: run(["docker", "inspect", "-f", "{{.State.StartedAt}}", i],
|
||||
"API StartedAt").stdout.decode().strip() for i in old}
|
||||
before = starts()
|
||||
run(["docker", "restart", "--time", "8", *old], "restart APIs")
|
||||
after = starts()
|
||||
require(all(after[i] != before[i] for i in old), "not all APIs restarted")
|
||||
return {"started_before": before, "started_after": after}
|
||||
elif command == "broker-restart":
|
||||
return restart_broker_with_pending()
|
||||
elif command == "arm" and args[0] in POINTS:
|
||||
point, _ = POINTS[args[0]]
|
||||
clean_point(point)
|
||||
(marker_dir() / (point + ".arm")).touch(exist_ok=False)
|
||||
elif command == "await":
|
||||
return wait_marker(args[0], str(uuid.UUID(args[1])))[1]
|
||||
elif command == "crash":
|
||||
return crash_observed(args[0], str(uuid.UUID(args[1])))
|
||||
elif command == "arm" and args[0] == "retry-transient":
|
||||
set_storage_net(False)
|
||||
elif command == "clear" and args[0] == "retry-transient":
|
||||
set_storage_net(True)
|
||||
elif command == "arm" and args[0] == "fail-permanent":
|
||||
compose("stop", "-t", "5", WORKER)
|
||||
elif command in ("activate", "clear") and args[0] == "fail-permanent":
|
||||
att = str(uuid.UUID(args[1]))
|
||||
if command == "activate":
|
||||
value = "0" * 64
|
||||
else:
|
||||
import hashlib
|
||||
value = hashlib.sha256(ORIGINAL).hexdigest()
|
||||
require(sql(f"UPDATE attachments SET sha256='{value}' WHERE id='{att}' RETURNING id").splitlines() ==
|
||||
[att, "UPDATE 1"],
|
||||
"could not inject/restore staging checksum fault")
|
||||
if command == "activate":
|
||||
start(WORKER)
|
||||
elif command == "activate" and args[0] == "retry-transient":
|
||||
pass
|
||||
elif command in ("inspect", "redeliver", "replay", "failed", "invalid-job"):
|
||||
att = str(uuid.UUID(args[0]))
|
||||
return {"inspect": inspect, "redeliver": publish_fixture, "replay": replay,
|
||||
"failed": failed, "invalid-job": invalid_job}[command](att)
|
||||
else:
|
||||
raise Unsupported("pipeline action unavailable")
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
result = main()
|
||||
if result is not None:
|
||||
print(json.dumps(result))
|
||||
except Unsupported as exc:
|
||||
print(str(exc), file=sys.stderr)
|
||||
sys.exit(78)
|
||||
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
|
||||
print("pipeline adapter:", exc if isinstance(exc, RuntimeError) else type(exc).__name__, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,457 @@
|
||||
"""Observe and exercise a Compose stand. Business traffic always goes via the LB."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from checks import ROOT, Failure, Pending, assert_history, check, history, message_path, key, post, summarize, wait
|
||||
from client import shape
|
||||
|
||||
|
||||
class Stand:
|
||||
# Whitelist inspect fields: no environment, mounts, or container log dumps.
|
||||
FORMAT = "\t".join(("{{.Id}}", "{{.Config.Hostname}}", "{{.Image}}", "{{.State.Status}}",
|
||||
"{{.State.StartedAt}}", "{{.State.FinishedAt}}", "{{.State.ExitCode}}",
|
||||
"{{.State.OOMKilled}}", "{{.HostConfig.NanoCpus}}", "{{.HostConfig.CpuQuota}}",
|
||||
"{{.HostConfig.CpuPeriod}}", "{{.HostConfig.Memory}}",
|
||||
"{{json .NetworkSettings.Ports}}", "{{json .HostConfig.PortBindings}}",
|
||||
"{{.HostConfig.NetworkMode}}", "{{.HostConfig.PublishAllPorts}}"))
|
||||
|
||||
def __init__(self, args, c):
|
||||
self.a = args
|
||||
self.c = c
|
||||
self.e = c.evidence
|
||||
self.compose = ["docker", "compose"]
|
||||
if args.project:
|
||||
self.compose += ["--project-name", args.project]
|
||||
for file in args.compose_file:
|
||||
self.compose += ["--file", str(Path(file).resolve())]
|
||||
|
||||
def command(self, name, argv, *, timeout=30, env=None, allow_failure=False):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
result = subprocess.run(argv, cwd=ROOT, env=env, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, timeout=timeout)
|
||||
except (OSError, subprocess.TimeoutExpired) as exc:
|
||||
self.e.event("command", action=name, elapsed_s=time.monotonic()-start, error=type(exc).__name__)
|
||||
raise Failure(f"{name}: {type(exc).__name__}") from None
|
||||
self.e.event("command", action=name, elapsed_s=time.monotonic()-start, exit_code=result.returncode)
|
||||
check(allow_failure or result.returncode == 0, f"{name}: exit {result.returncode}")
|
||||
return result
|
||||
|
||||
def ids(self, service, all_states=True):
|
||||
return self.command("compose ps " + service, self.compose + ["ps"] +
|
||||
(["-a"] if all_states else []) + ["-q", service]).stdout.decode().split()
|
||||
|
||||
def containers(self, service):
|
||||
results = []
|
||||
for cid in self.ids(service):
|
||||
result = self.command("inspect " + service, ["docker", "inspect", "--format", self.FORMAT, cid])
|
||||
parts = result.stdout.decode().rstrip("\n").split("\t")
|
||||
fields = ("id", "alias", "image", "state", "started_at", "finished_at", "exit_code", "oom",
|
||||
"nano_cpus", "cpu_quota", "cpu_period", "memory", "ports", "bindings", "network", "publish_all")
|
||||
check(len(parts) == len(fields), "unexpected docker inspect format")
|
||||
for index in range(6, len(fields)):
|
||||
parts[index] = json.loads(parts[index]) if fields[index] != "network" else parts[index]
|
||||
results.append(dict(zip(fields, parts)))
|
||||
return results
|
||||
|
||||
def public_topology(self):
|
||||
try:
|
||||
if not hasattr(self, "engine"):
|
||||
fmt = "{{.ServerVersion}}\t{{.OSType}}\t{{.Architecture}}\t{{.NCPU}}\t{{.MemTotal}}"
|
||||
result = self.command("Docker availability", ["docker", "info", "--format", fmt])
|
||||
self.engine = result.stdout.decode().strip().split("\t")
|
||||
check(len(self.engine) == 5, "unexpected Docker engine metadata")
|
||||
self.e.event("docker_environment", version=self.engine[0], os=self.engine[1],
|
||||
architecture=self.engine[2], logical_cpus=int(self.engine[3]),
|
||||
memory_bytes=int(self.engine[4]))
|
||||
except Failure:
|
||||
raise Pending("Docker daemon not available") from None
|
||||
services = self.command("Compose service names", self.compose + ["config", "--services"]).stdout.decode().split()
|
||||
if self.a.api not in services or self.a.lb not in services:
|
||||
raise Pending("Compose does not define API and LB services")
|
||||
api = [r for r in self.containers(self.a.api) if r["state"] == "running"]
|
||||
lb = [r for r in self.containers(self.a.lb) if r["state"] == "running"]
|
||||
self.e.event("topology", api=api, lb=lb)
|
||||
if len(api) < 2 or not lb:
|
||||
raise Pending("stand needs two running API replicas and a public LB")
|
||||
self.a_ids = {r["alias"] for r in api}
|
||||
check(len(self.a_ids) == len(api), "API aliases are not unique")
|
||||
self.lb = lb[0]
|
||||
port = urlsplit(self.c.base).port or (443 if self.c.base.startswith("https:") else 80)
|
||||
check(any(int(binding["HostPort"]) == port for r in lb
|
||||
for group in (r["ports"] or {}).values() for binding in group or []),
|
||||
"BASE_URL port is not published by the selected LB")
|
||||
return api
|
||||
|
||||
def resources(self):
|
||||
api = self.public_topology()
|
||||
for r in api:
|
||||
check(r["nano_cpus"] > 0 or (r["cpu_quota"] > 0 and r["cpu_period"] > 0),
|
||||
"API CPU has no hard limit")
|
||||
check(r["memory"] > 0, "API RAM has no hard limit")
|
||||
check(not any((r["ports"] or {}).values()) and not any((r["bindings"] or {}).values())
|
||||
and not r["publish_all"] and r["network"] != "host", "API bypasses LB via host ports/network")
|
||||
self.stats()
|
||||
|
||||
def stats(self):
|
||||
ids = self.ids(self.a.api, False) + [self.lb["id"]]
|
||||
result = self.command("docker stats", ["docker", "stats", "--no-stream", "--format",
|
||||
"{{.ID}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids], timeout=10)
|
||||
self.e.event("resource_sample", samples=result.stdout.decode().splitlines())
|
||||
|
||||
def observe(self, actor, wanted=None, *, duration=3, forbidden=None):
|
||||
wanted = self.a_ids if wanted is None else wanted
|
||||
deadline, seen, attempts = time.monotonic() + duration, set(), 0
|
||||
while time.monotonic() < deadline:
|
||||
result = self.c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
check(result["json"] == actor["user"], "same Bearer token resolved to another user")
|
||||
alias = result["headers"]["X-Instance-Id"]
|
||||
check(alias != forbidden, "LB routed authenticated request to the excluded replica")
|
||||
check(alias in self.a_ids, "LB routed to an API outside this Compose project")
|
||||
seen.add(alias)
|
||||
attempts += 1
|
||||
if forbidden is not None:
|
||||
time.sleep(0.05)
|
||||
if forbidden is None and wanted <= seen:
|
||||
break
|
||||
self.e.event("routing", wanted=sorted(wanted), observed=sorted(seen), excluded=forbidden, attempts=attempts)
|
||||
check(wanted <= seen and attempts >= (10 if forbidden else 2), "LB did not exercise the required replicas")
|
||||
return seen
|
||||
|
||||
def network_target(self, target):
|
||||
fmt = "{{json .NetworkSettings.Networks}}"
|
||||
def networks(cid):
|
||||
r = self.command("container networks", ["docker", "inspect", "--format", fmt, cid])
|
||||
return json.loads(r.stdout)
|
||||
net = networks(target["id"])
|
||||
shared = net.keys() & networks(self.lb["id"]).keys()
|
||||
chosen = self.a.network or (sorted(shared)[0] if shared else None)
|
||||
check(chosen in shared and net[chosen]["IPAddress"], "no shared API/LB network with IPv4")
|
||||
return net[chosen]["IPAddress"]
|
||||
|
||||
def direct_health(self, target, endpoint, status):
|
||||
# From the LB network namespace, bypass routing only for health diagnostics.
|
||||
ip = self.network_target(target)
|
||||
result = self.command("direct health/" + endpoint, [
|
||||
"docker", "run", "--rm", "--pull", "never", "--network", "container:" + self.lb["id"],
|
||||
"--entrypoint", "curl", self.a.probe_image, "--http1.1", "--noproxy", "*",
|
||||
"--include", "--silent", "--show-error", "--max-time", "4",
|
||||
f"http://{ip}:{self.a.api_port}/health/{endpoint}",
|
||||
], timeout=12)
|
||||
response = http.client.HTTPResponse(type("Socket", (), {"makefile": lambda *_: io.BytesIO(result.stdout)})())
|
||||
with response:
|
||||
response.begin()
|
||||
self.e.event("direct_health", endpoint=endpoint, status=response.status,
|
||||
instance=response.getheader("X-Instance-Id"))
|
||||
check(response.status == status and response.getheader("X-Instance-Id") == target["alias"],
|
||||
f"target /health/{endpoint}: expected {status}, got {response.status}")
|
||||
value = json.loads(response.read())
|
||||
rid = response.getheader("X-Request-Id")
|
||||
check(bool(rid) and response.headers.get_content_type() == "application/json",
|
||||
"direct health response is missing required headers")
|
||||
if status == 200:
|
||||
check(shape(value, "Health") == {"status": "ok"}, "direct health payload differs")
|
||||
else:
|
||||
check(shape(value, "Error")["error"]["code"] == "unavailable"
|
||||
and value["error"]["request_id"] == rid, "readiness 503 error envelope differs")
|
||||
return True
|
||||
|
||||
def hook(self, executable, target=None, timeout=90, **extra):
|
||||
if not executable:
|
||||
raise Pending("operator hook is not configured")
|
||||
path = Path(executable).resolve()
|
||||
check(path.is_file() and os.access(path, os.X_OK), "operator hook must be an executable file")
|
||||
env = dict(os.environ, BASE_URL=self.c.base, **extra)
|
||||
if self.a.project:
|
||||
env["COMPOSE_PROJECT_NAME"] = self.a.project
|
||||
if target:
|
||||
env.update(TARGET_INSTANCE_ID=target["alias"], TARGET_CONTAINER_ID=target["id"])
|
||||
self.command("hook " + path.name, [str(path)], env=env, timeout=timeout)
|
||||
|
||||
def unready(self):
|
||||
api = self.public_topology()
|
||||
if not (self.a.unready_hook and self.a.ready_hook):
|
||||
raise Pending("configure hooks to fault and restore one API dependency without disconnecting LB")
|
||||
alice = self.c.user("readiness")
|
||||
self.observe(alice)
|
||||
target = api[0]
|
||||
self.direct_health(target, "live", 200)
|
||||
self.direct_health(target, "ready", 200)
|
||||
try:
|
||||
self.hook(self.a.unready_hook, target, LAB5_HOOK_MODE="unready")
|
||||
wait(lambda: self.direct_health(target, "ready", 503), 20, "target never returned readiness 503")
|
||||
self.direct_health(target, "live", 200)
|
||||
# Allow LB convergence, then require sustained exclusion while the
|
||||
# target remains reachable from the LB network and answers 503.
|
||||
others = self.a_ids - {target["alias"]}
|
||||
def routed_elsewhere():
|
||||
response = self.c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
return response["headers"]["X-Instance-Id"] in others
|
||||
wait(routed_elsewhere, 10, "no authenticated request routed to a ready replica")
|
||||
wait(lambda: self.observe(alice, others, duration=3, forbidden=target["alias"]), 15,
|
||||
"LB did not consistently exclude a running 503 replica")
|
||||
self.direct_health(target, "live", 200)
|
||||
self.direct_health(target, "ready", 503)
|
||||
finally:
|
||||
self.hook(self.a.ready_hook, target, LAB5_HOOK_MODE="ready")
|
||||
wait(lambda: self.direct_health(target, "ready", 200), 20, "target stayed unready after restore")
|
||||
wait(lambda: self.observe(alice), 20, "restored API did not rejoin LB")
|
||||
|
||||
def ready_aliases(self, actor):
|
||||
api = self.public_topology()
|
||||
self.observe(actor)
|
||||
return api
|
||||
|
||||
def migration_snapshot(self):
|
||||
service = self.a.migrate
|
||||
rows = self.containers(service)
|
||||
check(len(rows) == 1, "expected one migrator container")
|
||||
row = rows[0]
|
||||
check(row["state"] == "exited" and row["exit_code"] == 0, "migrator did not exit cleanly")
|
||||
log = self.command("migrator logs", ["docker", "logs", row["id"]])
|
||||
completions = []
|
||||
for line in (log.stdout + log.stderr).splitlines():
|
||||
try:
|
||||
item = json.loads(line)
|
||||
except (ValueError, UnicodeError):
|
||||
continue
|
||||
if isinstance(item, dict) and item.get("msg") == "migrations completed":
|
||||
completions.append(item.get("applied"))
|
||||
check(len(completions) == 1, "migrator must log exactly one successful invocation")
|
||||
sql = ("SELECT version_id, is_applied, count(*) FROM goose_db_version "
|
||||
"GROUP BY 1,2 ORDER BY 1,2;")
|
||||
output = self.command("migration version counts", self.compose + [
|
||||
"exec", "-T", self.a.db, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-At",
|
||||
"-U", self.a.db_user, "-d", self.a.db_name, "-c", sql,
|
||||
]).stdout.decode().splitlines()
|
||||
versions = sorted(int(p.name.split("_", 1)[0]) for p in (ROOT / "db/migrations").glob("*.sql"))
|
||||
check(output == [f"{v}|t|1" for v in [0, *versions]], "migration history differs from one apply per version")
|
||||
check(all(r["started_at"] >= row["finished_at"] for r in self.containers(self.a.api)
|
||||
if r["state"] == "running"), "API started before migrations completed")
|
||||
self.e.event("migrations", container=row, applied=completions, versions=output)
|
||||
return row, output
|
||||
|
||||
def persistence(self):
|
||||
api = self.public_topology()
|
||||
if not self.a.restart_hook:
|
||||
raise Pending("configure a hook that restarts API and stores without removing volumes")
|
||||
stores = [self.a.db, *self.a.store]
|
||||
before = {s: self.containers(s) for s in stores}
|
||||
check(all(rows and all(r["state"] == "running" for r in rows) for rows in before.values()),
|
||||
"configured persistence stores must be running")
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
self.observe(alice)
|
||||
k, text = key(), "committed before restarting API and stores"
|
||||
original = post(self.c, alice, chat, k, text)["json"]
|
||||
self.hook(self.a.restart_hook)
|
||||
wait(lambda: self.c.call("GET", "/health/ready", schema="Health"), 90, "LB did not recover after restart")
|
||||
after = self.public_topology()
|
||||
for s, previous, current in [(self.a.api, api, after)] + [
|
||||
(s, before[s], self.containers(s)) for s in stores]:
|
||||
check(len(previous) == len(current) and all(r["state"] == "running" for r in current)
|
||||
and not {r["started_at"] for r in previous} & {r["started_at"] for r in current},
|
||||
f"restart did not change StartedAt for every {s}")
|
||||
self.e.event("restart_observed", service=s, before=previous, after=current)
|
||||
self.observe(alice)
|
||||
check(post(self.c, alice, chat, k, text)["json"] == original, "idempotency lost after restart")
|
||||
assert_history(self.c, bob, chat, [original])
|
||||
|
||||
def verify_stopped(self, target):
|
||||
now = {r["id"]: r for r in self.containers(self.a.api)}
|
||||
row = now.get(target["id"])
|
||||
check(row is not None and row["state"] == "exited", "SIGTERM did not stop the selected process")
|
||||
check(row["exit_code"] == 0 and not row["oom"], "API did not exit gracefully on SIGTERM")
|
||||
self.e.event("stopped", container=row)
|
||||
|
||||
def failover(self):
|
||||
api = self.public_topology()
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
self.observe(alice)
|
||||
with traffic(self.c, alice, bob, self.a.workers) as load:
|
||||
self.sample_under_load(load)
|
||||
for target in api:
|
||||
self.e.event("target", action="SIGTERM", alias=target["alias"], container=target["id"])
|
||||
k, text, sent = wait(lambda: write_from(self.c, alice, chat, target["alias"]), 10,
|
||||
"could not confirm original POST on selected replica")
|
||||
others = self.a_ids - {target["alias"]}
|
||||
endpoint = self.network_target(target)
|
||||
started = time.monotonic()
|
||||
first_record = len(load.records)
|
||||
# Race real client traffic and recovery probes with Docker stop.
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
stop = pool.submit(self.command, "SIGTERM " + target["alias"], [
|
||||
"docker", "stop", "--signal", "SIGTERM", "--time", "20", target["id"],
|
||||
])
|
||||
try:
|
||||
recovered = self.recover(alice, bob, chat, target, stop, started)
|
||||
self.e.event("recovery", target=target["alias"], seconds=recovered)
|
||||
if recovered is not None:
|
||||
print(f" {target['alias']}: read/write restored in {recovered:.3f} s", flush=True)
|
||||
check(recovered is not None and recovered <= 10, "read and write recovery exceeded 10 seconds")
|
||||
stop.result()
|
||||
self.verify_stopped(target)
|
||||
probe = self.command("fresh TCP to stopped API", ["docker", "exec", self.lb["id"],
|
||||
"nc", "-w", "2", "-z", endpoint, str(self.a.api_port)],
|
||||
allow_failure=True, timeout=5)
|
||||
check(probe.returncode == 1, "fresh connection to stopped replica was accepted or probe failed")
|
||||
replay = post(self.c, alice, chat, k, text)
|
||||
check(replay["json"] == sent["json"] and replay["headers"]["X-Instance-Id"] in others,
|
||||
"different replica did not replay the original Message")
|
||||
self.observe(alice, others, duration=self.a.window, forbidden=target["alias"])
|
||||
read_back = history(self.c, bob, chat)
|
||||
check([m for m in read_back if m["text"] == text] == [sent["json"]],
|
||||
"confirmed pre-stop POST missing, changed or duplicated")
|
||||
check(len({m["text"] for m in read_back}) == len(read_back),
|
||||
"an uncertain retry created duplicate effects")
|
||||
finally:
|
||||
summarize(self.e, load.records[first_record:], time.monotonic() - started,
|
||||
window="target " + target["alias"])
|
||||
# Settle the stop before starting the same container.
|
||||
try:
|
||||
stop.result()
|
||||
finally:
|
||||
self.command("restore " + target["alias"], ["docker", "start", target["id"]])
|
||||
wait(lambda: self.observe(alice), 25, "restored replica did not rejoin LB")
|
||||
|
||||
def recover(self, alice, bob, chat, target, stop, started):
|
||||
k, text = key(), "recovery probe " + key()
|
||||
deadline = started + 10
|
||||
while time.monotonic() < deadline:
|
||||
if stop.done():
|
||||
stop.result()
|
||||
try:
|
||||
result = post(self.c, alice, chat, k, text)
|
||||
if result["headers"]["X-Instance-Id"] != target["alias"]:
|
||||
page = self.c.call("GET", message_path(chat) + "?limit=100", actor=bob, schema="MessagePage")
|
||||
if (page["headers"]["X-Instance-Id"] != target["alias"]
|
||||
and result["json"] in page["json"]["items"]):
|
||||
return time.monotonic() - started
|
||||
except Failure:
|
||||
pass # Keep the exact key/body after an uncertain write.
|
||||
time.sleep(0.1)
|
||||
return None
|
||||
|
||||
def sample_under_load(self, load):
|
||||
time.sleep(self.a.warmup)
|
||||
check(load.successes() >= 1, "no successful business request during load warm-up")
|
||||
self.stats()
|
||||
|
||||
def rolling(self):
|
||||
api = self.public_topology()
|
||||
if not self.a.roll_hook:
|
||||
raise Pending("awaiting rolling update hook/candidate image")
|
||||
before = self.migration_snapshot()
|
||||
alice, bob, _, _ = self.c.bootstrap()
|
||||
self.observe(alice)
|
||||
original_ids = {r["id"] for r in api}
|
||||
previous = {r["id"]: r for r in api}
|
||||
with traffic(self.c, alice, bob, self.a.workers) as load:
|
||||
self.sample_under_load(load)
|
||||
start_index = len(load.records)
|
||||
for target in api:
|
||||
step_at = time.monotonic()
|
||||
self.e.event("target", action="rolling_update", alias=target["alias"], container=target["id"])
|
||||
self.hook(self.a.roll_hook, target)
|
||||
current = {r["id"]: r for r in self.public_topology()}
|
||||
stable = set(previous) - {target["id"]}
|
||||
new = set(current) - set(previous)
|
||||
check(set(current) == stable | new and len(new) == 1, "rolling step did not replace exactly one API")
|
||||
check(all(current[r] == previous[r] for r in stable), "rolling step also disturbed another API")
|
||||
replacement = current[new.pop()]
|
||||
check(replacement["image"] != target["image"], "rolling step did not apply a new immutable image")
|
||||
self.observe(alice)
|
||||
time.sleep(self.a.window)
|
||||
self.e.event("rolling_step", previous=target, replacement=replacement,
|
||||
seconds=time.monotonic() - step_at)
|
||||
previous = current
|
||||
check(not original_ids & set(previous), "some original replicas were not updated")
|
||||
stats = load.records[start_index:]
|
||||
check(stats and all(r["ok"] for r in stats), "business request failed during rolling update")
|
||||
check(self.migration_snapshot() == before, "rolling update restarted migrations or changed version history")
|
||||
|
||||
|
||||
def write_from(c, actor, chat, alias):
|
||||
k, text = key(), "before SIGTERM " + key()
|
||||
r = post(c, actor, chat, k, text)
|
||||
return (k, text, r) if r["headers"]["X-Instance-Id"] == alias else None
|
||||
|
||||
|
||||
class Traffic:
|
||||
def __init__(self, c, actor, reader, chat):
|
||||
self.c, self.actor, self.reader, self.chat = c, actor, reader, chat
|
||||
self.stop = threading.Event()
|
||||
self.records = []
|
||||
self.confirmed = {}
|
||||
self.offered = set()
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def lane(self):
|
||||
while not self.stop.is_set():
|
||||
k = key()
|
||||
with self.lock:
|
||||
self.offered.add(k)
|
||||
for op in ("write", "read"):
|
||||
started = time.monotonic()
|
||||
ok = False
|
||||
status = None
|
||||
try:
|
||||
if op == "write":
|
||||
result = post(self.c, self.actor, self.chat, k, k)
|
||||
with self.lock:
|
||||
self.confirmed[k] = result["json"]
|
||||
else:
|
||||
result = self.c.call("GET", "/api/v1/users/me", actor=self.actor, schema="User")
|
||||
check(result["json"] == self.actor["user"], "load token resolved to another user")
|
||||
ok = True
|
||||
except Failure:
|
||||
pass
|
||||
finally:
|
||||
status = self.c.local.status
|
||||
row = self.c.evidence.event("load_request", op=op, status=status, ok=ok,
|
||||
instance=self.c.local.instance, elapsed_s=time.monotonic()-started)
|
||||
with self.lock:
|
||||
self.records.append(row)
|
||||
if self.stop.is_set():
|
||||
break
|
||||
|
||||
def successes(self):
|
||||
with self.lock:
|
||||
return sum(r["ok"] for r in self.records)
|
||||
|
||||
def reconcile(self):
|
||||
found = history(self.c, self.reader, self.chat)
|
||||
by_text = {m["text"]: m for m in found}
|
||||
check(len(by_text) == len(found) and set(by_text) <= self.offered,
|
||||
"load history contains duplicate writes or unknown data")
|
||||
check(all(by_text.get(k) == v for k, v in self.confirmed.items()),
|
||||
"confirmed load write missing or changed in history")
|
||||
self.c.evidence.event("load_history", observed=len(found), confirmed=len(self.confirmed),
|
||||
offered=len(self.offered))
|
||||
|
||||
|
||||
@contextmanager
|
||||
def traffic(c, actor, reader, workers):
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
|
||||
body={"title": "Lab 5 load", "member_ids": [actor["id"], reader["id"]]})["json"]
|
||||
load = Traffic(c, actor, reader, chat)
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(load.lane) for _ in range(workers)]
|
||||
try:
|
||||
yield load
|
||||
finally:
|
||||
load.stop.set()
|
||||
for future in futures:
|
||||
future.result()
|
||||
elapsed = time.monotonic() - started
|
||||
summarize(c.evidence, load.records, elapsed)
|
||||
load.reconcile()
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Track 2 experiment. Each trial uses a separate attachment and real deliveries."""
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta
|
||||
import hashlib
|
||||
import json
|
||||
from statistics import median
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from checks import Failure, Pending, check, wait
|
||||
from pipeline import SAMPLE, VARIANTS, metadata, verify_ready
|
||||
|
||||
ORIGINAL = hashlib.sha256(SAMPLE).hexdigest()
|
||||
|
||||
|
||||
def utc(value):
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
def jobs(row):
|
||||
return {j["version"]: j for j in row["jobs"]}
|
||||
|
||||
|
||||
def deliveries(row, version):
|
||||
return [e for e in row["outbox"] if e["version"] == version]
|
||||
|
||||
|
||||
def fingerprint(row):
|
||||
# Dynamic clock and transport bookkeeping are intentionally outside the
|
||||
# effect. Attempts, pointers, generations and timestamps remain comparable.
|
||||
return {k: row[k] for k in ("version", "status", "original", "updated_at", "jobs")}
|
||||
|
||||
|
||||
class Versioned:
|
||||
def __init__(self, pipeline, ops):
|
||||
self.pipeline = pipeline
|
||||
self.c = pipeline.c
|
||||
self.e = self.c.evidence
|
||||
self.ops = ops
|
||||
self.timeout = pipeline.a.pipeline_timeout
|
||||
|
||||
def state(self, att):
|
||||
attachment = str(uuid.UUID(att["id"]))
|
||||
value = self.ops.sql(f"""
|
||||
SELECT json_build_object(
|
||||
'version', a.pipeline_version, 'status', a.status, 'original', a.object_key,
|
||||
'sha256', a.sha256, 'size', a.size_bytes, 'updated_at', a.updated_at, 'db_now', clock_timestamp(),
|
||||
'jobs', COALESCE((SELECT json_agg(json_build_object(
|
||||
'id', j.id, 'version', j.pipeline_version, 'generation', j.lease_generation,
|
||||
'attempt_count', j.attempts_started, 'lease_until', j.lease_until,
|
||||
'published_original', j.published_original_key,
|
||||
'variants', COALESCE((SELECT json_object_agg(v.name, json_build_object(
|
||||
'key',v.object_key,'sha256',v.sha256,'size',v.size_bytes,'width',v.width,'height',v.height))
|
||||
FROM attachment_variants v WHERE v.attachment_id=a.id AND v.pipeline_version=j.pipeline_version), '{{}}'),
|
||||
'attempts', COALESCE((SELECT json_agg(json_build_object(
|
||||
'attempt', x.attempt, 'generation', x.lease_generation,'started_at', x.started_at,
|
||||
'finished_at', x.finished_at, 'outcome', x.outcome, 'error_code', x.error_code) ORDER BY x.attempt)
|
||||
FROM attachment_attempts x WHERE x.job_id=j.id), '[]')
|
||||
) ORDER BY j.pipeline_version) FROM attachment_jobs j WHERE j.attachment_id=a.id), '[]'),
|
||||
'outbox', COALESCE((SELECT json_agg(json_build_object(
|
||||
'id', o.id, 'job_id', j.id, 'version', j.pipeline_version, 'available_at', o.available_at,
|
||||
'sent_at', o.sent_at, 'envelope', o.payload) ORDER BY o.created_at,o.id)
|
||||
FROM outbox o JOIN attachment_jobs j ON o.job_id=j.id WHERE j.attachment_id=a.id), '[]')
|
||||
) FROM attachments a WHERE a.id='{attachment}';
|
||||
""")
|
||||
check(bool(value), "accepted attachment disappeared")
|
||||
state = json.loads(value)
|
||||
check(state["sha256"] == ORIGINAL and state["size"] == len(SAMPLE), "original metadata changed")
|
||||
return state
|
||||
|
||||
def observe(self, name, att, row=None):
|
||||
row = self.state(att) if row is None else row
|
||||
self.e.event("versioned_state", stage=name, attachment=att["id"], state=row)
|
||||
return row
|
||||
|
||||
def ready(self, att, version, job_id, started=None):
|
||||
started = time.monotonic() if started is None else started
|
||||
deadline = started + self.timeout
|
||||
while time.monotonic() < deadline:
|
||||
row = self.state(att)
|
||||
check(row["version"] == version and jobs(row).get(version, {}).get("id") == job_id,
|
||||
"active version or job changed while waiting for ready")
|
||||
check(row["status"] in ("queued", "processing", "ready"), f"version {version} reached {row['status']}")
|
||||
if row["status"] == "ready" and time.monotonic() <= deadline:
|
||||
elapsed = time.monotonic() - started
|
||||
self.e.event("versioned_ready", version=version, job=job_id, seconds=elapsed)
|
||||
return elapsed
|
||||
time.sleep(0.25)
|
||||
raise Failure(f"version {version} did not reach ready within {self.timeout}s")
|
||||
|
||||
def verify_s3(self, expected):
|
||||
# Read every named object, including historical published objects that
|
||||
# are no longer exposed by GET. Store digests and sizes, not the bodies.
|
||||
shell = self.ops.S3_SETUP + """for key do
|
||||
"$rc" object show "app/$S3_BUCKET/$key" >/tmp/lab5-object
|
||||
digest=$(sha256sum /tmp/lab5-object)
|
||||
size=$(wc -c </tmp/lab5-object)
|
||||
printf '%s %s %s\\n' "$key" "${digest%% *}" "$size"
|
||||
done
|
||||
"""
|
||||
result = self.ops.compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "/bin/sh", "s3-init",
|
||||
"-c", shell, "lab5-versioned", *expected,
|
||||
label="read exact published S3 keys", timeout=30)
|
||||
rows = {}
|
||||
for line in result.stdout.decode().splitlines():
|
||||
key, sha256, size = line.split()
|
||||
check(key not in rows, "S3 returned duplicate keys")
|
||||
rows[key] = (sha256, int(size))
|
||||
self.e.event("versioned_s3", objects=rows)
|
||||
check(rows == expected, "actual published S3 objects differ from recorded hashes or sizes")
|
||||
|
||||
def verify(self, reader, att, version, expected_versions, stage):
|
||||
row = self.observe(stage, att)
|
||||
current = jobs(row)
|
||||
versions = {1, 2} if version == 2 else {1}
|
||||
check(set(current) == versions, "unexpected job versions")
|
||||
active = current[version]
|
||||
check(row["status"] == "ready" and row["version"] == version
|
||||
and row["original"] and row["original"] == active["published_original"], "wrong current published pointer")
|
||||
ready = verify_ready(self.c, reader, att, metadata(self.c, reader, att), decoder=self.pipeline.decoder)
|
||||
for item in ready["variants"]:
|
||||
db = active["variants"][item["name"]]
|
||||
check((db["sha256"], db["size"], db["width"], db["height"]) ==
|
||||
(item["sha256"], item["size_bytes"], item["width"], item["height"]),
|
||||
"HTTP variant differs from the current published DB row")
|
||||
expected = {}
|
||||
for v, job in current.items():
|
||||
if v not in expected_versions:
|
||||
check(not job["published_original"] and not job["variants"],
|
||||
"superseded attempt published an unexpected result")
|
||||
continue
|
||||
check(set(job["variants"]) == set(VARIANTS), "published version has missing or duplicate variants")
|
||||
check(job["attempt_count"] == len(job["attempts"]) and job["attempts"]
|
||||
and job["attempts"][-1]["outcome"] == "ready", "published job has no successful attempt")
|
||||
prefix = f"results/{att['id']}/v{v}/{job['generation']}/"
|
||||
keys = [job["published_original"], *[d["key"] for d in job["variants"].values()]]
|
||||
check(all(isinstance(k, str) and k.startswith(prefix) and not any(c.isspace() for c in k)
|
||||
for k in keys) and len(set(keys)) == 4, "published keys do not isolate version and generation")
|
||||
expected[keys[0]] = (ORIGINAL, len(SAMPLE))
|
||||
expected.update({d["key"]: (d["sha256"], d["size"]) for d in job["variants"].values()})
|
||||
|
||||
def cleaned():
|
||||
staging, actual = self.ops.list_key_sets(f"staging/{att['id']}/", f"results/{att['id']}/")
|
||||
self.e.event("versioned_listing", attachment=att["id"], staging=sorted(staging), results=sorted(actual))
|
||||
check(set(expected) <= actual, "cleanup lost a published object")
|
||||
return not staging and actual == set(expected)
|
||||
|
||||
wait(cleaned, self.timeout, "unpublished objects or staging remained after cleanup")
|
||||
self.verify_s3(expected)
|
||||
if expected_versions == {1, 2}:
|
||||
check(all(current[1]["variants"][n]["sha256"] != current[2]["variants"][n]["sha256"] for n in VARIANTS),
|
||||
"fixture does not distinguish the two pipeline outputs")
|
||||
return row
|
||||
|
||||
def upgrade(self, att):
|
||||
attachment = att["id"]
|
||||
|
||||
def cli():
|
||||
result = self.ops.compose("exec", "-T", self.ops.CLEANER, "/app/jobs", "upgrade",
|
||||
"-attachment-id", attachment, "-to-version", "2", label="operator upgrade")
|
||||
data = json.loads(result.stdout)
|
||||
check(data["attachment_id"] == attachment and data["pipeline_version"] == 2,
|
||||
"upgrade returned the wrong attachment/version")
|
||||
data["job_id"] = str(uuid.UUID(data["job_id"]))
|
||||
return data
|
||||
|
||||
first, repeated = cli(), cli()
|
||||
self.e.event("versioned_upgrade", first=first, repeated=repeated)
|
||||
check(first["queued"] is True and repeated["queued"] is False
|
||||
and first["job_id"] == repeated["job_id"], "upgrade retry created or selected a different job")
|
||||
row = self.state(att)
|
||||
check(set(jobs(row)) == {1, 2} and jobs(row)[2]["id"] == first["job_id"]
|
||||
and len(deliveries(row, 2)) == 1, "upgrade did not atomically create one v2 job and outbox")
|
||||
return first["job_id"]
|
||||
|
||||
def started_v1(self):
|
||||
alice, bob, _, chat = self.c.bootstrap()
|
||||
return bob, self.c.attachment(alice, chat)[0]
|
||||
|
||||
def ready_v1(self):
|
||||
reader, att = self.started_v1()
|
||||
self.ready(att, 1, jobs(self.state(att))[1]["id"])
|
||||
original = self.verify(reader, att, 1, {1}, "v1 baseline")
|
||||
self.ops.drained()
|
||||
return reader, att, original
|
||||
|
||||
def no_dlq(self, previous):
|
||||
now = self.ops.queue("image.invalid")["messages_ready"]
|
||||
self.e.event("versioned_dlq", before=previous, after=now)
|
||||
check(now == previous, "valid stale or duplicate delivery went to DLQ")
|
||||
|
||||
def duplicate_and_stale(self):
|
||||
reader, att, original = self.ready_v1()
|
||||
jid = self.upgrade(att)
|
||||
elapsed = self.ready(att, 2, jid)
|
||||
before = self.verify(reader, att, 2, {1, 2}, "before duplicate delivery")
|
||||
check(jobs(before)[1] == jobs(original)[1], "upgrade changed the previously published v1 job")
|
||||
self.ops.drained()
|
||||
dead = self.ops.queue("image.invalid")["messages_ready"]
|
||||
for version in (2, 1):
|
||||
outbox_id = self.ops.publish_fixture(att["id"], version=version)
|
||||
after = self.verify(reader, att, 2, {1, 2}, f"after valid v{version} delivery")
|
||||
injected = next(o for o in after["outbox"] if o["id"] == outbox_id)
|
||||
source = deliveries(before, version)[0]
|
||||
check(injected["sent_at"] and injected["envelope"] == source["envelope"],
|
||||
"injected job was not the original valid envelope")
|
||||
check(fingerprint(after) == fingerprint(before), "valid repeated/stale delivery changed the effect")
|
||||
self.no_dlq(dead)
|
||||
check(all(j["attempt_count"] == 1 for j in jobs(after).values()), "duplicate started another attempt")
|
||||
return after, elapsed
|
||||
|
||||
def reorder(self):
|
||||
self.ops.compose("stop", "-t", "4", self.ops.RELAY)
|
||||
oid = None
|
||||
try:
|
||||
reader, att = self.started_v1()
|
||||
queued = self.observe("v1 committed, relay stopped", att)
|
||||
(old,) = deliveries(queued, 1)
|
||||
check(old["sent_at"] is None and jobs(queued)[1]["attempt_count"] == 0, "v1 leaked before reorder")
|
||||
oid = str(uuid.UUID(old["id"]))
|
||||
changed = self.ops.sql(f"""UPDATE outbox SET available_at=clock_timestamp()+interval '12 hours'
|
||||
WHERE id='{oid}' AND sent_at IS NULL RETURNING id""").splitlines()
|
||||
check(changed == [oid, "UPDATE 1"], "could not delay the original v1 outbox row")
|
||||
jid = self.upgrade(att)
|
||||
held = self.observe("v1 delayed while v2 queued", att)
|
||||
self.ops.start(self.ops.RELAY)
|
||||
elapsed = self.ready(att, 2, jid)
|
||||
before = self.verify(reader, att, 2, {2}, "v2 ready before release of v1")
|
||||
check(deliveries(before, 1)[0]["id"] == oid and deliveries(before, 1)[0]["sent_at"] is None
|
||||
and jobs(before)[1]["attempt_count"] == 0, "old intent disappeared or was delivered ahead of v2")
|
||||
dead = self.ops.queue("image.invalid")["messages_ready"]
|
||||
self.release_outbox(oid)
|
||||
self.ops.await_publication(oid)
|
||||
after = self.verify(reader, att, 2, {2}, "after original v1 delivery")
|
||||
v1, v2 = deliveries(after, 1)[0], deliveries(after, 2)[0]
|
||||
check(v1["envelope"] == old["envelope"] == deliveries(held, 1)[0]["envelope"]
|
||||
and v1["sent_at"] and v2["sent_at"] and utc(v1["sent_at"]) > utc(v2["sent_at"]),
|
||||
"broker publication order or original envelope does not prove reorder")
|
||||
check(fingerprint(after) == fingerprint(before) and jobs(after)[2]["attempt_count"] == 1,
|
||||
"v1 sent after v2 changed jobs or published data")
|
||||
self.no_dlq(dead)
|
||||
return after, elapsed
|
||||
finally:
|
||||
if oid:
|
||||
self.release_outbox(oid)
|
||||
self.ops.start(self.ops.RELAY)
|
||||
|
||||
def release_outbox(self, oid):
|
||||
self.ops.sql(f"UPDATE outbox SET available_at=clock_timestamp() WHERE id='{oid}' AND sent_at IS NULL")
|
||||
|
||||
def arm(self, point):
|
||||
self.ops.clean_point(point)
|
||||
(self.ops.marker_dir() / (point + ".arm")).touch(exist_ok=False)
|
||||
|
||||
def marker(self, point, jid):
|
||||
path = self.ops.marker_dir() / (point + ".hit")
|
||||
value = self.ops.until(lambda: path.read_text().strip() if path.is_file() else None,
|
||||
f"no marker for {point}", seconds=30)
|
||||
check(value == jid, f"{point} marker was from a different job")
|
||||
self.e.event("versioned_marker", point=point, job=jid)
|
||||
|
||||
def release(self, point):
|
||||
(self.ops.marker_dir() / (point + ".release")).touch()
|
||||
|
||||
def crash(self, point):
|
||||
reader, att, baseline = self.ready_v1()
|
||||
cid = self.ops.one_container(self.ops.WORKER)
|
||||
self.arm(point)
|
||||
try:
|
||||
jid = self.upgrade(att)
|
||||
self.marker(point, jid)
|
||||
row = self.observe("before crash", att)
|
||||
job = jobs(row)[2]
|
||||
check(row["status"] == "processing" and job["attempt_count"] == 1 and job["lease_until"],
|
||||
"marker did not hold an active v2 attempt")
|
||||
expected = 0 if point == "before_objects" else 4
|
||||
prefix = f"results/{att['id']}/v2/{job['generation']}/"
|
||||
objects = self.ops.list_key_sets(prefix)[0]
|
||||
check(len(objects) == expected, "S3 side effect does not match the intended crash window")
|
||||
work_end = utc(job["attempts"][0]["started_at"]) + timedelta(
|
||||
seconds=self.ops.runtime()["job_timeout_seconds"])
|
||||
deadline = min(utc(job["lease_until"]), work_end)
|
||||
read_started = time.monotonic()
|
||||
remaining = (deadline - utc(self.state(att)["db_now"])).total_seconds()
|
||||
check(remaining > 0, "work deadline or lease elapsed before crash")
|
||||
started = time.monotonic()
|
||||
self.ops.run(["docker", "kill", "--signal", "KILL", cid], "kill held worker", timeout=8)
|
||||
check(time.monotonic() - read_started < remaining, "SIGKILL did not land while attempt was held")
|
||||
self.e.event("versioned_crash", point=point, container=cid, job=jid,
|
||||
work_budget_remaining_s=remaining, object_keys=sorted(objects))
|
||||
finally:
|
||||
self.release(point)
|
||||
self.ops.start(self.ops.WORKER)
|
||||
elapsed = self.ready(att, 2, jid, started)
|
||||
self.ops.drained()
|
||||
after = self.verify(reader, att, 2, {1, 2}, "after recovery")
|
||||
check(jobs(after)[1] == jobs(baseline)[1], "v2 crash changed historical v1")
|
||||
job = jobs(after)[2]
|
||||
check(job["attempt_count"] == 2 and
|
||||
[x["outcome"] for x in job["attempts"]] == ["lease_expired", "ready"] and
|
||||
job["generation"] > jobs(row)[2]["generation"], "crash did not recover in a new fenced attempt")
|
||||
return after, elapsed
|
||||
|
||||
def workers(self, count):
|
||||
self.ops.compose("up", "-d", "--no-deps", "--no-build", "--scale", f"{self.ops.WORKER}={count}",
|
||||
self.ops.WORKER, label=f"set {count} worker processes")
|
||||
|
||||
def started_at(self, cid):
|
||||
return self.ops.run(["docker", "inspect", "-f", "{{.State.StartedAt}}", cid],
|
||||
"old worker StartedAt").stdout.decode().strip()
|
||||
|
||||
def rejection(self, cid, jid, since):
|
||||
result = self.ops.run(["docker", "logs", "--timestamps", "--since", since, cid],
|
||||
"old worker finalization log")
|
||||
for line in (result.stdout + result.stderr).decode().splitlines():
|
||||
if "job finalization rejected" in line and jid in line:
|
||||
return line.split()[0]
|
||||
return None
|
||||
|
||||
def late_worker(self):
|
||||
old_cid = self.ops.one_container(self.ops.WORKER)
|
||||
original_process = self.started_at(old_cid)
|
||||
budget = self.ops.runtime()["job_timeout_seconds"]
|
||||
point = "after_objects"
|
||||
self.arm(point)
|
||||
scaled = False
|
||||
try:
|
||||
reader, att = self.started_v1()
|
||||
jid = jobs(self.state(att))[1]["id"]
|
||||
self.marker(point, jid)
|
||||
hold = self.observe("v1 stopped after its S3 writes", att)
|
||||
old = jobs(hold)[1]
|
||||
check(hold["status"] == "processing" and old["attempt_count"] == 1 and old["lease_until"],
|
||||
"v1 was not held with an active lease")
|
||||
prefix = f"results/{att['id']}/v1/{old['generation']}/"
|
||||
keys = self.ops.list_key_sets(prefix)[0]
|
||||
self.e.event("versioned_old_effect", job=jid, keys=sorted(keys))
|
||||
check(len(keys) == 4, "old worker did not write its output set")
|
||||
scaled = True
|
||||
self.workers(2)
|
||||
self.ops.until(lambda: self.ops.queue()["consumers"] == 2, "two workers did not join")
|
||||
check(self.started_at(old_cid) == original_process, "old worker was replaced")
|
||||
next_id = self.upgrade(att)
|
||||
elapsed = self.ready(att, 2, next_id)
|
||||
before = self.observe("v2 ready while v1 remains held", att)
|
||||
deadline = min(utc(old["lease_until"]), utc(old["attempts"][0]["started_at"]) + timedelta(seconds=budget))
|
||||
dead = self.ops.queue("image.invalid")["messages_ready"]
|
||||
released = utc(self.ops.sql("SELECT clock_timestamp()"))
|
||||
check(released < deadline, "old work deadline/lease elapsed before release")
|
||||
self.release(point)
|
||||
reject = self.ops.until(lambda: self.rejection(old_cid, jid, old["attempts"][0]["started_at"]),
|
||||
"resumed old worker did not reject finalization")
|
||||
self.e.event("versioned_rejected_commit", job=jid, container=old_cid, released_at=released.isoformat(),
|
||||
rejected_at=reject, deadline=deadline.isoformat())
|
||||
check(released <= utc(reject) < deadline and self.started_at(old_cid) == original_process,
|
||||
"old worker did not reach the version check within its original lease")
|
||||
self.ops.drained()
|
||||
after = self.verify(reader, att, 2, {2}, "after old worker rejection")
|
||||
check(jobs(after)[1]["attempt_count"] == 1 and jobs(after)[2]["attempt_count"] == 1
|
||||
and jobs(after)[2] == jobs(before)[2] and after["original"] == before["original"]
|
||||
and after["updated_at"] == before["updated_at"], "old worker overrode the v2 effect")
|
||||
self.no_dlq(dead)
|
||||
return after, elapsed
|
||||
finally:
|
||||
self.release(point)
|
||||
if scaled:
|
||||
self.workers(1)
|
||||
|
||||
|
||||
def series(pipeline, repetitions):
|
||||
# Imported after acceptance has set the explicit Compose scope.
|
||||
import pipeline_action as ops
|
||||
|
||||
if not ops.PROJECT or ops.PROJECT == "highload-lab5":
|
||||
raise Failure("explicit isolated versioned project required")
|
||||
try:
|
||||
ops.marker_dir()
|
||||
except ops.Unsupported as exc:
|
||||
raise Pending(str(exc)) from None
|
||||
pipeline.stand.public_topology()
|
||||
supported = ops.sql("""SELECT EXISTS (SELECT 1 FROM information_schema.columns
|
||||
WHERE table_schema=current_schema() AND table_name='attachment_jobs'
|
||||
AND column_name='published_original_key')""") == "t"
|
||||
if not supported:
|
||||
raise Pending("versioned pipeline migration is not installed on this stand")
|
||||
|
||||
experiment = Versioned(pipeline, ops)
|
||||
cases = (
|
||||
("duplicate-v2-and-stale-v1", experiment.duplicate_and_stale),
|
||||
("reorder-v2-before-v1", experiment.reorder),
|
||||
("crash-before-S3", lambda: experiment.crash("before_objects")),
|
||||
("crash-after-S3", lambda: experiment.crash("after_objects")),
|
||||
("late-v1-worker-after-v2", experiment.late_worker),
|
||||
)
|
||||
samples = defaultdict(list)
|
||||
digests = set()
|
||||
for repetition in range(1, repetitions + 1):
|
||||
for name, case in cases:
|
||||
start = time.monotonic()
|
||||
pipeline.c.evidence.event("versioned_trial_start", scenario=name, repetition=repetition)
|
||||
try:
|
||||
pipeline.action("reset")
|
||||
ops.one_container(ops.WORKER)
|
||||
ops.drained()
|
||||
row, ready_s = case()
|
||||
digest = {n: v["sha256"] for n, v in jobs(row)[2]["variants"].items()}
|
||||
digests.add(tuple(sorted(digest.items())))
|
||||
sample = {"status": "PASS", "ready_s": ready_s, "v2_sha256": digest,
|
||||
"attempts": {v: j["attempt_count"] for v, j in jobs(row).items()}}
|
||||
except (Failure, RuntimeError, OSError, ValueError) as exc:
|
||||
note = str(exc) if isinstance(exc, (Failure, RuntimeError)) else type(exc).__name__
|
||||
sample = {"status": "FAIL", "reason": note}
|
||||
sample["elapsed_s"] = time.monotonic() - start
|
||||
samples[name].append(sample)
|
||||
pipeline.c.evidence.event("versioned_trial", scenario=name, repetition=repetition, **sample)
|
||||
print(f"{sample['status']}: {name}, repeat {repetition}/{repetitions}"
|
||||
+ (f" — {sample['reason']}" if "reason" in sample else ""), flush=True)
|
||||
|
||||
aggregates = {}
|
||||
for name, trials in samples.items():
|
||||
ready = [r["ready_s"] for r in trials if r["status"] == "PASS"]
|
||||
aggregates[name] = {
|
||||
"attempted": len(trials), "passed": len(ready), "failed": len(trials) - len(ready),
|
||||
"ready_seconds": [min(ready), median(ready), max(ready)] if ready else None,
|
||||
}
|
||||
stable = len(digests) == 1
|
||||
pipeline.c.evidence.event("versioned_summary", repeats=repetitions, results=aggregates,
|
||||
identical_v2=stable, v2_sha256=dict(next(iter(digests))) if stable else None)
|
||||
check(all(result["passed"] == repetitions for result in aggregates.values()) and stable,
|
||||
"versioned experiment failed a trial or produced different v2 checksums")
|
||||
Reference in New Issue
Block a user