ЛР 4 — БПИ2303 — Лазарев — на 3 #91
+43
-8
@@ -1,20 +1,55 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
# scripts/init-secrets.sh делает это сам и создаёт файлы в secrets/ (Docker secrets).
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
# Пароль БД НЕ задаётся здесь: он в файле secrets/postgres_password (Docker secret),
|
||||
# в контейнерах виден как /run/secrets/postgres_password (POSTGRES_PASSWORD_FILE).
|
||||
# Вместо DATABASE_URL_FILE из skeleton используется POSTGRES_* + POSTGRES_PASSWORD_FILE;
|
||||
# приложение понимает и DATABASE_URL_FILE (см. REPORT.md).
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_USER=messenger
|
||||
# Сессии хранятся в PostgreSQL (lab2), Redis/Valkey не используется:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
DB_POOL_SIZE=10
|
||||
# Graceful shutdown реплики: пауза с ready=503 и лимит на дообслуживание запросов.
|
||||
DRAIN_SECONDS=3
|
||||
SHUTDOWN_TIMEOUT_SECONDS=10
|
||||
LB_PORT=8080
|
||||
APP_VERSION=1
|
||||
# Защита от OOM при шторме входов: одновременных scrypt на реплику и ожидание слота (с).
|
||||
PASSWORD_HASH_CONCURRENCY=2
|
||||
PASSWORD_HASH_WAIT_SECONDS=0.5
|
||||
# Readiness: фоновый пинг БД (с) и сколько секунд без успешного пинга реплика ещё «готова».
|
||||
DB_HEALTH_INTERVAL_SECONDS=1
|
||||
READY_STALE_SECONDS=3
|
||||
# Попыток POST /auth/sessions за 10 с с одного IP на LB (сверх — 429).
|
||||
LOGIN_RATE_LIMIT=20
|
||||
|
||||
# --- Lab4: S3 (SeaweedFS) и вложения ---
|
||||
# S3 API SeaweedFS слушает 8333 (не 9000, как у MinIO); наружу не публикуется.
|
||||
S3_ENDPOINT=http://s3:8333
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
# Ключи API (права только Read+Write на bucket). Значения — в secrets/, здесь только пути.
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_api_access_key
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_api_secret_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
# Весь приём тела upload, с; одновременных загрузок и JPEG-декодирований на реплику.
|
||||
UPLOAD_TIMEOUT_SECONDS=60
|
||||
UPLOAD_CONCURRENCY=8
|
||||
DECODE_CONCURRENCY=2
|
||||
# Одновременных S3 PUT на реплику (~20 MiB RAM каждый), остальные ждут в очереди.
|
||||
S3_PUT_CONCURRENCY=3
|
||||
S3_CONNECT_TIMEOUT_SECONDS=2
|
||||
# < timeout server 10s у LB: на зависший S3 API сам отвечает 503, а не LB 504.
|
||||
S3_READ_TIMEOUT_SECONDS=5
|
||||
# Janitor: возраст, после которого pending-строка/объект без строки считаются брошенными, и период обхода.
|
||||
ATTACHMENT_GRACE_SECONDS=3600
|
||||
JANITOR_INTERVAL_SECONDS=300
|
||||
# Только для эксперимента отказов (student-tests/consistency_faults.py). В обычной работе 0.
|
||||
FAULT_INJECTION=0
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# Lab4: мессенджер на Python + PostgreSQL + S3. Один образ для API-реплик и job-ов
|
||||
# migrate (схема), s3-init (bucket) и janitor (сверка БД/S3).
|
||||
FROM python:3.12.7-slim@sha256:60d9996b6a8a3689d36db740b49f4327be3be09a21122bd02fb8895abb38b50d
|
||||
|
||||
# MALLOC_ARENA_MAX=2: glibc не заводит арену на каждый поток ThreadingHTTPServer —
|
||||
# освобождённые буферы upload возвращаются в общий пул, RSS не растёт с числом потоков.
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
MALLOC_ARENA_MAX=2 \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Сначала зависимости (закреплённые версии) — слой кэшируется, пока не изменится requirements.txt.
|
||||
COPY requirements.txt /app/
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY src/ /app/src/
|
||||
COPY migrations/ /app/migrations/
|
||||
# Временные файлы upload (безымянные O_TMPFILE): каталог в writable-слое контейнера.
|
||||
RUN mkdir -p /tmp/uploads && chmod 1777 /tmp/uploads
|
||||
ENV UPLOAD_TMP_DIR=/tmp/uploads
|
||||
|
||||
# Метка версии сборки (rolling update: scripts/rolling-update.sh собирает с новым значением).
|
||||
ARG APP_VERSION=1
|
||||
ENV APP_VERSION=${APP_VERSION}
|
||||
|
||||
RUN useradd --no-create-home --uid 10001 app
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
# Python-процесс — PID 1 (exec-форма), сам обрабатывает SIGTERM (graceful shutdown).
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=5s --timeout=2s --start-period=10s --retries=2 \
|
||||
CMD ["python", "-c", "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).status == 200 else 1)"]
|
||||
CMD ["python", "/app/src/server.py"]
|
||||
@@ -1,37 +1,269 @@
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Лазарев Юрий Сергеевич, БПИ2303
|
||||
- Целевая оценка; выбранный трек 5, если нужен: **4**, трек 5 не заявлен
|
||||
- Commit/PR: [PR #91 — ЛР 4 — БПИ2303 — Лазарев — на 4](https://gitea.privcloud.tech/mtusi2026/mtusi2026lab4/pulls/91); реализация `c5a07dc`, ветка `solution/bpi2303-lazarev`, fork [zemiles/mtusi2026lab4](https://gitea.privcloud.tech/zemiles/mtusi2026lab4).
|
||||
- Использованные источники, библиотеки и помощь ИИ: Python 3.12 (стандартная библиотека: `http.server`, `hashlib`, `zlib`, `tempfile`, `threading`), `psycopg[binary]==3.2.3`, `psycopg-pool==3.2.4`, `minio==7.2.15` (S3-клиент, SigV4, multipart), `urllib3==2.3.0`, `Pillow==11.1.0` (только пробное декодирование JPEG). Образы: `python:3.12.7-slim@sha256:60d9996b…b50d`, `postgres:16.4-alpine@sha256:5660c2cb…e64c`, `haproxy:3.0.5-alpine@sha256:43a2591a…e949`, `chrislusf/seaweedfs:4.50@sha256:c2658820…4860` (полные digest — в `compose.yaml` и `Dockerfile`). Документация: AWS S3 (PutObject, multipart, presigned URLs), SeaweedFS wiki (S3 API, `s3.json` identities, `weed server` flags), спецификация PNG (RFC 2083 / W3C PNG: chunks, CRC, Adam7), JPEG (ITU T.81, маркеры SOF), Docker Compose, HAProxy 3.0. Код lab3 перенесён и доработан с помощью ИИ-ассистента (Claude); решения, запуск и проверки — автор.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Проверено: MacBook Air M3, 16 GB RAM, macOS 26.4; Docker Desktop 28.0.4 (VM 8 vCPU, 7.7 GiB), Compose v2.34.0; Python 3.12 на хосте только для тестов. Порты `127.0.0.1:8080` (LB) и `127.0.0.1:8404` (статистика HAProxy) должны быть свободны (стенд lab3 нужно остановить: `docker compose stop` в его каталоге).
|
||||
|
||||
```sh
|
||||
# 0. Локальные секреты и .env (не коммитятся; значения не печатаются; повтор ничего не перезаписывает).
|
||||
# Создаёт пароль БД, три пары ключей S3 (admin / api / janitor) и secrets/s3_identities.json с их правами.
|
||||
./scripts/init-secrets.sh
|
||||
|
||||
# 1. Проверка конфигурации, сборка, запуск, ожидание готовности
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
# порядок: db, s3 (healthy) -> migrate, s3-init (exit 0) -> api x2, janitor (healthy) -> lb
|
||||
docker compose ps # migrate и s3-init Exited (0); порты только у lb
|
||||
|
||||
# 2. Обязательные проверки
|
||||
make check && make test
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh && ./scripts/start-all.sh
|
||||
|
||||
# 3. Проверки уровня 4 (результаты сохраняются в evidence/)
|
||||
docker compose --profile tools run --rm s3-check # приватность bucket и права ключей вне API
|
||||
docker compose --env-file .env run --rm --no-deps s3-init # повторный bootstrap — идемпотентен
|
||||
python3 student-tests/attachments_negative.py --output evidence/attachments-negative.json
|
||||
python3 student-tests/attachment_failover.py --output evidence/attachment-failover.json
|
||||
python3 student-tests/s3_outage.py --output evidence/s3-outage.json
|
||||
python3 student-tests/upload_memory.py --concurrency 12 --rounds 3 --output evidence/upload-memory-c12.json
|
||||
FAULT_INJECTION=1 docker compose --env-file .env up -d --no-deps --wait api # учебный хук отказов, только на время теста
|
||||
python3 student-tests/consistency_faults.py --output evidence/consistency-faults.json
|
||||
docker compose --env-file .env up -d --no-deps --wait api # обратно FAULT_INJECTION=0
|
||||
|
||||
# 4. Janitor вручную: отчёт без изменений / исправление
|
||||
docker compose run --rm --no-deps janitor python /app/src/janitor.py --once --dry-run
|
||||
docker compose run --rm --no-deps janitor python /app/src/janitor.py --once
|
||||
|
||||
# 5. Безопасная остановка (данные остаются в volumes pgdata и s3data)
|
||||
docker compose stop # или docker compose down (контейнеры удаляются, volumes остаются)
|
||||
|
||||
# 6. Намеренное удаление учебных данных (НЕОБРАТИМО: БД и все объекты S3)
|
||||
docker compose down -v
|
||||
```
|
||||
|
||||
Прогрев: от `up` до готовности ~30 с (SeaweedFS ~10–25 с: выбор raft-лидера master и регистрация volume-сервера). Bootstrap bucket и миграции выполняются автоматически однократными job; действия оператора, кроме перечисленных, не нужны. Однажды `docker compose up --build` завис на этапе сборки, повтор и `docker compose build` прошли; воспроизвести не удалось.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
клиент ──HTTP──> lb (HAProxy, 127.0.0.1:8080) ──roundrobin──> api × 2 (без портов наружу)
|
||||
│ │
|
||||
migrate (job) ──> db (PostgreSQL 16, pgdata) метаданные, сессии, ключи
|
||||
s3-init (job) ──> s3 (SeaweedFS 4.50, s3data) байты вложений, приватный bucket
|
||||
janitor ─────────> db + s3 (сверка, очистка)
|
||||
```
|
||||
|
||||
| Роль | Service | Образ | Health/readiness | Volume | Сеть / порт | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| LB | `lb` | `haproxy:3.0.5-alpine` | проверка конфигурации; сам проверяет `/health/ready` API | — | frontend+backend; `127.0.0.1:8080`, `:8404` | нет |
|
||||
| API | `api` ×2 | `mtusi-messenger:lab4` (из `Dockerfile`) | `/health/live`, `/health/ready` (только БД) | — (без состояния) | backend, `8080` внутри | `postgres_password`, `s3_api_*` |
|
||||
| Миграции | `migrate` | тот же | exit 0 | — | backend | `postgres_password` |
|
||||
| БД | `db` | `postgres:16.4-alpine` | `pg_isready` | `pgdata` | backend (`internal`) | `postgres_password` |
|
||||
| S3 | `s3` | `chrislusf/seaweedfs:4.50` | `/healthz` S3 **и** работающая запись (PUT во внутренний filer) | `s3data` | backend, только `:8333` | `s3_identities.json` |
|
||||
| Bootstrap S3 | `s3-init` | `mtusi-messenger:lab4` | exit 0 | — | backend | `s3_admin_*` (только он) |
|
||||
| Сверка | `janitor` | тот же | heartbeat-файл ≤ 90 с | — | backend | `postgres_password`, `s3_janitor_*` |
|
||||
| Проверка | `s3-check` (profile `tools`) | тот же | — | — | backend | `s3_api_*`, `s3_janitor_*` |
|
||||
|
||||
### Почему SeaweedFS
|
||||
|
||||
Задание разрешает MinIO, SeaweedFS или RustFS. Образы `minio/minio` и `minio/mc` на момент работы удалены с Docker Hub (`pull access denied … repository does not exist`), на quay.io доступ закрыт. У SeaweedFS права ключей задаются декларативно (`s3.json` identities), это проще проверить и повторить. Один процесс `weed server`: master, volume и filer слушают **только 127.0.0.1 внутри контейнера**. Их HTTP API (UI master `:9333`, filer `:8888`, volume `:8080`) обходит авторизацию S3, поэтому они недоступны даже из backend-сети. Наружу контейнера открыт только S3 `:8333`. Встроенный IAM API (`-s3.iam=false`), Iceberg и Lance выключены; порты на хост не публикуются. Отдельной веб-консоли у SeaweedFS нет.
|
||||
|
||||
### Модель данных и транзакционные границы
|
||||
|
||||
`migrations/003_attachments.sql` (expand-only): `attachments` (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, `object_key UNIQUE`, `status pending|ready`, created_at, updated_at) и `message_attachments (message_id, attachment_id, position)`.
|
||||
|
||||
- **Object key назначает сервер:** `originals/<случайный uuid4>`. Он не совпадает с id вложения и не содержит filename. Filename — только отображаемое имя: 1–255 code points, без `/ \`, NUL, управляющих символов, bidi-override (U+202A–E, U+2066–9, U+200E/F), не `.`/`..`. Наружу ключ, bucket и адрес S3 не отдаются.
|
||||
- **Upload** `POST /chats/{id}/attachments?filename=…`. Порядок проверок:
|
||||
1. сессия;
|
||||
2. членство в чате (посторонний получает 404);
|
||||
3. filename, Content-Type (`image/png`|`image/jpeg`, иначе 415), Content-Length (> 10 MiB → 413 до чтения тела; chunked → 400);
|
||||
4. известный отказ S3 → 503 до приёма 10 MiB.
|
||||
|
||||
Затем тело читается кусками по 64 KiB в **безымянный временный файл** (`tempfile.TemporaryFile` → `O_TMPFILE`: у файла нет имени в каталоге, он исчезает при закрытии и при падении процесса). SHA-256 считается на лету. По первым 33 байтам проверяются сигнатура (подмена MIME → 415) и пиксели из PNG IHDR (> 40 Мпикс → 413). Потом — полная проверка содержимого (`src/images.py`):
|
||||
- **PNG** — собственный потоковый валидатор: CRC каждого chunk, порядок IHDR/PLTE/IDAT/IEND, допустимые IHDR, IDAT распаковывается zlib шагами по 1 MiB без сохранения результата. Объём распакованных данных должен **точно** совпасть с вычисленным из IHDR (с учётом Adam7): больше — zlib-бомба, меньше — обрезанный файл. Данные после IEND (полиглот) не принимаются;
|
||||
- **JPEG** — размеры из маркера SOF без декодирования, затем пробное декодирование Pillow в режиме `draft` (масштаб 1/8): 36 Мпикс занимают ~2 MiB вместо ~108 MiB.
|
||||
- **Запись: три шага, их порядок — основа согласованности:**
|
||||
1. `INSERT … status='pending'` (COMMIT) — намерение известно БД **до** записи в S3;
|
||||
2. S3 PUT (multipart, части по 5 MiB);
|
||||
3. `UPDATE … SET status='ready' WHERE status='pending'` → **201** только после этого.
|
||||
|
||||
Отсюда инвариант: в bucket нет объекта, о котором не знает БД (кроме ручного вмешательства).
|
||||
- **Компенсация.** PUT не удался (в том числе по таймауту, когда объект мог успеть записаться) или не удался шаг 3 → API удаляет объект, затем pending-строку. Если S3 не ответил, строка остаётся pending, и её добирает janitor. Если строку уже убрал janitor (шаг 3 вернул 0 строк), API удаляет свой объект и отвечает 503.
|
||||
- **Janitor** (`src/janitor.py`, под `pg_try_advisory_lock`), за один проход:
|
||||
- pending-строки старше grace → удалить объект (идемпотентно), затем строку;
|
||||
- объекты `originals/*` старше grace без строки → удалить;
|
||||
- ready-строки без объекта (строка стала ready раньше начала обхода bucket) → **только отчёт**, метаданные автоматически не удаляются.
|
||||
|
||||
Grace по умолчанию 3600 с (`ATTACHMENT_GRACE_SECONDS`). Это в 60 раз больше полного срока приёма тела (`UPLOAD_TIMEOUT_SECONDS=60`) и таймаутов S3, поэтому идущая загрузка не может быть принята за брошенную. Ready-вложения janitor не удаляет никогда. Режимы: `--dry-run`, `--once`, фоновый цикл раз в 300 с.
|
||||
- **Сообщение с вложениями.** В той же транзакции, что и в lab3 (блокировка строки чата + ключ идемпотентности), выполняется `SELECT … FOR SHARE` по `attachment_ids`: все должны быть ready и принадлежать **этому** чату. Чужое, неизвестное или из другого чата того же пользователя — одинаково 404. `text=""` допустим только с ≥1 вложением. Отпечаток тела для `Idempotency-Key` включает `attachment_ids`; в lab3 он уже считался с `[]`, поэтому старые ключи остались валидными.
|
||||
- **Download** `GET /attachments/{id}/content`: только участникам чата; pending не виден. Байты идут потоком из S3 через API, **без redirect**. Заголовки: `Content-Type` из метаданных, `Content-Length`, `X-Content-Type-Options: nosniff`, `Cache-Control: private, no-store`, `ETag` = SHA-256. После отдачи размер и SHA-256 сверяются с метаданными; расхождение пишется в лог, соединение закрывается. Нет объекта при ready-метаданных → 503 и `ERROR` в логе (такое рассогласование находит janitor). `variant=thumbnail|crop|optimized` → 404 (в lab4 вариантов нет), прочее → 400.
|
||||
|
||||
### Права S3 (`secrets/s3_identities.json`, генерирует `init-secrets.sh`)
|
||||
|
||||
| Ключ | Кто получает | Права в SeaweedFS | Проверено `s3-check` |
|
||||
| --- | --- | --- | --- |
|
||||
| admin | только job `s3-init` | Admin, Read, List, Write | — |
|
||||
| api | реплики API | `Read:bucket`, `Write:bucket` | Put/Get/Delete можно; ListBucket, CreateBucket, DeleteBucket, PutBucketPolicy — AccessDenied |
|
||||
| janitor | `janitor` | `List:bucket`, `Write:bucket` | List/Delete можно; **GetObject — AccessDenied** (содержимое не читает); CreateBucket — AccessDenied |
|
||||
| аноним | — | нет identity | GET объекта, ListBucket, ListAllMyBuckets, PUT — 403 |
|
||||
|
||||
Ограничение SeaweedFS: действие `Write` включает и Put, и Delete, поэтому отдельного «только удалять» для janitor нет.
|
||||
|
||||
**Bootstrap** (`src/s3_bootstrap.py`) идемпотентен:
|
||||
- ждёт S3;
|
||||
- создаёт bucket, только если его нет;
|
||||
- кладёт probe-объект и проверяет **анонимными** HTTP-запросами, что GET и List дают 403;
|
||||
- если bucket публичен — exit 1, и API не стартует.
|
||||
|
||||
Повторный запуск: `created:false, already_existed:true, private:true` (`evidence/s3-bootstrap-idempotent.txt`).
|
||||
|
||||
### Health, таймауты, лимиты (дополнение к таблице lab3)
|
||||
|
||||
| Параметр | Значение | Почему |
|
||||
| --- | --- | --- |
|
||||
| `/health/ready` | только PostgreSQL (как в lab3) | S3 общий для всех реплик: убрать все реплики из LB при отказе S3 бессмысленно, а текстовые сообщения без S3 работают. Проверено: при остановленном S3 ready=200, сообщения 201 |
|
||||
| S3Health (фон, 1 с) | PUT + GET `health/<реплика>`, устарело через 3 с | У SeaweedFS после рестарта `/healthz` и HEAD bucket уже успешны, а первая запись ещё висит. При подтверждённом отказе upload и download → сразу 503; на старте реплики upload ждёт первой успешной проверки до `S3_STARTUP_WAIT_SECONDS=5` |
|
||||
| healthcheck `s3` | `/healthz` и PUT маленького файла во внутренний filer (`/.healthcheck/probe`, вне `/buckets`, через S3 не виден); `start_interval 1s`, затем раз в 5 с | после рестарта SeaweedFS запись ещё 10–20 с не готова (выбор raft-лидера, выдача volume). Без проверки записи `restart.sh` перезапускал API раньше, и `make test-failover` сразу после `make test-persistence` падал на первой загрузке (503) |
|
||||
| S3-клиент API | connect 2 с, read 5 с, без повторов | 5 с < `timeout server 10s` у LB: API сам отвечает 503 в формате контракта, а не LB 504 |
|
||||
| HAProxy для upload | `http-request set-timeout server 75s` | приём ≤ 60 с + PUT; тело проксируется потоком (без `http-buffer-request`) |
|
||||
| Приём тела | `UPLOAD_TIMEOUT_SECONDS=60` на всё тело, 30 с на один recv | медленный клиент не держит поток бесконечно |
|
||||
| Параллелизм на реплику | загрузок 8 (ожидание 5 с → 503), JPEG-декодирований 2, **S3 PUT 3** (ожидание 30 с) | PUT — самый дорогой по памяти шаг (см. эксперимент) |
|
||||
| Ранний отказ (401/404/413/415) | остаток тела ≤ 20 MiB дочитывается и выбрасывается, больше — соединение закрывается | иначе клиент, ещё передающий 10 MiB, получал обрыв вместо JSON 413 |
|
||||
| `MALLOC_ARENA_MAX=2` | в образе | glibc не держит освобождённые буферы в арене каждого потока |
|
||||
| SeaweedFS | `GOMEMLIMIT=512MiB`, лимит 768 MiB, `-{s3,filer,volume}.concurrentUploadLimitMB=64`, кэши чтения 16/32 MiB, `restart: unless-stopped` | без этого был OOM-kill при 12 параллельных загрузках (см. ниже) |
|
||||
| Лимиты ресурсов | api 0.5 CPU/256 MiB, s3 1 CPU/768 MiB, db 1 CPU/512 MiB, janitor 0.25 CPU/128 MiB, lb 0.5 CPU/128 MiB | |
|
||||
|
||||
### Что перенесено из lab3 и что изменено
|
||||
|
||||
Перенесены без изменения поведения: REST API, scrypt и семафор входов, Bearer-сессии в PostgreSQL, идемпотентность сообщений, `X-Instance-Id`, graceful shutdown, job миграций, HAProxy (DNS-обнаружение реплик, JSON-ошибки LB, rate limit входа), скрипты `stop-one.sh`, `start-all.sh`, `failover-each.sh`, `rolling-update.sh`. Регрессия lab3 прогнана повторно (`evidence/lab3-regression.txt`: 6 проверок cursor; 320 конкурентных запросов через 2 реплики, 20 сообщений, 0 дублей). Изменено:
|
||||
- `Message.attachment_ids`;
|
||||
- маршрутизация: тело читается после выбора маршрута, а upload читает его сам, потоком;
|
||||
- `restart.sh` перезапускает и S3;
|
||||
- у `db` и `s3` появился `restart: unless-stopped`;
|
||||
- `stop-one.sh` берёт список реплик у `docker compose ps`, а не по жёстко прописанному имени проекта: хук работает и при другом `COMPOSE_PROJECT_NAME` (так проверялся чистый clone);
|
||||
- digest-ы образов закреплены полностью.
|
||||
|
||||
`failover-each.sh` и `rolling-update.sh` в lab4 повторно не прогонялись.
|
||||
|
||||
### Соответствие `.env.example`
|
||||
|
||||
| Переменная skeleton | Реализация |
|
||||
| --- | --- |
|
||||
| `APP_*`, `SESSION_TTL_SECONDS`, `IDEMPOTENCY_TTL_SECONDS`, `API_REPLICAS`, `SESSION_STORE=postgres` | как в lab3 |
|
||||
| `DATABASE_URL_FILE` | поддерживается; в compose используется `POSTGRES_*` + `POSTGRES_PASSWORD_FILE` |
|
||||
| `CACHE_URL_FILE` | не используется (Redis/Valkey нет) |
|
||||
| `S3_ENDPOINT` | `http://s3:8333` (порт SeaweedFS S3, не 9000 как у MinIO) |
|
||||
| `S3_REGION`, `S3_BUCKET`, `MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` | как есть (`us-east-1`, `messenger-attachments`, 10485760, 40000000) |
|
||||
| `S3_ACCESS_KEY_ID_FILE`, `S3_SECRET_ACCESS_KEY_FILE` | файлы Docker secrets; у каждого сервиса свой ключ (api / janitor / s3-init) |
|
||||
| добавлены | `UPLOAD_TIMEOUT_SECONDS`, `UPLOAD_CONCURRENCY`, `DECODE_CONCURRENCY`, `S3_PUT_CONCURRENCY`, `S3_CONNECT_TIMEOUT_SECONDS`, `S3_READ_TIMEOUT_SECONDS`, `S3_STARTUP_WAIT_SECONDS`, `ATTACHMENT_GRACE_SECONDS`, `JANITOR_INTERVAL_SECONDS`, `FAULT_INJECTION` (по умолчанию 0) |
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
Все прогоны — 07.11.2026 на итоговом коде (после исправлений из раздела «Повторная проверка»), машина и лимиты — как выше. Тот же набор дополнительно прошёл в чистом clone с новыми секретами и пустыми volumes.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke | `make check`, `make test` | PASS; checksum, 404 постороннему для метаданных и байтов | `evidence/check.txt`, `evidence/smoke.txt` |
|
||||
| 3: S3 в общем стенде, метаданные в PostgreSQL, байты в приватном bucket, не в БД и не на диске API | `docker compose ps`; `s3-check`; осмотр контейнеров API | у API нет volumes (только bind-файлы secrets), `/tmp/uploads` пуст после всех тестов, временный файл безымянный; анонимные GET/List/PUT → 403 | `compose.yaml`, `evidence/api-no-local-originals.txt`, `evidence/s3-private-check.txt` |
|
||||
| 3: 201 ready после сохранения, побайтный download, message с `attachment_ids` читается участником | `make test`, `attachments_negative.py` | 201 `status=ready`, SHA-256 и Content-Type совпадают для PNG, JPEG и PNG 10 482 871 B; bob скачивает файл alice, отправляет `text=""` + вложение | `evidence/smoke.txt`, `evidence/attachments-negative.txt` |
|
||||
| 3: PNG/JPEG ≤ 10 MiB и ≤ 40 Мпикс, MIME по содержимому, опасные filename, лимиты до чтения/декодирования | `attachments_negative.py` | 10 MiB+1 → 413; IHDR 100000² и 7000×6000 → 413 без распаковки; zlib-бомба 50 MB → 415; 13 вариантов опасных filename → 400 | `evidence/attachments-negative.json` |
|
||||
| 3: upload → остановка обслужившей реплики → download через другую | `attachment_failover.py` (по каждой реплике) | 2/2 раунда: остановлена именно загрузившая реплика, 5/5 скачиваний другой репликой, SHA-256 совпал | `evidence/attachment-failover.json` |
|
||||
| 3: restart с volumes сохраняет метаданные и оригинал | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` ×2 | PASS; `StartedAt` всех 6 контейнеров (db, s3, api×2, janitor, lb) изменился; тот же токен, тот же файл | `evidence/persistence-failover.txt` |
|
||||
| 3: failover (публичный) | `make test-failover` ×2, каждый раз **сразу после** persistence | PASS, 2 реплики, 129/128 записей, 0 неуспешных, восстановление 3,7/3,3 с | `evidence/persistence-failover.txt` |
|
||||
| 4: тесты: большой файл, повреждённое изображение, подмена MIME, чужое `attachment_id`, вложение другого чата; ошибка пользователя ≠ 500 | `attachments_negative.py` | 60/60 PASS, **0 ответов 5xx**; все ошибки — JSON контракта с `request_id` = `X-Request-Id` | `evidence/attachments-negative.json` |
|
||||
| 4: прерывание загрузки и отказ между S3 и БД не оставляют вечных объектов; компенсация/сверка с grace | `consistency_faults.py` (`FAULT_INJECTION=1`) | см. «Согласованность» ниже: компенсация ничего не оставляет, свежее не удаляется, после grace удалено всё брошенное, повторный проход ничего не находит | `evidence/consistency-faults.json` |
|
||||
| 4: лимиты/таймауты и потоковая обработка; ≥ 10 одновременных загрузок с замером пика памяти | `upload_memory.py --concurrency 12` и `20` | 36/36 и 60/60 × 201; пиковый RSS API 91–97 MiB при лимите 256 и **не растёт** с 12 до 20; до исправления — 178–189 MiB | `evidence/upload-memory-c{12,20}.json`, `evidence/before-fix/` |
|
||||
| 4: bootstrap bucket идемпотентен | `s3-init` два раза подряд | оба раза exit 0, `created:false`, `private:true` | `evidence/s3-bootstrap-idempotent.txt` |
|
||||
| 4: у API отдельные ограниченные S3 credentials; консоль не открыта; проверка private bucket вне API | `docker compose --profile tools run --rm s3-check` | 21/21 PASS: права api/janitor/анонима как в таблице; из backend-сети закрыты 9333, 8080, 8888, 8111, 8181, 9101, открыт только 8333; на хост S3 не опубликован | `evidence/s3-private-check.txt` |
|
||||
| Проверка недоступности S3 (README, п. 5) | `s3_outage.py` (`stop` и `pause` S3) | upload/download → 503 `unavailable` + `Retry-After: 1` за 10–15 мс; сообщения 201, ready 200; восстановление без перезапуска API | `evidence/s3-outage.json` |
|
||||
| Регрессия lab3 | `cursor_validation.py`, `idempotency_concurrency.py` | PASS; 0 дублей | `evidence/lab3-regression.txt` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
### Согласованность PostgreSQL ↔ S3 (`student-tests/consistency_faults.py`)
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
Методика: реальные upload через LB с заголовком `X-Fault-Inject`. Хук включён только при `FAULT_INJECTION=1`, в обычной работе выключен. `crash-*` — `os._exit(86)` прямо в обработчике: процесс умирает без finally и компенсаций (как SIGKILL), Docker перезапускает контейнер. Состояние БД и bucket снимается janitor в режиме `--dry-run`. Сироты и «missing» внедряются вручную: удалением строки в psql и удалением объекта ключом api.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Итог |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| `db-fail-after-s3-put`: PUT прошёл, перевод в ready упал | 503, компенсация | 503; новых pending 0, новых объектов 0 | ничего не осталось |
|
||||
| `crash-after-s3-put` ×2: процесс умер после PUT | pending + объект ждут janitor | клиент получил ошибку соединения; +2 pending, +2 объекта; реплика перезапущена | убрано janitor |
|
||||
| `crash-after-pending`: процесс умер до PUT | pending без объекта | +1 pending, объектов не прибавилось | убрано janitor |
|
||||
| Клиент оборвал upload на 1 MiB из 5 | ничего не создаётся | строк и объектов не прибавилось (временный файл без имени исчез) | — |
|
||||
| Строку брошенной загрузки удалили вручную | объект-сирота | janitor: `orphan_objects: 1` | удалён после grace |
|
||||
| Объект ready-вложения удалили в S3 | только отчёт, download 503 | download 503 (не 500); `missing_objects` растёт, строка не удалена | требует человека |
|
||||
| janitor с grace 3600 (всё свежее), dry-run и боевой | ничего не удалять | `deleted_objects: 0, deleted_rows: 0` | свежие и используемые не тронуты |
|
||||
| ожидание 22 с, janitor с grace 20: dry-run → боевой → повтор | найти → удалить → 0 | dry-run: 3 брошенных pending + 1 сирота, удалено 0; боевой: удалено 4 объекта и 3 строки; повтор: 0/0/0 | контрольное ready-вложение скачивается, SHA-256 совпал |
|
||||
|
||||
Третья брошенная pending-строка — не от инъекции: до эксперимента в БД уже лежала одна (baseline `pending: 1`). Она осталась от теста отказа S3: первая загрузка во время `pause` упала по таймауту PUT, удалить объект тоже не вышло, и строка по проекту осталась pending. Janitor убрал её вместе с остальными. В более раннем прогоне (до исправления памяти SeaweedFS) таких строк было 15 — следы OOM-kill S3, — и janitor их так же нашёл и убрал. Ещё эксперимент нашёл ошибку в первой версии компенсации. При неудачном PUT удалялась только pending-строка, а PUT по таймауту мог успеть записать объект: так возникли 2 объекта-сироты. Исправлено: сначала удаляется объект, потом строка. `missing_objects: 4` — объекты, намеренно удалённые этим экспериментом в четырёх прогонах; строки остаются, как и задумано. Обход bucket из ~470 объектов и сверка с БД занимают ≈ 100 мс за проход.
|
||||
|
||||
### Память при одновременных загрузках (`student-tests/upload_memory.py`)
|
||||
|
||||
Гипотеза: потоковый приём (буфер 64 KiB → временный файл), multipart PUT и draft-декодирование держат RAM реплики ограниченной и не зависящей линейно от числа одновременных загрузок.
|
||||
|
||||
Методика:
|
||||
- перед прогоном реплики API перезапускаются, затем идёт прогрев одной загрузкой каждого типа;
|
||||
- внутри контейнеров каждые 50 мс читаются VmRSS процесса и `anon`/`file` из cgroup `memory.stat`, в конце — `VmHWM` (пиковый RSS) и `memory.peak`;
|
||||
- нагрузка — N потоков через LB, 3 раунда;
|
||||
- файлы синтетические: несжимаемый PNG 10 482 871 B и JPEG 6000×6000 (36 Мпикс) 8 051 216 B, поровну;
|
||||
- клиент и стенд на одном ноутбуке, по одному прогону на конфигурацию — иллюстрация, а не статистика.
|
||||
|
||||
| Конфигурация | Загрузок / объём | 201 | wall, p50/max | Пиковый RSS API (VmHWM), MiB | cgroup peak API, MiB | Пиковый RSS SeaweedFS |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| до: без лимита PUT, glibc по умолчанию, c=12 | 36 / 318 MiB | 36 | 6,2 с; 1,9/2,2 с | **178 / 189** (из 256) | 213 / 229 | не мерили |
|
||||
| до: S3 без лимитов буферов, 512 MiB, c=12 | 36 / 318 MiB | 36 | 5,9 с | 96 / 94 | 145 / 124 | 395 MiB; **в одном из прогонов — OOM-kill (exit 137), без restart S3 остался лежать** |
|
||||
| **после**, c=12 | 36 / 318 MiB | 36 | 5,2 с; 1,52/1,81 с | **93 / 97** | 133 / 139 | 484 MiB (лимит 768) |
|
||||
| **после**, c=20 | 60 / 530 MiB | 60 | 8,4 с; 2,23/2,82 с | **91 / 94** | 145 / 159 | 487 MiB |
|
||||
|
||||
Выводы:
|
||||
1. **Память API.** На простое RSS реплики ~50 MiB. Основную добавку давал S3 PUT: minio-py держит в памяти часть 5 MiB с копиями для подписи, ~20 MiB на загрузку. Ограничение PUT до 3 на реплику (тело уже на диске, остальные ждут в очереди) и `MALLOC_ARENA_MAX=2` снизили пик почти вдвое. Рост конкуренции с 12 до 20 пик **не увеличил** (93–97 → 91–94 MiB), а задержки выросли (p50 1,52 → 2,23 с) — избыток ждёт, а не занимает память. Гипотеза подтверждена в этих пределах.
|
||||
2. **File-память cgroup (cgroup peak − RSS ≈ 40–65 MiB)** — page cache временных файлов. Она вытесняема и OOM не вызывает.
|
||||
3. **SeaweedFS** после исправлений выходит на плато ~480 MiB одинаково при c=12 и c=20, OOM нет, `RestartCount 0`. OOM из прогона до исправления зафиксирован в `evidence/before-fix/s3-oom.txt`.
|
||||
|
||||
### Недоступность S3 (`student-tests/s3_outage.py`)
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Восстановление / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| `docker compose stop s3` | upload/download 503, текст и ready работают | сразу и через 5 с: upload 503 (14–18 мс), download 503 (10–11 мс), `Retry-After: 1`; сообщение 201; ready 200 | upload 201 через 20,1 с после `start` (старт SeaweedFS + выбор лидера) / 0 |
|
||||
| `docker compose pause s3` (S3 завис) | то же, без 500 и таймаутов LB | первый upload после паузы — 503 за 10,0 с (PUT 5 с + попытка компенсации 5 с); дальше S3Health знает об отказе: upload 503 за 13 мс, download 503 за 9–11 мс; сообщения 201 | upload 201 сразу после `unpause`; healthcheck S3 снова healthy через 5,2 с / 0 |
|
||||
| `make test-persistence` (рестарт db, s3, api, janitor, lb) | данные, сессия и файл сохраняются | PASS, все `StartedAt` новые | в пределах лимита теста / 0 |
|
||||
| `stop-one.sh` (SIGTERM загрузившей реплики) | download через другую | PASS, по каждой реплике | 3,3–3,7 с по метрике публичного теста / 0 |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- **Выдерживается:** остановка или падение одной API-реплики (в том числе посреди upload — остаток убирает janitor), рестарт всего стенда с volumes, временная недоступность или зависание S3 (вложения — 503, остальной API работает), обрыв клиента.
|
||||
- **Не выдерживается:** потеря volume `s3data` или `pgdata` (одна копия, без репликации и бэкапов); отказ PostgreSQL, единственного S3 или LB; потеря Docker-host. SeaweedFS запущен одним процессом без репликации (`replication 000`).
|
||||
- **Сразу после старта или рестарта SeaweedFS** запись готова не сразу (~10–20 с). Healthcheck S3 это учитывает, поэтому `up` и `restart.sh` запускают API только после готовности записи. Если перезапустить один S3 вручную, upload в это окно получат 503 (чтение работает раньше). Это честный отказ, а не зависание, но и не нулевое время восстановления.
|
||||
- **`docker compose up api` при нездоровом S3** (например, сразу после `pause`/`unpause`) пересоздаёт реплики и не запускает их: compose ждёт здоровья зависимости `s3-init → s3`. Переключать `FAULT_INJECTION` и пересоздавать API нужно с `--no-deps` (так в инструкции) или после восстановления S3; `s3_outage.py` в конце сам ждёт healthy S3.
|
||||
- **Компенсация при зависшем S3** удлиняет ответ до ~10 с (таймаут PUT + таймаут DELETE); это меньше таймаута LB 75 с.
|
||||
- **Grace 1 ч — компромисс:** брошенные объекты до часа занимают место; уменьшать его можно, пока он намного больше `UPLOAD_TIMEOUT_SECONDS` + таймаутов S3.
|
||||
- **«Missing»** (ready-строка без объекта) только сообщается в лог и отчёт janitor; автоматического восстановления нет (бэкапов нет).
|
||||
- **Ранний отказ дочитывает тело** до 20 MiB, в том числе для неаутентифицированных запросов. Это трафик, но не память (буфер 64 KiB), и он ограничен `maxconn` LB и таймаутом приёма.
|
||||
- **Права SeaweedFS грубее IAM S3:** `Write` = Put + Delete, поэтому у janitor есть и Put. Ключи статичны и меняются только перезапуском S3 с новым `s3_identities.json`.
|
||||
- **Ресурсы SeaweedFS:** ему нужно ~0,5 GiB RAM даже на учебном объёме; лимит 768 MiB подобран экспериментом на этой машине, а не расчётом.
|
||||
- **Хук `FAULT_INJECTION`** — учебный: при значении 1 любой аутентифицированный клиент может уронить реплику. В обычной конфигурации он выключен; в lab7 код хука стоит удалить.
|
||||
- **Следующие шаги:** stream PUT без буферизации части в памяти (другой клиент или `UNSIGNED-PAYLOAD`), presigned upload (трек 1), метрики janitor для lab6, при необходимости — replica SeaweedFS.
|
||||
|
||||
## Повторная проверка — 07.11.2026
|
||||
|
||||
Работа повторно развёрнута из чистого clone ветки (коммит `ace2bbd`, отдельный проект `COMPOSE_PROJECT_NAME=mtusi-lab4-fresh`, новые секреты из `init-secrets.sh`, пустые volumes). Холодный старт занял 34 с, bucket создан и приватен. Затем выполнены все команды раздела «Запуск». Найдено и исправлено:
|
||||
|
||||
1. **`make test-failover` сразу после `make test-persistence` падал**: первая загрузка получала 503. После рестарта SeaweedFS отвечал healthy (`/healthz` и регистрация volume-сервера), но запись ещё не работала, и `restart.sh` перезапускал API слишком рано. Исправлено: healthcheck S3 проверяет реальную запись; на старте реплики upload до 5 с ждёт первой успешной проверки S3, а не отвечает 503 мгновенно. После исправления persistence → failover прошли два раза подряд.
|
||||
2. **`stop-one.sh` работал только при имени проекта `mtusi-lab4`**. Исправлено: реплики берутся из `docker compose ps`.
|
||||
3. **После теста отказа S3 `docker compose up api` оставлял API не запущенным** (см. «Ограничения»). Исправлено: тест ждёт восстановления S3, команды переключения `FAULT_INJECTION` используют `--no-deps`.
|
||||
|
||||
После исправлений в чистом clone прошли:
|
||||
- `make check`, `make test`;
|
||||
- persistence и failover ×2;
|
||||
- failover вложений, 60 негативных сценариев, 21 проверка S3, повторный bootstrap;
|
||||
- отказ S3, эксперимент согласованности, замер памяти (c=12: 36/36, VmHWM 100/103 MiB);
|
||||
- регрессия lab3;
|
||||
- полный `docker compose down` → `up` с сохранёнными volumes (31 с) и smoke после него.
|
||||
|
||||
Временный стенд удалён. Все файлы `evidence/` перезаписаны прогоном на основном стенде с этим кодом. Обязательные `tests/` и `contracts/` не изменены.
|
||||
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
# Lab4: HAProxy -> API x N (по умолчанию 2) -> PostgreSQL (данные, сессии, метаданные вложений)
|
||||
# -> SeaweedFS S3 (байты вложений, приватный bucket)
|
||||
# Запуск: ./scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait
|
||||
name: mtusi-lab4
|
||||
|
||||
x-api-image: &api-image
|
||||
build:
|
||||
context: .
|
||||
args:
|
||||
APP_VERSION: ${APP_VERSION:-1}
|
||||
image: mtusi-messenger:lab4
|
||||
|
||||
x-db-env: &db-env
|
||||
POSTGRES_HOST: db
|
||||
POSTGRES_PORT: "5432"
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
|
||||
x-s3-env: &s3-env
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:8333}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_CONNECT_TIMEOUT_SECONDS: ${S3_CONNECT_TIMEOUT_SECONDS:-2}
|
||||
S3_READ_TIMEOUT_SECONDS: ${S3_READ_TIMEOUT_SECONDS:-5}
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16.4-alpine@sha256:5660c2cbfea50c7a9127d17dc4e48543eedd3d7a41a595a2dfa572471e37e64c
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets: [postgres_password]
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data # данные переживают перезапуск контейнера
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 512M}
|
||||
|
||||
# S3-совместимое хранилище. Один процесс `weed server`: master/volume/filer слушают
|
||||
# ТОЛЬКО 127.0.0.1 внутри контейнера (их HTTP API обходит авторизацию S3 и не должен
|
||||
# быть доступен даже из backend-сети), наружу контейнера — только S3 API :8333.
|
||||
# Встроенный IAM API, Iceberg и Lance выключены. Порты на хост не публикуются.
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.50@sha256:c2658820e763294a9e9de7b36c81e59b879e3459148351aee4e31a126ca64860
|
||||
command:
|
||||
- server
|
||||
- -dir=/data
|
||||
- -ip=127.0.0.1
|
||||
- -ip.bind=127.0.0.1
|
||||
- -master.volumeSizeLimitMB=1024
|
||||
# Один master: выборы raft-лидера после рестарта 2 с вместо 10 (иначе ~10–20 с чтения висят).
|
||||
- -master.electionTimeout=2s
|
||||
- -volume.preStopSeconds=2
|
||||
- -volume.max=0
|
||||
- -s3
|
||||
- -s3.ip.bind=0.0.0.0
|
||||
- -s3.port=8333
|
||||
- -s3.config=/run/secrets/s3_identities.json
|
||||
- -s3.iam=false
|
||||
- -s3.port.iceberg=0
|
||||
- -s3.port.lance=0
|
||||
# Память: по умолчанию буферы параллельных загрузок и кэши чтения не ограничены.
|
||||
# API пишет не более 2x3 PUT по 5 MiB одновременно — 64 MiB хватает с запасом.
|
||||
- -s3.concurrentUploadLimitMB=64
|
||||
- -filer.concurrentUploadLimitMB=64
|
||||
- -volume.concurrentUploadLimitMB=64
|
||||
- -s3.cacheCapacityMB=16
|
||||
- -s3.readerCacheSizeMB=32
|
||||
secrets: [s3_identities.json]
|
||||
environment:
|
||||
# Go-рантайм: сборщик мусора ужимает кучу до этого предела раньше, чем cgroup
|
||||
# убьёт процесс по OOM. Без него 12 параллельных загрузок по 10 MiB дали OOM-kill
|
||||
# при лимите 512 MiB (evidence/before-fix/s3-oom.txt). Лимит поднят до 768 MiB.
|
||||
GOMEMLIMIT: 512MiB
|
||||
volumes:
|
||||
- s3data:/data # объекты и метаданные filer
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
# Готов, когда S3 отвечает И реально работает ЗАПИСЬ: PUT маленького файла во внутренний
|
||||
# filer (путь /.healthcheck вне /buckets, через S3 не виден). После рестарта SeaweedFS
|
||||
# /healthz уже 200, а запись ещё 10–20 с висит (выбор raft-лидера, выдача volume);
|
||||
# без этой проверки restart.sh и depends_on стартовали API раньше готовности S3.
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8333/healthz && curl -sf -m 2 -X PUT --data-binary ok http://127.0.0.1:8888/.healthcheck/probe -o /dev/null"]
|
||||
interval: 5s
|
||||
start_interval: 1s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 768M}
|
||||
|
||||
# Однократный job миграций: выполняется до старта API и завершается (exit 0).
|
||||
migrate:
|
||||
<<: *api-image
|
||||
command: ["python", "/app/src/migrate.py"]
|
||||
environment:
|
||||
<<: *db-env
|
||||
secrets: [postgres_password]
|
||||
networks: [backend]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
# Однократный идемпотентный bootstrap bucket + проверка приватности. Единственный
|
||||
# потребитель admin-ключей S3.
|
||||
s3-init:
|
||||
<<: *api-image
|
||||
command: ["python", "/app/src/s3_bootstrap.py"]
|
||||
environment:
|
||||
<<: *s3-env
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_key
|
||||
secrets: [s3_admin_access_key, s3_admin_secret_key]
|
||||
networks: [backend]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
depends_on:
|
||||
s3: {condition: service_healthy}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
api:
|
||||
<<: *api-image
|
||||
# Без container_name и без ports: масштабируется `--scale api=N`, доступен только через LB.
|
||||
expose: ["8080"]
|
||||
environment:
|
||||
<<: [*db-env, *s3-env]
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
DB_POOL_SIZE: ${DB_POOL_SIZE:-10}
|
||||
DRAIN_SECONDS: ${DRAIN_SECONDS:-3}
|
||||
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-10}
|
||||
PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-2}
|
||||
PASSWORD_HASH_WAIT_SECONDS: ${PASSWORD_HASH_WAIT_SECONDS:-0.5}
|
||||
DB_HEALTH_INTERVAL_SECONDS: ${DB_HEALTH_INTERVAL_SECONDS:-1}
|
||||
READY_STALE_SECONDS: ${READY_STALE_SECONDS:-3}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_api_access_key
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_api_secret_key
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
UPLOAD_TIMEOUT_SECONDS: ${UPLOAD_TIMEOUT_SECONDS:-60}
|
||||
UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-8}
|
||||
DECODE_CONCURRENCY: ${DECODE_CONCURRENCY:-2}
|
||||
S3_PUT_CONCURRENCY: ${S3_PUT_CONCURRENCY:-3}
|
||||
FAULT_INJECTION: ${FAULT_INJECTION:-0}
|
||||
secrets: [postgres_password, s3_api_access_key, s3_api_secret_key]
|
||||
networks: [backend]
|
||||
restart: unless-stopped
|
||||
# DRAIN(3) + дообслуживание(<=10) < 20: Docker не убьёт процесс SIGKILL раньше.
|
||||
stop_grace_period: 20s
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
# Фоновая сверка БД <-> S3 (src/janitor.py): брошенные pending и объекты без строки
|
||||
# старше ATTACHMENT_GRACE_SECONDS удаляются; ready без объекта — только в отчёт.
|
||||
janitor:
|
||||
<<: *api-image
|
||||
command: ["python", "/app/src/janitor.py"]
|
||||
environment:
|
||||
<<: [*db-env, *s3-env]
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_janitor_access_key
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_janitor_secret_key
|
||||
ATTACHMENT_GRACE_SECONDS: ${ATTACHMENT_GRACE_SECONDS:-3600}
|
||||
JANITOR_INTERVAL_SECONDS: ${JANITOR_INTERVAL_SECONDS:-300}
|
||||
secrets: [postgres_password, s3_janitor_access_key, s3_janitor_secret_key]
|
||||
networks: [backend]
|
||||
# Живость цикла: heartbeat-файл обновляется не реже раза в 30 с.
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import os,sys,time; sys.exit(0 if time.time() - os.path.getmtime('/tmp/janitor.heartbeat') < 90 else 1)"]
|
||||
interval: 15s
|
||||
timeout: 3s
|
||||
retries: 2
|
||||
start_period: 20s
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-init: {condition: service_completed_successfully}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 128M}
|
||||
|
||||
lb:
|
||||
image: haproxy:3.0.5-alpine@sha256:43a2591a6a62a41dd22edb4452880e9c70de489fbd7c54ffb52d035cccbfe949
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
environment:
|
||||
LOGIN_RATE_LIMIT: ${LOGIN_RATE_LIMIT:-20}
|
||||
ports:
|
||||
- "127.0.0.1:${LB_PORT:-8080}:8080" # единственная публичная точка API
|
||||
- "127.0.0.1:8404:8404" # статистика HAProxy, только localhost
|
||||
networks: [frontend, backend]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "haproxy", "-c", "-q", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
depends_on:
|
||||
api: {condition: service_started}
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
# Инструмент проверки приватности bucket и прав ключей ВНЕ API (не часть стенда):
|
||||
# docker compose --profile tools run --rm s3-check
|
||||
# Получает ключи api и janitor (чтобы проверить их ограничения), но не admin.
|
||||
s3-check:
|
||||
<<: *api-image
|
||||
profiles: [tools]
|
||||
command: ["python", "/app/student-tests/s3_private_check.py"]
|
||||
environment:
|
||||
<<: *s3-env
|
||||
volumes:
|
||||
- ./student-tests:/app/student-tests:ro
|
||||
secrets: [s3_api_access_key, s3_api_secret_key, s3_janitor_access_key, s3_janitor_secret_key]
|
||||
networks: [backend]
|
||||
healthcheck: {disable: true}
|
||||
restart: "no"
|
||||
|
||||
# Каждый секрет подключён только к тем сервисам, которым он нужен.
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
s3_identities.json:
|
||||
file: ./secrets/s3_identities.json
|
||||
s3_admin_access_key:
|
||||
file: ./secrets/s3_admin_access_key
|
||||
s3_admin_secret_key:
|
||||
file: ./secrets/s3_admin_secret_key
|
||||
s3_api_access_key:
|
||||
file: ./secrets/s3_api_access_key
|
||||
s3_api_secret_key:
|
||||
file: ./secrets/s3_api_secret_key
|
||||
s3_janitor_access_key:
|
||||
file: ./secrets/s3_janitor_access_key
|
||||
s3_janitor_secret_key:
|
||||
file: ./secrets/s3_janitor_secret_key
|
||||
|
||||
networks:
|
||||
frontend: {}
|
||||
backend:
|
||||
internal: true # db, s3 и api недоступны извне, кроме как через LB
|
||||
|
||||
volumes:
|
||||
pgdata: {}
|
||||
s3data: {}
|
||||
@@ -0,0 +1,16 @@
|
||||
# 2026-11-07T08:32:11Z API containers: mounts and temp upload dir after all tests
|
||||
## mtusi-lab4-api-1
|
||||
Mounts: bind:/run/secrets/s3_api_secret_key bind:/run/secrets/postgres_password bind:/run/secrets/s3_api_access_key
|
||||
ls -la /tmp/uploads:
|
||||
total 12
|
||||
drwxrwxrwt 1 root root 4096 Nov 7 08:23 .
|
||||
drwxrwxrwt 1 root root 4096 Nov 7 08:23 ..
|
||||
files > 10 KB anywhere writable (excluding /proc,/sys,/usr,/run/secrets):
|
||||
## mtusi-lab4-api-2
|
||||
Mounts: bind:/run/secrets/postgres_password bind:/run/secrets/s3_api_access_key bind:/run/secrets/s3_api_secret_key
|
||||
ls -la /tmp/uploads:
|
||||
total 12
|
||||
drwxrwxrwt 1 root root 4096 Nov 7 08:23 .
|
||||
drwxrwxrwt 1 root root 4096 Nov 7 08:23 ..
|
||||
files > 10 KB anywhere writable (excluding /proc,/sys,/usr,/run/secrets):
|
||||
## upload buffering: tempfile.TemporaryFile -> O_TMPFILE (no directory entry), deleted on close or process death
|
||||
@@ -0,0 +1,73 @@
|
||||
{
|
||||
"replicas": [
|
||||
"3c9bca5b2595",
|
||||
"76cd26b71556"
|
||||
],
|
||||
"rounds": [
|
||||
{
|
||||
"uploaded_by": "3c9bca5b2595",
|
||||
"stopped": "3c9bca5b2595",
|
||||
"downloads": [
|
||||
{
|
||||
"instance": "76cd26b71556",
|
||||
"sha256_ok": true,
|
||||
"ms": 8.0
|
||||
},
|
||||
{
|
||||
"instance": "76cd26b71556",
|
||||
"sha256_ok": true,
|
||||
"ms": 5.7
|
||||
},
|
||||
{
|
||||
"instance": "76cd26b71556",
|
||||
"sha256_ok": true,
|
||||
"ms": 6.9
|
||||
},
|
||||
{
|
||||
"instance": "76cd26b71556",
|
||||
"sha256_ok": true,
|
||||
"ms": 22.4
|
||||
},
|
||||
{
|
||||
"instance": "76cd26b71556",
|
||||
"sha256_ok": true,
|
||||
"ms": 5.8
|
||||
}
|
||||
],
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"uploaded_by": "76cd26b71556",
|
||||
"stopped": "76cd26b71556",
|
||||
"downloads": [
|
||||
{
|
||||
"instance": "3c9bca5b2595",
|
||||
"sha256_ok": true,
|
||||
"ms": 8.8
|
||||
},
|
||||
{
|
||||
"instance": "3c9bca5b2595",
|
||||
"sha256_ok": true,
|
||||
"ms": 5.5
|
||||
},
|
||||
{
|
||||
"instance": "3c9bca5b2595",
|
||||
"sha256_ok": true,
|
||||
"ms": 5.9
|
||||
},
|
||||
{
|
||||
"instance": "3c9bca5b2595",
|
||||
"sha256_ok": true,
|
||||
"ms": 6.9
|
||||
},
|
||||
{
|
||||
"instance": "3c9bca5b2595",
|
||||
"sha256_ok": true,
|
||||
"ms": 4.5
|
||||
}
|
||||
],
|
||||
"pass": true
|
||||
}
|
||||
],
|
||||
"pass": true
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{"uploaded_by": "3c9bca5b2595", "stopped": "3c9bca5b2595", "downloads": [{"instance": "76cd26b71556", "sha256_ok": true, "ms": 8.0}, {"instance": "76cd26b71556", "sha256_ok": true, "ms": 5.7}, {"instance": "76cd26b71556", "sha256_ok": true, "ms": 6.9}, {"instance": "76cd26b71556", "sha256_ok": true, "ms": 22.4}, {"instance": "76cd26b71556", "sha256_ok": true, "ms": 5.8}], "pass": true}
|
||||
{"uploaded_by": "76cd26b71556", "stopped": "76cd26b71556", "downloads": [{"instance": "3c9bca5b2595", "sha256_ok": true, "ms": 8.8}, {"instance": "3c9bca5b2595", "sha256_ok": true, "ms": 5.5}, {"instance": "3c9bca5b2595", "sha256_ok": true, "ms": 5.9}, {"instance": "3c9bca5b2595", "sha256_ok": true, "ms": 6.9}, {"instance": "3c9bca5b2595", "sha256_ok": true, "ms": 4.5}], "pass": true}
|
||||
{"pass": true, "rounds": 2}
|
||||
exit=0
|
||||
@@ -0,0 +1,430 @@
|
||||
{
|
||||
"summary": {
|
||||
"cases": 60,
|
||||
"failed": 0,
|
||||
"server_errors_5xx": 0,
|
||||
"pass": true
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"case": "valid PNG fixture",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "valid JPEG",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "unicode filename",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG near 10 MiB limit (10482871 B)",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "too large: 10 MiB + 1 B",
|
||||
"expected": 413,
|
||||
"status": 413,
|
||||
"error_code": "payload_too_large",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "pixel bomb header 100000x100000",
|
||||
"expected": 413,
|
||||
"status": 413,
|
||||
"error_code": "payload_too_large",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG 7000x6000 = 42 Mpx (> 40 Mpx)",
|
||||
"expected": 413,
|
||||
"status": 413,
|
||||
"error_code": "payload_too_large",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "zlib bomb: 100x100 header, 50 MB inflated",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "corrupted PNG (byte flipped, bad CRC)",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "truncated PNG",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG without IEND",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG with appended ZIP (polyglot)",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "truncated JPEG",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "JPEG header only",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "empty body",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "JPEG bytes declared image/png",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG bytes declared image/jpeg",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "text declared image/png",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "GIF declared image/png",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG declared text/html",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "PNG declared image/svg+xml",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "multipart/form-data instead of raw",
|
||||
"expected": 415,
|
||||
"status": 415,
|
||||
"error_code": "unsupported_media_type",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: ../etc/passwd",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: slash",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: backslash",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: NUL",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: newline",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: bidi override U+202E",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: ..",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: empty",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: whitespace only",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: 256 code points",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: missing filename",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: filename twice",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "filename: invalid UTF-8",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "eve uploads to her own chat",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "non-member uploads to alice chat",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "upload without session",
|
||||
"expected": 401,
|
||||
"status": 401,
|
||||
"error_code": "unauthorized",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "upload to unknown chat",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "foreign attachment metadata",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "foreign attachment content",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "eve reads alice attachment",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "message with foreign attachment_id",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "message mixing own and foreign ids",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "attachment of OTHER chat of the same user",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "unknown attachment_id",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "malformed attachment_id",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "duplicate attachment_ids",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "11 attachment_ids",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "attachment_ids not a list",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "empty text without attachments",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "empty text with attachment (bob links alice's file)",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "idempotent send with attachments",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "same key, same body (key order changed)",
|
||||
"expected": 201,
|
||||
"status": 201,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "same key, different attachment_ids -> 409",
|
||||
"expected": 409,
|
||||
"status": 409,
|
||||
"error_code": "conflict",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "variant=thumbnail (no variants in lab4)",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "variant=bogus",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "variant=original",
|
||||
"expected": 200,
|
||||
"status": 200,
|
||||
"error_code": null,
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "malformed attachment id in path",
|
||||
"expected": 400,
|
||||
"status": 400,
|
||||
"error_code": "invalid_request",
|
||||
"pass": true
|
||||
},
|
||||
{
|
||||
"case": "unknown attachment id",
|
||||
"expected": 404,
|
||||
"status": 404,
|
||||
"error_code": "not_found",
|
||||
"pass": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
PASS valid PNG fixture -> 201
|
||||
PASS valid JPEG -> 201
|
||||
PASS unicode filename -> 201
|
||||
PASS PNG near 10 MiB limit (10482871 B) -> 201
|
||||
PASS too large: 10 MiB + 1 B -> 413 payload_too_large
|
||||
PASS pixel bomb header 100000x100000 -> 413 payload_too_large
|
||||
PASS PNG 7000x6000 = 42 Mpx (> 40 Mpx) -> 413 payload_too_large
|
||||
PASS zlib bomb: 100x100 header, 50 MB inflated -> 415 unsupported_media_type
|
||||
PASS corrupted PNG (byte flipped, bad CRC) -> 415 unsupported_media_type
|
||||
PASS truncated PNG -> 415 unsupported_media_type
|
||||
PASS PNG without IEND -> 415 unsupported_media_type
|
||||
PASS PNG with appended ZIP (polyglot) -> 415 unsupported_media_type
|
||||
PASS truncated JPEG -> 415 unsupported_media_type
|
||||
PASS JPEG header only -> 415 unsupported_media_type
|
||||
PASS empty body -> 415 unsupported_media_type
|
||||
PASS JPEG bytes declared image/png -> 415 unsupported_media_type
|
||||
PASS PNG bytes declared image/jpeg -> 415 unsupported_media_type
|
||||
PASS text declared image/png -> 415 unsupported_media_type
|
||||
PASS GIF declared image/png -> 415 unsupported_media_type
|
||||
PASS PNG declared text/html -> 415 unsupported_media_type
|
||||
PASS PNG declared image/svg+xml -> 415 unsupported_media_type
|
||||
PASS multipart/form-data instead of raw -> 415 unsupported_media_type
|
||||
PASS filename: ../etc/passwd -> 400 invalid_request
|
||||
PASS filename: slash -> 400 invalid_request
|
||||
PASS filename: backslash -> 400 invalid_request
|
||||
PASS filename: NUL -> 400 invalid_request
|
||||
PASS filename: newline -> 400 invalid_request
|
||||
PASS filename: bidi override U+202E -> 400 invalid_request
|
||||
PASS filename: .. -> 400 invalid_request
|
||||
PASS filename: empty -> 400 invalid_request
|
||||
PASS filename: whitespace only -> 400 invalid_request
|
||||
PASS filename: 256 code points -> 400 invalid_request
|
||||
PASS filename: missing filename -> 400 invalid_request
|
||||
PASS filename: filename twice -> 400 invalid_request
|
||||
PASS filename: invalid UTF-8 -> 400 invalid_request
|
||||
PASS eve uploads to her own chat -> 201
|
||||
PASS non-member uploads to alice chat -> 404 not_found
|
||||
PASS upload without session -> 401 unauthorized
|
||||
PASS upload to unknown chat -> 404 not_found
|
||||
PASS foreign attachment metadata -> 404 not_found
|
||||
PASS foreign attachment content -> 404 not_found
|
||||
PASS eve reads alice attachment -> 404 not_found
|
||||
PASS message with foreign attachment_id -> 404 not_found
|
||||
PASS message mixing own and foreign ids -> 404 not_found
|
||||
PASS attachment of OTHER chat of the same user -> 404 not_found
|
||||
PASS unknown attachment_id -> 404 not_found
|
||||
PASS malformed attachment_id -> 400 invalid_request
|
||||
PASS duplicate attachment_ids -> 400 invalid_request
|
||||
PASS 11 attachment_ids -> 400 invalid_request
|
||||
PASS attachment_ids not a list -> 400 invalid_request
|
||||
PASS empty text without attachments -> 400 invalid_request
|
||||
PASS empty text with attachment (bob links alice's file) -> 201
|
||||
PASS idempotent send with attachments -> 201
|
||||
PASS same key, same body (key order changed) -> 201
|
||||
PASS same key, different attachment_ids -> 409 -> 409 conflict
|
||||
PASS variant=thumbnail (no variants in lab4) -> 404 not_found
|
||||
PASS variant=bogus -> 400 invalid_request
|
||||
PASS variant=original -> 200
|
||||
PASS malformed attachment id in path -> 400 invalid_request
|
||||
PASS unknown attachment id -> 404 not_found
|
||||
{"cases": 60, "failed": 0, "server_errors_5xx": 0, "pass": true}
|
||||
@@ -0,0 +1,7 @@
|
||||
# 2026-11-06T22:27:39Z upload_memory.py --concurrency 12 --rounds 3, s3 limit 512M, no GOMEMLIMIT, no restart policy
|
||||
container=/mtusi-lab4-s3-1 OOMKilled=true ExitCode=137 FinishedAt=2026-11-06T22:26:33.807520926Z RestartPolicy=no
|
||||
## api logs at that moment
|
||||
api-2 | 2026-11-06 22:26:33,809 WARNING s3 health: failing (MaxRetryError)
|
||||
api-1 | 2026-11-06 22:26:33,806 WARNING s3 health: failing (MaxRetryError)
|
||||
api-1 | 2026-11-06 22:26:48,084 WARNING s3 health: failing (MaxRetryError)
|
||||
api-2 | 2026-11-06 22:26:48,049 WARNING s3 health: failing (MaxRetryError)
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"concurrency": 12,
|
||||
"rounds": 3,
|
||||
"files": [
|
||||
{
|
||||
"type": "image/png",
|
||||
"bytes": 10482871,
|
||||
"sha256": "a9d76b9ed9660de7"
|
||||
},
|
||||
{
|
||||
"type": "image/jpeg",
|
||||
"bytes": 8051216,
|
||||
"sha256": "c49ef6d9ef42362e"
|
||||
}
|
||||
],
|
||||
"uploads": 36,
|
||||
"status_counts": {
|
||||
"201": 36
|
||||
},
|
||||
"megabytes_uploaded_ok": 318.2,
|
||||
"wall_s": 5.9,
|
||||
"latency_s_p50_max": [
|
||||
1.79,
|
||||
2.1
|
||||
],
|
||||
"replicas": {
|
||||
"0a9e8191e9fe": {
|
||||
"rss_mib": 54,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 131,
|
||||
"peak_rss_mib_sampled": 96.0,
|
||||
"peak_anon_mib": 85.1,
|
||||
"peak_file_cache_mib": 55.4,
|
||||
"vmhwm_mib": 96,
|
||||
"cgroup_memory_peak_mib": 145.0,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 18
|
||||
},
|
||||
"0353e8a0b29e": {
|
||||
"rss_mib": 50,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 128,
|
||||
"peak_rss_mib_sampled": 94.8,
|
||||
"peak_anon_mib": 77.7,
|
||||
"peak_file_cache_mib": 53.1,
|
||||
"vmhwm_mib": 94,
|
||||
"cgroup_memory_peak_mib": 124.1,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 18
|
||||
}
|
||||
},
|
||||
"s3": {
|
||||
"rss_mib": 365,
|
||||
"oom_killed": "false",
|
||||
"peak_rss_mib_sampled": 395.3,
|
||||
"peak_anon_mib": 314.7,
|
||||
"restarts": 0,
|
||||
"oom_killed_after": "false",
|
||||
"memory_limit_mib": 512
|
||||
},
|
||||
"oom_kills": [
|
||||
"false",
|
||||
"false"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"concurrency": 12,
|
||||
"rounds": 3,
|
||||
"files": [
|
||||
{
|
||||
"type": "image/png",
|
||||
"bytes": 10482871,
|
||||
"sha256": "4e9ec1dec161b0bd"
|
||||
},
|
||||
{
|
||||
"type": "image/jpeg",
|
||||
"bytes": 8051216,
|
||||
"sha256": "c49ef6d9ef42362e"
|
||||
}
|
||||
],
|
||||
"uploads": 36,
|
||||
"status_counts": {
|
||||
"201": 36
|
||||
},
|
||||
"megabytes_uploaded_ok": 318.2,
|
||||
"wall_s": 6.2,
|
||||
"latency_s_p50_max": [
|
||||
1.9,
|
||||
2.18
|
||||
],
|
||||
"replicas": {
|
||||
"998f5e4e3c8c": {
|
||||
"rss_mib": 51,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 132,
|
||||
"peak_rss_mib_sampled": 178.2,
|
||||
"peak_anon_mib": 160.2,
|
||||
"peak_file_cache_mib": 55.6,
|
||||
"vmhwm_mib": 178,
|
||||
"cgroup_memory_peak_mib": 212.6,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 18
|
||||
},
|
||||
"7f7d9ec27329": {
|
||||
"rss_mib": 55,
|
||||
"hwm_mib_after_warmup": 83,
|
||||
"samples": 134,
|
||||
"peak_rss_mib_sampled": 189.5,
|
||||
"peak_anon_mib": 171.1,
|
||||
"peak_file_cache_mib": 55.5,
|
||||
"vmhwm_mib": 189,
|
||||
"cgroup_memory_peak_mib": 229.0,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 18
|
||||
}
|
||||
},
|
||||
"oom_kills": [
|
||||
"false",
|
||||
"false"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"concurrency": 20,
|
||||
"rounds": 3,
|
||||
"files": [
|
||||
{
|
||||
"type": "image/png",
|
||||
"bytes": 10482871,
|
||||
"sha256": "471292d26a5129a1"
|
||||
},
|
||||
{
|
||||
"type": "image/jpeg",
|
||||
"bytes": 8051216,
|
||||
"sha256": "c49ef6d9ef42362e"
|
||||
}
|
||||
],
|
||||
"uploads": 60,
|
||||
"status_counts": {
|
||||
"201": 60
|
||||
},
|
||||
"megabytes_uploaded_ok": 530.3,
|
||||
"wall_s": 9.3,
|
||||
"latency_s_p50_max": [
|
||||
2.42,
|
||||
3.44
|
||||
],
|
||||
"replicas": {
|
||||
"0a9e8191e9fe": {
|
||||
"rss_mib": 50,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 181,
|
||||
"peak_rss_mib_sampled": 94.8,
|
||||
"peak_anon_mib": 83.3,
|
||||
"peak_file_cache_mib": 77.7,
|
||||
"vmhwm_mib": 94,
|
||||
"cgroup_memory_peak_mib": 161.0,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 30
|
||||
},
|
||||
"0353e8a0b29e": {
|
||||
"rss_mib": 54,
|
||||
"hwm_mib_after_warmup": 78,
|
||||
"samples": 174,
|
||||
"peak_rss_mib_sampled": 102.0,
|
||||
"peak_anon_mib": 95.7,
|
||||
"peak_file_cache_mib": 73.0,
|
||||
"vmhwm_mib": 101,
|
||||
"cgroup_memory_peak_mib": 156.7,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 30
|
||||
}
|
||||
},
|
||||
"s3": {
|
||||
"rss_mib": 373,
|
||||
"oom_killed": "false",
|
||||
"peak_rss_mib_sampled": 442.3,
|
||||
"peak_anon_mib": 362.4,
|
||||
"restarts": 0,
|
||||
"oom_killed_after": "false",
|
||||
"memory_limit_mib": 512
|
||||
},
|
||||
"oom_kills": [
|
||||
"false",
|
||||
"false"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# 2026-11-07T08:24:34Z make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
exit=0
|
||||
# 2026-11-07T08:24:34Z docker compose config --quiet
|
||||
exit=0
|
||||
@@ -0,0 +1,209 @@
|
||||
{
|
||||
"pass": true,
|
||||
"steps": [
|
||||
{
|
||||
"step": "baseline janitor dry-run",
|
||||
"t": 1794040130.0,
|
||||
"report": {
|
||||
"dry_run": true,
|
||||
"grace_seconds": 3600,
|
||||
"rows_by_status": {
|
||||
"pending": 1,
|
||||
"ready": 467
|
||||
},
|
||||
"objects_total": 465,
|
||||
"abandoned_pending": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 3,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 100.5
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "control + victim uploaded (ready)",
|
||||
"t": 1794040130.0,
|
||||
"control": "8ef93cb0-8d87-4bee-9c98-c0b3295e8b28",
|
||||
"victim": "59255c3f-edc6-4e6f-861f-fc02a57e11e1"
|
||||
},
|
||||
{
|
||||
"step": "db-fail-after-s3-put -> compensation",
|
||||
"t": 1794040133.2,
|
||||
"status": 503,
|
||||
"report": {
|
||||
"dry_run": true,
|
||||
"grace_seconds": 3600,
|
||||
"rows_by_status": {
|
||||
"pending": 1,
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 467,
|
||||
"abandoned_pending": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 3,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 99.1
|
||||
},
|
||||
"leftover_pending": 0,
|
||||
"leftover_objects": 0
|
||||
},
|
||||
{
|
||||
"step": "crash-after-s3-put",
|
||||
"t": 1794040133.2,
|
||||
"client_saw": "Failure"
|
||||
},
|
||||
{
|
||||
"step": "crash-after-s3-put",
|
||||
"t": 1794040136.4,
|
||||
"client_saw": "Failure"
|
||||
},
|
||||
{
|
||||
"step": "crash-after-pending",
|
||||
"t": 1794040145.1,
|
||||
"client_saw": "Failure"
|
||||
},
|
||||
{
|
||||
"step": "client aborted upload at 1 of 5 MiB",
|
||||
"t": 1794040152.9,
|
||||
"report": {
|
||||
"dry_run": true,
|
||||
"grace_seconds": 3600,
|
||||
"rows_by_status": {
|
||||
"pending": 4,
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 469,
|
||||
"abandoned_pending": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 3,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 24.9
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "pending rows left by crashes",
|
||||
"t": 1794040153.1,
|
||||
"pending": 3
|
||||
},
|
||||
{
|
||||
"step": "orphan injected: pending row deleted, object kept",
|
||||
"t": 1794040153.2,
|
||||
"row": "59726e36-b9bd-478c-8012-1d004f7cc7a5"
|
||||
},
|
||||
{
|
||||
"step": "missing injected: victim object deleted in S3",
|
||||
"t": 1794040153.9,
|
||||
"download_status": 503
|
||||
},
|
||||
{
|
||||
"step": "janitor grace=3600 (all fresh): dry-run",
|
||||
"t": 1794040160.3,
|
||||
"report": {
|
||||
"dry_run": true,
|
||||
"grace_seconds": 3600,
|
||||
"rows_by_status": {
|
||||
"pending": 3,
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 468,
|
||||
"abandoned_pending": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 4,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 104.3
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "janitor grace=3600 (all fresh): real run deletes nothing",
|
||||
"t": 1794040160.3,
|
||||
"report": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 3600,
|
||||
"rows_by_status": {
|
||||
"pending": 3,
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 468,
|
||||
"abandoned_pending": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 4,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 101.2
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "after grace: dry-run",
|
||||
"t": 1794040185.3,
|
||||
"report": {
|
||||
"dry_run": true,
|
||||
"grace_seconds": 20,
|
||||
"rows_by_status": {
|
||||
"pending": 3,
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 468,
|
||||
"abandoned_pending": 3,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 4,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 103.0
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "after grace: real run",
|
||||
"t": 1794040188.5,
|
||||
"report": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 20,
|
||||
"rows_by_status": {
|
||||
"pending": 3,
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 466,
|
||||
"abandoned_pending": 3,
|
||||
"orphan_objects": 1,
|
||||
"missing_objects": 4,
|
||||
"deleted_objects": 4,
|
||||
"deleted_rows": 3,
|
||||
"errors": 0,
|
||||
"duration_ms": 180.4
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "after grace: repeated run (idempotent)",
|
||||
"t": 1794040191.2,
|
||||
"report": {
|
||||
"dry_run": false,
|
||||
"grace_seconds": 20,
|
||||
"rows_by_status": {
|
||||
"ready": 469
|
||||
},
|
||||
"objects_total": 465,
|
||||
"abandoned_pending": 0,
|
||||
"orphan_objects": 0,
|
||||
"missing_objects": 4,
|
||||
"deleted_objects": 0,
|
||||
"deleted_rows": 0,
|
||||
"errors": 0,
|
||||
"duration_ms": 99.3
|
||||
}
|
||||
},
|
||||
{
|
||||
"step": "control attachment still intact",
|
||||
"t": 1794040191.4,
|
||||
"sha256_ok": true,
|
||||
"pending_left": 0
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{"step": "baseline janitor dry-run", "t": 1794040130.0, "report": {"dry_run": true, "grace_seconds": 3600, "rows_by_status": {"pending": 1, "ready": 467}, "objects_total": 465, "abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 3, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 100.5}}
|
||||
{"step": "control + victim uploaded (ready)", "t": 1794040130.0, "control": "8ef93cb0-8d87-4bee-9c98-c0b3295e8b28", "victim": "59255c3f-edc6-4e6f-861f-fc02a57e11e1"}
|
||||
{"step": "db-fail-after-s3-put -> compensation", "t": 1794040133.2, "status": 503, "report": {"dry_run": true, "grace_seconds": 3600, "rows_by_status": {"pending": 1, "ready": 469}, "objects_total": 467, "abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 3, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 99.1}, "leftover_pending": 0, "leftover_objects": 0}
|
||||
{"step": "crash-after-s3-put", "t": 1794040133.2, "client_saw": "Failure"}
|
||||
{"step": "crash-after-s3-put", "t": 1794040136.4, "client_saw": "Failure"}
|
||||
{"step": "crash-after-pending", "t": 1794040145.1, "client_saw": "Failure"}
|
||||
{"step": "client aborted upload at 1 of 5 MiB", "t": 1794040152.9, "report": {"dry_run": true, "grace_seconds": 3600, "rows_by_status": {"pending": 4, "ready": 469}, "objects_total": 469, "abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 3, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 24.9}}
|
||||
{"step": "pending rows left by crashes", "t": 1794040153.1, "pending": 3}
|
||||
{"step": "orphan injected: pending row deleted, object kept", "t": 1794040153.2, "row": "59726e36-b9bd-478c-8012-1d004f7cc7a5"}
|
||||
{"step": "missing injected: victim object deleted in S3", "t": 1794040153.9, "download_status": 503}
|
||||
{"step": "janitor grace=3600 (all fresh): dry-run", "t": 1794040160.3, "report": {"dry_run": true, "grace_seconds": 3600, "rows_by_status": {"pending": 3, "ready": 469}, "objects_total": 468, "abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 4, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 104.3}}
|
||||
{"step": "janitor grace=3600 (all fresh): real run deletes nothing", "t": 1794040160.3, "report": {"dry_run": false, "grace_seconds": 3600, "rows_by_status": {"pending": 3, "ready": 469}, "objects_total": 468, "abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 4, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 101.2}}
|
||||
{"step": "after grace: dry-run", "t": 1794040185.3, "report": {"dry_run": true, "grace_seconds": 20, "rows_by_status": {"pending": 3, "ready": 469}, "objects_total": 468, "abandoned_pending": 3, "orphan_objects": 1, "missing_objects": 4, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 103.0}}
|
||||
{"step": "after grace: real run", "t": 1794040188.5, "report": {"dry_run": false, "grace_seconds": 20, "rows_by_status": {"pending": 3, "ready": 469}, "objects_total": 466, "abandoned_pending": 3, "orphan_objects": 1, "missing_objects": 4, "deleted_objects": 4, "deleted_rows": 3, "errors": 0, "duration_ms": 180.4}}
|
||||
{"step": "after grace: repeated run (idempotent)", "t": 1794040191.2, "report": {"dry_run": false, "grace_seconds": 20, "rows_by_status": {"ready": 469}, "objects_total": 465, "abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 4, "deleted_objects": 0, "deleted_rows": 0, "errors": 0, "duration_ms": 99.3}}
|
||||
{"step": "control attachment still intact", "t": 1794040191.4, "sha256_ok": true, "pending_left": 0}
|
||||
{"pass": true}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"rounds": 10,
|
||||
"parallel_per_burst": 16,
|
||||
"requests_total": 320,
|
||||
"status_counts": {
|
||||
"same_body": {
|
||||
"201": 160
|
||||
},
|
||||
"conflicting_body": {
|
||||
"409": 80,
|
||||
"201": 80
|
||||
}
|
||||
},
|
||||
"replicas_answered": 2,
|
||||
"requests_per_replica": [
|
||||
80,
|
||||
80
|
||||
],
|
||||
"messages_in_history": 20,
|
||||
"expected_messages": 20,
|
||||
"duplicates": 0,
|
||||
"problems": []
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# 2026-11-07T08:30:54Z cursor_validation
|
||||
PASS: 6 cursor date boundary checks; invalid dates return 400.
|
||||
# 2026-11-07T08:30:55Z idempotency_concurrency --rounds 10 --parallel 16
|
||||
"problems": []
|
||||
}
|
||||
PASS
|
||||
@@ -0,0 +1,54 @@
|
||||
# 2026-11-07T08:24:37Z round 1: make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
## before
|
||||
mtusi-lab4-api-1 StartedAt=2026-11-07T08:24:09.858075054Z
|
||||
mtusi-lab4-api-2 StartedAt=2026-11-07T08:24:09.791252554Z
|
||||
mtusi-lab4-db-1 StartedAt=2026-11-07T08:23:50.523803795Z
|
||||
mtusi-lab4-janitor-1 StartedAt=2026-11-07T08:24:09.793362971Z
|
||||
mtusi-lab4-lb-1 StartedAt=2026-11-07T08:24:09.948012971Z
|
||||
mtusi-lab4-s3-1 StartedAt=2026-11-07T08:23:50.522934587Z
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
## after
|
||||
mtusi-lab4-api-1 StartedAt=2026-11-07T08:25:18.150425752Z
|
||||
mtusi-lab4-api-2 StartedAt=2026-11-07T08:25:18.130956294Z
|
||||
mtusi-lab4-db-1 StartedAt=2026-11-07T08:24:38.899196554Z
|
||||
mtusi-lab4-janitor-1 StartedAt=2026-11-07T08:25:25.061171964Z
|
||||
mtusi-lab4-lb-1 StartedAt=2026-11-07T08:25:15.229845459Z
|
||||
mtusi-lab4-s3-1 StartedAt=2026-11-07T08:24:56.087874506Z
|
||||
# 2026-11-07T08:25:25Z round 1: make test-failover ACTION_SCRIPT=scripts/stop-one.sh (сразу после persistence)
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 129, "failed_attempts": 0, "first_recovery_seconds": 3.723}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
mtusi-lab4-api-1 Up 22 seconds (healthy)
|
||||
mtusi-lab4-api-2 Exited (0) 11 seconds ago
|
||||
# 2026-11-07T08:25:50Z round 2: make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
## before
|
||||
mtusi-lab4-api-1 StartedAt=2026-11-07T08:25:18.150425752Z
|
||||
mtusi-lab4-api-2 StartedAt=2026-11-07T08:25:41.189426555Z
|
||||
mtusi-lab4-db-1 StartedAt=2026-11-07T08:24:38.899196554Z
|
||||
mtusi-lab4-janitor-1 StartedAt=2026-11-07T08:25:25.061171964Z
|
||||
mtusi-lab4-lb-1 StartedAt=2026-11-07T08:25:15.229845459Z
|
||||
mtusi-lab4-s3-1 StartedAt=2026-11-07T08:24:56.087874506Z
|
||||
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
## after
|
||||
mtusi-lab4-api-1 StartedAt=2026-11-07T08:26:31.35367805Z
|
||||
mtusi-lab4-api-2 StartedAt=2026-11-07T08:26:31.310593342Z
|
||||
mtusi-lab4-db-1 StartedAt=2026-11-07T08:25:51.588460754Z
|
||||
mtusi-lab4-janitor-1 StartedAt=2026-11-07T08:26:37.94729322Z
|
||||
mtusi-lab4-lb-1 StartedAt=2026-11-07T08:26:28.08777384Z
|
||||
mtusi-lab4-s3-1 StartedAt=2026-11-07T08:26:09.003885512Z
|
||||
# 2026-11-07T08:26:38Z round 2: make test-failover ACTION_SCRIPT=scripts/stop-one.sh (сразу после persistence)
|
||||
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8080"
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 128, "failed_attempts": 0, "first_recovery_seconds": 3.347}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
mtusi-lab4-api-1 Up 22 seconds (healthy)
|
||||
mtusi-lab4-api-2 Exited (0) 11 seconds ago
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-07T08:24:35Z s3-init run twice (idempotency)
|
||||
{"bucket": "messenger-attachments", "created": false, "already_existed": true, "anonymous_http_status": {"anonymous_get_object": 403, "anonymous_list_bucket": 403}, "private": true}
|
||||
exit=0
|
||||
{"bucket": "messenger-attachments", "created": false, "already_existed": true, "anonymous_http_status": {"anonymous_get_object": 403, "anonymous_list_bucket": 403}, "private": true}
|
||||
exit=0
|
||||
@@ -0,0 +1,163 @@
|
||||
{
|
||||
"pass": true,
|
||||
"phases": [
|
||||
{
|
||||
"phase": "baseline",
|
||||
"probe": {
|
||||
"upload": {
|
||||
"status": 201,
|
||||
"ms": 6,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"download": {
|
||||
"status": 200,
|
||||
"ms": 3,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"text_message": {
|
||||
"status": 201,
|
||||
"ms": 3,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"ready": {
|
||||
"status": 200,
|
||||
"ms": 1,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"phase": "immediately after `stop s3` (S3Health not yet stale)",
|
||||
"probe": {
|
||||
"upload": {
|
||||
"status": 503,
|
||||
"ms": 18,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"download": {
|
||||
"status": 503,
|
||||
"ms": 10,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"text_message": {
|
||||
"status": 201,
|
||||
"ms": 9,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"ready": {
|
||||
"status": 200,
|
||||
"ms": 3,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"phase": "S3 down for 5 s (`stop s3`)",
|
||||
"probe": {
|
||||
"upload": {
|
||||
"status": 503,
|
||||
"ms": 14,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"download": {
|
||||
"status": 503,
|
||||
"ms": 11,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"text_message": {
|
||||
"status": 201,
|
||||
"ms": 12,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"ready": {
|
||||
"status": 200,
|
||||
"ms": 2,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"phase": "recovery after `start s3`",
|
||||
"upload_201_after_s": 20.1
|
||||
},
|
||||
{
|
||||
"phase": "immediately after `pause s3` (S3Health not yet stale)",
|
||||
"probe": {
|
||||
"upload": {
|
||||
"status": 503,
|
||||
"ms": 10032,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"download": {
|
||||
"status": 503,
|
||||
"ms": 11,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"text_message": {
|
||||
"status": 201,
|
||||
"ms": 15,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"ready": {
|
||||
"status": 200,
|
||||
"ms": 4,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"phase": "S3 down for 5 s (`pause s3`)",
|
||||
"probe": {
|
||||
"upload": {
|
||||
"status": 503,
|
||||
"ms": 13,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"download": {
|
||||
"status": 503,
|
||||
"ms": 9,
|
||||
"code": "unavailable",
|
||||
"retry_after": "1"
|
||||
},
|
||||
"text_message": {
|
||||
"status": 201,
|
||||
"ms": 14,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
},
|
||||
"ready": {
|
||||
"status": 200,
|
||||
"ms": 3,
|
||||
"code": null,
|
||||
"retry_after": null
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"phase": "recovery after `unpause s3`",
|
||||
"upload_201_after_s": 0.0
|
||||
},
|
||||
{
|
||||
"phase": "s3 healthcheck healthy again",
|
||||
"after_s": 5.2,
|
||||
"status": "healthy"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{"phase": "baseline", "probe": {"upload": {"status": 201, "ms": 6, "code": null, "retry_after": null}, "download": {"status": 200, "ms": 3, "code": null, "retry_after": null}, "text_message": {"status": 201, "ms": 3, "code": null, "retry_after": null}, "ready": {"status": 200, "ms": 1, "code": null, "retry_after": null}}}
|
||||
{"phase": "immediately after `stop s3` (S3Health not yet stale)", "probe": {"upload": {"status": 503, "ms": 18, "code": "unavailable", "retry_after": "1"}, "download": {"status": 503, "ms": 10, "code": "unavailable", "retry_after": "1"}, "text_message": {"status": 201, "ms": 9, "code": null, "retry_after": null}, "ready": {"status": 200, "ms": 3, "code": null, "retry_after": null}}}
|
||||
{"phase": "S3 down for 5 s (`stop s3`)", "probe": {"upload": {"status": 503, "ms": 14, "code": "unavailable", "retry_after": "1"}, "download": {"status": 503, "ms": 11, "code": "unavailable", "retry_after": "1"}, "text_message": {"status": 201, "ms": 12, "code": null, "retry_after": null}, "ready": {"status": 200, "ms": 2, "code": null, "retry_after": null}}}
|
||||
{"phase": "recovery after `start s3`", "upload_201_after_s": 20.1}
|
||||
{"phase": "immediately after `pause s3` (S3Health not yet stale)", "probe": {"upload": {"status": 503, "ms": 10032, "code": "unavailable", "retry_after": "1"}, "download": {"status": 503, "ms": 11, "code": "unavailable", "retry_after": "1"}, "text_message": {"status": 201, "ms": 15, "code": null, "retry_after": null}, "ready": {"status": 200, "ms": 4, "code": null, "retry_after": null}}}
|
||||
{"phase": "S3 down for 5 s (`pause s3`)", "probe": {"upload": {"status": 503, "ms": 13, "code": "unavailable", "retry_after": "1"}, "download": {"status": 503, "ms": 9, "code": "unavailable", "retry_after": "1"}, "text_message": {"status": 201, "ms": 14, "code": null, "retry_after": null}, "ready": {"status": 200, "ms": 3, "code": null, "retry_after": null}}}
|
||||
{"phase": "recovery after `unpause s3`", "upload_201_after_s": 0.0}
|
||||
{"phase": "s3 healthcheck healthy again", "after_s": 5.2, "status": "healthy"}
|
||||
{"pass": true, "only_200_201_503": true}
|
||||
@@ -0,0 +1,24 @@
|
||||
# 2026-11-07T08:24:37Z docker compose --profile tools run --rm s3-check
|
||||
PASS api: PutObject в свой bucket expected=allowed got=allowed
|
||||
PASS anonymous GET object expected=403 got=403
|
||||
PASS anonymous ListBucket expected=403 got=403
|
||||
PASS anonymous ListAllMyBuckets expected=403 got=403
|
||||
PASS anonymous PUT object expected=403 got=403
|
||||
PASS api: GetObject expected=allowed got=allowed
|
||||
PASS api: ListBucket expected=denied got=AccessDenied
|
||||
PASS api: CreateBucket expected=denied got=AccessDenied
|
||||
PASS api: DeleteBucket expected=denied got=AccessDenied
|
||||
PASS api: PutBucketPolicy (сделать публичным) expected=denied got=AccessDenied
|
||||
PASS janitor: GetObject (чтение содержимого) expected=denied got=AccessDenied
|
||||
PASS janitor: ListBucket expected=allowed got=allowed
|
||||
PASS janitor: CreateBucket expected=denied got=AccessDenied
|
||||
PASS api: DeleteObject (компенсация) expected=allowed got=allowed
|
||||
PASS port 9333 (master UI/API) из backend-сети expected=closed got=closed
|
||||
PASS port 8080 (volume) из backend-сети expected=closed got=closed
|
||||
PASS port 8888 (filer UI/API) из backend-сети expected=closed got=closed
|
||||
PASS port 8111 (IAM API) из backend-сети expected=closed got=closed
|
||||
PASS port 8181 (Iceberg) из backend-сети expected=closed got=closed
|
||||
PASS port 9101 (Lance) из backend-сети expected=closed got=closed
|
||||
PASS port 8333 (S3 API) из backend-сети expected=open got=open
|
||||
{"checks": 21, "failed": 0}
|
||||
exit=0
|
||||
@@ -0,0 +1,4 @@
|
||||
# 2026-11-07T08:24:34Z make test
|
||||
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
exit=0
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"concurrency": 12,
|
||||
"rounds": 3,
|
||||
"files": [
|
||||
{
|
||||
"type": "image/png",
|
||||
"bytes": 10482871,
|
||||
"sha256": "b71e4655e4cd99ff"
|
||||
},
|
||||
{
|
||||
"type": "image/jpeg",
|
||||
"bytes": 8051216,
|
||||
"sha256": "c49ef6d9ef42362e"
|
||||
}
|
||||
],
|
||||
"uploads": 36,
|
||||
"status_counts": {
|
||||
"201": 36
|
||||
},
|
||||
"megabytes_uploaded_ok": 318.2,
|
||||
"wall_s": 5.2,
|
||||
"latency_s_p50_max": [
|
||||
1.52,
|
||||
1.81
|
||||
],
|
||||
"replicas": {
|
||||
"f3ae32951e26": {
|
||||
"rss_mib": 50,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 115,
|
||||
"peak_rss_mib_sampled": 93.8,
|
||||
"peak_anon_mib": 75.6,
|
||||
"peak_file_cache_mib": 55.4,
|
||||
"vmhwm_mib": 93,
|
||||
"cgroup_memory_peak_mib": 133.0,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 18
|
||||
},
|
||||
"0bab682c4d3c": {
|
||||
"rss_mib": 53,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 111,
|
||||
"peak_rss_mib_sampled": 97.6,
|
||||
"peak_anon_mib": 85.8,
|
||||
"peak_file_cache_mib": 53.1,
|
||||
"vmhwm_mib": 97,
|
||||
"cgroup_memory_peak_mib": 139.4,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 18
|
||||
}
|
||||
},
|
||||
"s3": {
|
||||
"rss_mib": 439,
|
||||
"oom_killed": "false",
|
||||
"peak_rss_mib_sampled": 484.4,
|
||||
"peak_anon_mib": 402.8,
|
||||
"restarts": 0,
|
||||
"oom_killed_after": "false",
|
||||
"memory_limit_mib": 768
|
||||
},
|
||||
"oom_kills": [
|
||||
"false",
|
||||
"false"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"concurrency": 20,
|
||||
"rounds": 3,
|
||||
"files": [
|
||||
{
|
||||
"type": "image/png",
|
||||
"bytes": 10482871,
|
||||
"sha256": "d6c6106d37335280"
|
||||
},
|
||||
{
|
||||
"type": "image/jpeg",
|
||||
"bytes": 8051216,
|
||||
"sha256": "c49ef6d9ef42362e"
|
||||
}
|
||||
],
|
||||
"uploads": 60,
|
||||
"status_counts": {
|
||||
"201": 60
|
||||
},
|
||||
"megabytes_uploaded_ok": 530.3,
|
||||
"wall_s": 8.4,
|
||||
"latency_s_p50_max": [
|
||||
2.23,
|
||||
2.82
|
||||
],
|
||||
"replicas": {
|
||||
"f3ae32951e26": {
|
||||
"rss_mib": 53,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 159,
|
||||
"peak_rss_mib_sampled": 91.9,
|
||||
"peak_anon_mib": 73.5,
|
||||
"peak_file_cache_mib": 70.7,
|
||||
"vmhwm_mib": 91,
|
||||
"cgroup_memory_peak_mib": 145.4,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 30
|
||||
},
|
||||
"0bab682c4d3c": {
|
||||
"rss_mib": 50,
|
||||
"hwm_mib_after_warmup": 82,
|
||||
"samples": 170,
|
||||
"peak_rss_mib_sampled": 94.5,
|
||||
"peak_anon_mib": 75.9,
|
||||
"peak_file_cache_mib": 75.4,
|
||||
"vmhwm_mib": 94,
|
||||
"cgroup_memory_peak_mib": 159.2,
|
||||
"memory_limit_mib": 256,
|
||||
"uploads_served": 30
|
||||
}
|
||||
},
|
||||
"s3": {
|
||||
"rss_mib": 463,
|
||||
"oom_killed": "false",
|
||||
"peak_rss_mib_sampled": 487.3,
|
||||
"peak_anon_mib": 406.0,
|
||||
"restarts": 0,
|
||||
"oom_killed_after": "false",
|
||||
"memory_limit_mib": 768
|
||||
},
|
||||
"oom_kills": [
|
||||
"false",
|
||||
"false"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
# Lab3/4: единая точка входа перед API-репликами.
|
||||
#
|
||||
# Lab4: upload вложений — тело идёт потоком (без http-buffer-request); для upload timeout server
|
||||
# увеличен до 75 с (> UPLOAD_TIMEOUT_SECONDS=60 у API + запись в S3). Content-Length
|
||||
# больше лимита API отклоняет сам, не читая тело.
|
||||
#
|
||||
# Обнаружение реплик: DNS Docker (127.0.0.11) отдаёт по имени сервиса `api` адреса
|
||||
# ВСЕХ его контейнеров; server-template создаёт до 8 слотов и заполняет их по DNS.
|
||||
# Поэтому `docker compose up --scale api=N` не требует правки конфигурации.
|
||||
#
|
||||
# Readiness: активная проверка GET /health/ready каждую 1 с; 2 неудачи подряд -> DOWN,
|
||||
# 2 успеха -> UP. Максимальное время обнаружения отказа:
|
||||
# inter(1s) + timeout check(1s) + fastinter(0.5s) + timeout check(1s) ~= 3.5 с;
|
||||
# ready=503 или refused без ожидания таймаута -> ~1.5 с.
|
||||
# Sticky sessions НЕ используются: balance roundrobin без cookie/stick-table для backend
|
||||
# (stick-table во frontend считает только частоту входов по IP, на выбор реплики не влияет).
|
||||
#
|
||||
# Перегрузка: maxconn 10 на реплику (= DB_POOL_SIZE) — лишние запросы ждут в очереди LB
|
||||
# (timeout queue 5s), а не плодят потоки внутри Python-процесса. Переполнение -> 503 JSON.
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 4096
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold other 2s
|
||||
hold refused 2s
|
||||
hold nx 2s
|
||||
hold timeout 2s
|
||||
hold obsolete 2s
|
||||
accepted_payload_size 8192
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
# Внутри одного Docker-host соединение устанавливается за доли мс: 500 мс хватает с запасом,
|
||||
# а при внезапно исчезнувшей реплике запрос быстро уходит в retry на другую.
|
||||
timeout connect 500ms
|
||||
timeout client 30s
|
||||
timeout server 10s
|
||||
timeout http-request 10s
|
||||
timeout http-keep-alive 5s
|
||||
timeout queue 5s
|
||||
timeout check 1s
|
||||
# Повтор только если соединение с backend НЕ установлено (запрос точно не дошёл
|
||||
# до приложения) — это безопасно даже для неидемпотентных POST. Повтор уходит
|
||||
# на другую реплику (redispatch). Ответы/таймауты после отправки не повторяются.
|
||||
retries 2
|
||||
retry-on conn-failure
|
||||
option redispatch 1
|
||||
|
||||
# Ошибки, которые формирует сам HAProxy (нет живых реплик, обрыв backend, timeout,
|
||||
# переполнение очереди), отдаются в общем JSON-формате ошибки контракта, а не HTML.
|
||||
# Ответы приложения (в т.ч. его 503) эти правила не затрагивают.
|
||||
unique-id-format %[uuid()]
|
||||
http-error status 400 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"invalid_request","message":"Неверный запрос","request_id":"%ID"}}'
|
||||
http-error status 408 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"invalid_request","message":"Запрос не получен вовремя","request_id":"%ID"}}'
|
||||
http-error status 413 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"payload_too_large","message":"Файл больше допустимого размера","request_id":"%ID"}}'
|
||||
http-error status 429 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "10" lf-string '{"error":{"code":"rate_limited","message":"Слишком много запросов, повторите позже","request_id":"%ID"}}'
|
||||
http-error status 500 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" lf-string '{"error":{"code":"internal_error","message":"Внутренняя ошибка сервера","request_id":"%ID"}}'
|
||||
http-error status 502 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}'
|
||||
http-error status 503 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}'
|
||||
http-error status 504 content-type "application/json; charset=utf-8" hdr X-Request-Id "%ID" hdr Retry-After "1" lf-string '{"error":{"code":"unavailable","message":"Сервис временно недоступен","request_id":"%ID"}}'
|
||||
|
||||
frontend fe_api
|
||||
bind :8080
|
||||
# X-Request-Id формирует само приложение; LB только пробрасывает адрес клиента.
|
||||
option forwardfor
|
||||
# Защита входа от перебора паролей и шторма scrypt: не более LOGIN_RATE_LIMIT
|
||||
# попыток POST /auth/sessions за 10 с с одного IP, сверх — 429 rate_limited.
|
||||
stick-table type ip size 100k expire 60s store http_req_rate(10s)
|
||||
acl is_login method POST
|
||||
acl is_login_path path /api/v1/auth/sessions
|
||||
# Явно вычисляем unique-id до deny: иначе в ответе 429 request_id остаётся пустым.
|
||||
http-request set-var(txn.request_id) unique-id
|
||||
http-request track-sc0 src if is_login is_login_path
|
||||
http-request deny deny_status 429 if is_login is_login_path { sc_http_req_rate(0) gt "${LOGIN_RATE_LIMIT}" }
|
||||
# Lab4: лимит размера upload проверяет API по Content-Length ДО чтения тела (ответ 413
|
||||
# с X-Instance-Id по контракту). Дублирующий deny на LB убран: его ответ без X-Instance-Id.
|
||||
default_backend be_api
|
||||
|
||||
backend be_api
|
||||
balance roundrobin
|
||||
http-request set-timeout server 75s if METH_POST { path_reg ^/api/v1/chats/[^/]+/attachments$ }
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb
|
||||
http-check expect status 200
|
||||
# on-marked-down shutdown-sessions НЕ используется: при штатной остановке реплика ещё
|
||||
# дообслуживает начатые запросы (drain), и обрыв их сессий дал бы лишние 502.
|
||||
default-server maxconn 10 check inter 1s fastinter 500ms downinter 1s fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr libc,none
|
||||
server-template api 8 api:8080
|
||||
|
||||
# Статистика LB (только на 127.0.0.1 хоста): видно, какие реплики UP/DOWN.
|
||||
frontend stats
|
||||
bind :8404
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
stats show-legends
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Lab2: начальная схема. Источник истины — PostgreSQL.
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL UNIQUE,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
position integer NOT NULL, -- порядок участников как в запросе
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL
|
||||
);
|
||||
-- Индекс под keyset-пагинацию истории: (created_at, id) внутри чата.
|
||||
CREATE INDEX messages_chat_order_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY, -- SHA-256 от токена; сам токен не хранится
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
created_at timestamptz NOT NULL,
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Lab3: общая (для всех реплик) идемпотентность POST сообщения.
|
||||
-- Миграция только добавляет таблицу: код lab2 продолжает работать на новой схеме
|
||||
-- (expand-only), поэтому её можно применить до замены реплик при rolling update.
|
||||
--
|
||||
-- Область уникальности по контракту: пользователь + метод + путь чата + ключ.
|
||||
-- Метод всегда POST, путь однозначно задаётся chat_id, поэтому ключ PK — (user_id, chat_id, idem_key).
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
idem_key text NOT NULL,
|
||||
request_hash bytea NOT NULL, -- SHA-256 канонического JSON тела запроса
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, chat_id, idem_key)
|
||||
);
|
||||
CREATE INDEX idempotency_keys_expires_idx ON idempotency_keys (expires_at);
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Lab4: метаданные вложений (PostgreSQL) отдельно от байтов (приватный S3-bucket).
|
||||
-- Expand-only: только новые таблицы, код lab3 продолжает работать на этой схеме.
|
||||
--
|
||||
-- Жизненный цикл строки attachments:
|
||||
-- pending — намерение записано ДО S3 PUT (известны размер, SHA-256, object_key);
|
||||
-- ready — объект в S3 подтверждён, строка видна API и может быть прикреплена.
|
||||
-- Если процесс упал/БД отказала между PUT и переводом в ready, строка остаётся pending.
|
||||
-- Её находит janitor (src/janitor.py) по created_at старше grace period и удаляет
|
||||
-- сначала объект в S3, затем строку. Поэтому в S3 нет объектов, о которых не знает БД.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename text NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
-- Ключ назначает сервер (случайный), filename в нём не участвует.
|
||||
object_key text NOT NULL UNIQUE,
|
||||
status text NOT NULL CHECK (status IN ('pending', 'ready')),
|
||||
created_at timestamptz NOT NULL,
|
||||
updated_at timestamptz NOT NULL
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
|
||||
-- Janitor ищет только «зависшие» pending: частичный индекс маленький.
|
||||
CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending';
|
||||
|
||||
-- Ссылки сообщения на вложения (порядок как в запросе).
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id)
|
||||
);
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
|
||||
-- Отпечаток тела в ключе идемпотентности уже включает attachment_ids (= [] для lab3),
|
||||
-- поэтому существующие ключи остаются валидными без пересчёта.
|
||||
@@ -0,0 +1,8 @@
|
||||
# Закреплённые версии.
|
||||
# Драйвер PostgreSQL для Python (из lab3).
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg-pool==3.2.4
|
||||
# Lab4: S3-клиент (SigV4, multipart) и проверка JPEG (draft-декодирование).
|
||||
minio==7.2.15
|
||||
urllib3==2.3.0
|
||||
Pillow==11.1.0
|
||||
Executable
+50
@@ -0,0 +1,50 @@
|
||||
#!/bin/sh
|
||||
# Уровень 4: ПОСЛЕДОВАТЕЛЬНО останавливает КАЖДУЮ API-реплику под нагрузкой,
|
||||
# восстанавливая предыдущую перед следующей. Режимы:
|
||||
# stop — docker stop (SIGTERM -> graceful drain), штатная остановка/деплой;
|
||||
# kill — docker kill (SIGKILL), внезапное падение процесса без drain.
|
||||
# Результаты: evidence/failover-<mode>-<container>.json (+ .action.log).
|
||||
# Использование: scripts/failover-each.sh [stop|kill] ... (по умолчанию: stop kill)
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
MODES=${*:-stop kill}
|
||||
CONCURRENCY=${CONCURRENCY:-8}
|
||||
DURATION=${DURATION:-40}
|
||||
mkdir -p evidence
|
||||
|
||||
wait_all_up() {
|
||||
# API-контейнеры healthy и HAProxy видит их все UP (rise 2 * inter 1s).
|
||||
./scripts/start-all.sh >/dev/null
|
||||
n=$(docker compose ps -q api | wc -l | tr -d ' ')
|
||||
for _ in $(seq 1 60); do
|
||||
up=$(curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' ')
|
||||
[ "$up" -ge "$n" ] && return 0
|
||||
sleep 1
|
||||
done
|
||||
echo "HAProxy did not mark all $n api servers UP" >&2; return 1
|
||||
}
|
||||
|
||||
wait_all_up
|
||||
# Список фиксируется один раз: остановленная реплика пропала бы из `docker compose ps`.
|
||||
NAMES=$(docker compose ps --format '{{.Name}}' api | sort)
|
||||
for mode in $MODES; do
|
||||
for name in $NAMES; do
|
||||
wait_all_up
|
||||
cid=$(docker inspect -f '{{.Id}}' "$name"); short=$(echo "$cid" | cut -c1-12)
|
||||
case $mode in
|
||||
stop) action="docker stop -t 20 $cid" ;;
|
||||
kill) action="docker kill $cid" ;;
|
||||
*) echo "unknown mode $mode" >&2; exit 2 ;;
|
||||
esac
|
||||
echo "== $mode $name ($short) $(date -u +%FT%TZ)"
|
||||
out=evidence/failover-$mode-$name.json
|
||||
python3 student-tests/failover_bench.py --label "$mode $name" \
|
||||
--concurrency "$CONCURRENCY" --duration "$DURATION" --action-at 10 \
|
||||
--action "$action" --target-instance "$short" \
|
||||
--action-log "${out%.json}.action.log" --output "$out" \
|
||||
| python3 -c 'import json,sys; t=sys.stdin.read(); s=json.loads(t[:t.rindex("}")+1]); print(json.dumps({k:s[k] for k in ("baseline_ok_rps","post_action_ok_rps","capacity_ratio","errors_total","errors_by_kind","error_window_s","recovery_s","target_last_seen_s","lb_events","lost_confirmed","duplicate_texts","pass")},ensure_ascii=False)); sys.exit(0 if s["pass"] else 1)'
|
||||
echo "-- state after action:"; docker compose ps -a --format '{{.Name}} {{.Status}}' api
|
||||
done
|
||||
done
|
||||
wait_all_up
|
||||
echo "== restored: $(docker compose ps --format '{{.Name}} {{.Status}}' api | tr '\n' ';')"
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
# Создаёт локальные секреты и .env для учебного стенда. Повторный запуск ничего не перезаписывает.
|
||||
# Значения секретов не печатаются.
|
||||
#
|
||||
# S3 (SeaweedFS) — три РАЗНЫХ набора ключей с разными правами (secrets/s3_identities.json):
|
||||
# admin — Admin/Read/Write/List: только job s3-init (создание bucket);
|
||||
# api — Read+Write на bucket: без List, без создания/удаления bucket, без политик;
|
||||
# janitor — List+Write на bucket: обход и удаление, без чтения содержимого.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
gen() { # gen <file> <bytes>
|
||||
if [ ! -s "secrets/$1" ]; then
|
||||
python3 -c "import secrets,sys; print(secrets.token_urlsafe(int(sys.argv[1])))" "$2" > "secrets/$1"
|
||||
echo "created secrets/$1"
|
||||
fi
|
||||
}
|
||||
gen postgres_password 24
|
||||
for who in admin api janitor; do
|
||||
if [ ! -s "secrets/s3_${who}_access_key" ]; then
|
||||
python3 -c "import secrets; print('MTUSI' + secrets.token_hex(8).upper())" > "secrets/s3_${who}_access_key"
|
||||
echo "created secrets/s3_${who}_access_key"
|
||||
fi
|
||||
gen "s3_${who}_secret_key" 30
|
||||
done
|
||||
BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | cut -d= -f2 || true)
|
||||
BUCKET=${BUCKET:-messenger-attachments}
|
||||
# Конфигурация identities SeaweedFS пересобирается из ключей (детерминированно).
|
||||
python3 - "$BUCKET" <<'PY'
|
||||
import json, sys
|
||||
b = sys.argv[1]
|
||||
def key(who, kind):
|
||||
return open("secrets/s3_%s_%s_key" % (who, kind)).read().strip()
|
||||
def ident(name, actions):
|
||||
return {"name": name, "credentials": [{"accessKey": key(name, "access"), "secretKey": key(name, "secret")}],
|
||||
"actions": actions}
|
||||
cfg = {"identities": [
|
||||
ident("admin", ["Admin", "Read", "List", "Tagging", "Write"]),
|
||||
ident("api", ["Read:" + b, "Write:" + b]),
|
||||
ident("janitor", ["List:" + b, "Write:" + b]),
|
||||
]}
|
||||
with open("secrets/s3_identities.json", "w") as f:
|
||||
json.dump(cfg, f, indent=1)
|
||||
PY
|
||||
# Файлы монтируются в контейнеры (uid 70 postgres, uid 10001 app, root в seaweedfs) — нужны на чтение;
|
||||
# от других пользователей хоста их закрывает каталог secrets/ с правами 700.
|
||||
chmod 644 secrets/*
|
||||
if [ ! -f .env ]; then
|
||||
cp .env.example .env
|
||||
echo "created .env from .env.example"
|
||||
fi
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
# Перезапуск ВСЕХ хранилищ (PostgreSQL, SeaweedFS S3) и API (все реплики), janitor и LB
|
||||
# с сохранением volumes pgdata и s3data. Не выполняет down -v, не пересоздаёт БД/bucket
|
||||
# и не повторяет seed. Сначала хранилища, затем потребители.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart db s3
|
||||
# API стартует, когда хранилища действительно готовы (healthcheck s3 проверяет запись).
|
||||
docker compose up -d --no-deps --no-recreate --wait db s3
|
||||
docker compose restart api janitor lb
|
||||
Executable
+57
@@ -0,0 +1,57 @@
|
||||
#!/bin/sh
|
||||
# Поочерёдная замена API-реплик на новую версию образа без остановки сервиса.
|
||||
# scripts/rolling-update.sh <APP_VERSION>
|
||||
# Порядок (expand -> replace):
|
||||
# 1. собрать новый образ (тот же тег mtusi-messenger:lab4, build-arg APP_VERSION);
|
||||
# 2. ОДИН раз применить миграции (job migrate). Допускаются только обратно совместимые
|
||||
# (expand-only) миграции: старые реплики продолжают работать на новой схеме;
|
||||
# 3. для каждой старой реплики: поднять +1 новую -> дождаться healthy и UP в HAProxy ->
|
||||
# штатно остановить (SIGTERM, drain) и удалить старую. Число обслуживающих реплик
|
||||
# не опускается ниже исходного.
|
||||
# 4. записать APP_VERSION в .env, чтобы следующий `docker compose up` не пересоздал всё разом.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
VERSION=${1:?usage: rolling-update.sh <APP_VERSION>}
|
||||
export APP_VERSION="$VERSION"
|
||||
ts() { date -u +%FT%TZ; }
|
||||
|
||||
lb_up_count() {
|
||||
curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' '
|
||||
}
|
||||
# UP ли в HAProxy слот с адресом конкретного контейнера. Проверяем именно адрес, а не число
|
||||
# UP-серверов: новый контейнер может получить IP только что удалённого, и счётчик обманет.
|
||||
lb_has_up() {
|
||||
curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, -v a="$1:8080" '$1=="be_api" && $18=="UP" && $74==a' | grep -q .
|
||||
}
|
||||
|
||||
echo "$(ts) build version $VERSION"
|
||||
docker compose --env-file .env build api >/dev/null
|
||||
echo "$(ts) migrate (once)"
|
||||
docker compose --env-file .env run --rm --no-deps migrate
|
||||
|
||||
OLD=$(docker compose ps -q api)
|
||||
N=$(echo "$OLD" | wc -l | tr -d ' ')
|
||||
echo "$(ts) replacing $N replicas"
|
||||
for old in $OLD; do
|
||||
before=$(docker compose ps -q api | sort)
|
||||
docker compose --env-file .env up -d --no-deps --no-recreate --scale api=$((N + 1)) api >/dev/null 2>&1
|
||||
new=$(docker compose ps -q api | sort | grep -v -F "$before" | head -1)
|
||||
[ -n "$new" ] || { echo "new replica was not created" >&2; exit 1; }
|
||||
for _ in $(seq 1 60); do
|
||||
[ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ] && break; sleep 1
|
||||
done
|
||||
[ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ] || { echo "new replica not healthy" >&2; exit 1; }
|
||||
ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$new")
|
||||
for _ in $(seq 1 30); do lb_has_up "$ip" && break; sleep 0.5; done
|
||||
lb_has_up "$ip" || { echo "HAProxy did not mark new replica $ip UP" >&2; exit 1; }
|
||||
echo "$(ts) up $(docker inspect -f '{{.Name}}' "$new" | tr -d /) version=$(docker exec "$new" printenv APP_VERSION) ip=$ip UP in LB (UP slots: $(lb_up_count))"
|
||||
name=$(docker inspect -f '{{.Name}}' "$old" | tr -d /)
|
||||
docker stop -t 20 "$old" >/dev/null && docker rm "$old" >/dev/null
|
||||
echo "$(ts) gone $name (graceful SIGTERM)"
|
||||
done
|
||||
if grep -q '^APP_VERSION=' .env; then
|
||||
sed -i.bak "s/^APP_VERSION=.*/APP_VERSION=$VERSION/" .env && rm -f .env.bak
|
||||
else
|
||||
echo "APP_VERSION=$VERSION" >> .env
|
||||
fi
|
||||
echo "$(ts) done: $(docker compose ps --format '{{.Name}}' api | tr '\n' ' ')"
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Восстанавливает остановленные API-реплики (после stop-one.sh / failover-each.sh) и ждёт готовности.
|
||||
# --no-deps: БД и job миграций не трогаются; --no-recreate: те же контейнеры (тот же образ).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose up -d --no-deps --no-recreate --wait api
|
||||
docker compose ps --format '{{.Name}} {{.Status}}' api
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Останавливает ОДНУ API-реплику, обслужившую тест, и оставляет её остановленной.
|
||||
# TARGET_INSTANCE_ID = X-Instance-Id = hostname контейнера = короткий ID контейнера.
|
||||
# DB, LB и volumes не трогаются. Восстановление: scripts/start-all.sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!0-9a-f]*|'') echo "unexpected instance id format" >&2; exit 2 ;;
|
||||
esac
|
||||
# Проверяем, что это действительно запущенный контейнер сервиса api ЭТОГО compose-проекта.
|
||||
# Список берём у самого compose: работает и при другом имени проекта (-p / COMPOSE_PROJECT_NAME).
|
||||
cid=$(docker compose ps -q --status running api | grep "^${TARGET_INSTANCE_ID}" || true)
|
||||
[ -n "$cid" ] || { echo "no running api container for $TARGET_INSTANCE_ID" >&2; exit 3; }
|
||||
name=$(docker inspect -f '{{.Name}}' "$cid")
|
||||
echo "$(date -u +%FT%TZ) stopping api container ${name#/} (${TARGET_INSTANCE_ID})" >&2
|
||||
# SIGTERM -> graceful shutdown приложения (drain 3 с + дообслуживание), затем выход.
|
||||
docker stop -t 20 "$cid" >/dev/null
|
||||
echo "$(date -u +%FT%TZ) stopped ${name#/}" >&2
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
"""Проверка загружаемых изображений по СОДЕРЖИМОМУ, с ограниченной памятью.
|
||||
|
||||
Заголовок Content-Type клиента — только заявление: настоящий формат определяется
|
||||
по сигнатуре и структуре файла. Лимит пикселей проверяется по заголовку (PNG IHDR,
|
||||
JPEG SOF) ДО распаковки, поэтому «бомба» 100 000×100 000 не декодируется вовсе.
|
||||
|
||||
PNG проверяется собственным потоковым валидатором (стандартная библиотека):
|
||||
структура и CRC каждого chunk, допустимые IHDR, IDAT распаковывается zlib кусками
|
||||
по 1 MiB без сохранения результата; объём распакованных данных должен ТОЧНО совпасть
|
||||
с размером, который следует из IHDR (больше — бомба/мусор, меньше — обрезанный файл).
|
||||
|
||||
JPEG: разбор маркеров до SOF (размеры), затем пробное декодирование Pillow в режиме
|
||||
draft (масштаб 1/8): проверяются энтропийные данные, а памяти нужно ~1/64 от полного
|
||||
кадра (40 Мпикс -> ~2 MiB вместо ~120 MiB).
|
||||
"""
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
JPEG_SOI = b"\xff\xd8\xff"
|
||||
READ_CHUNK = 64 * 1024
|
||||
INFLATE_STEP = 1024 * 1024
|
||||
|
||||
# Допустимые глубины цвета по типу цвета PNG и число каналов.
|
||||
_PNG_DEPTHS = {0: {1, 2, 4, 8, 16}, 2: {8, 16}, 3: {1, 2, 4, 8}, 4: {8, 16}, 6: {8, 16}}
|
||||
_PNG_CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
|
||||
# Adam7: (x0, y0, dx, dy)
|
||||
_ADAM7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2))
|
||||
_JPEG_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
|
||||
|
||||
|
||||
class InvalidImage(Exception):
|
||||
"""Файл не является корректным PNG/JPEG заявленного типа -> 415."""
|
||||
|
||||
|
||||
class TooManyPixels(Exception):
|
||||
"""Декодированный размер превышает лимит -> 413."""
|
||||
|
||||
|
||||
def sniff(head):
|
||||
"""Тип по сигнатуре первых байтов: 'image/png', 'image/jpeg' или None."""
|
||||
if head.startswith(PNG_SIGNATURE):
|
||||
return "image/png"
|
||||
if head.startswith(JPEG_SOI):
|
||||
return "image/jpeg"
|
||||
return None
|
||||
|
||||
|
||||
def png_header_pixels(head):
|
||||
"""Ранняя проверка по первым 33 байтам (сигнатура + IHDR): (w, h) или None."""
|
||||
if len(head) < 33 or not head.startswith(PNG_SIGNATURE) or head[12:16] != b"IHDR":
|
||||
return None
|
||||
return struct.unpack(">II", head[16:24])
|
||||
|
||||
|
||||
def _read_exact(f, n):
|
||||
data = f.read(n)
|
||||
if len(data) != n:
|
||||
raise InvalidImage("truncated")
|
||||
return data
|
||||
|
||||
|
||||
def _png_expected_bytes(w, h, bits_per_pixel, interlace):
|
||||
def raw(pw, ph):
|
||||
return ph * (1 + (pw * bits_per_pixel + 7) // 8) if pw and ph else 0
|
||||
if interlace == 0:
|
||||
return raw(w, h)
|
||||
total = 0
|
||||
for x0, y0, dx, dy in _ADAM7:
|
||||
pw = (w - x0 + dx - 1) // dx if w > x0 else 0
|
||||
ph = (h - y0 + dy - 1) // dy if h > y0 else 0
|
||||
total += raw(pw, ph)
|
||||
return total
|
||||
|
||||
|
||||
def validate_png(f, size, max_pixels):
|
||||
if _read_exact(f, 8) != PNG_SIGNATURE:
|
||||
raise InvalidImage("signature")
|
||||
pos = 8
|
||||
width = height = None
|
||||
expected = produced = 0
|
||||
inflater = None
|
||||
seen_plte = idat_done = False
|
||||
color_type = None
|
||||
last_type = None
|
||||
while True:
|
||||
if pos + 12 > size:
|
||||
raise InvalidImage("truncated")
|
||||
length, ctype = struct.unpack(">I4s", _read_exact(f, 8))
|
||||
pos += 8
|
||||
if length > 0x7FFFFFFF or pos + length + 4 > size:
|
||||
raise InvalidImage("chunk length")
|
||||
if not ctype.isalpha():
|
||||
raise InvalidImage("chunk type")
|
||||
if width is None and ctype != b"IHDR":
|
||||
raise InvalidImage("IHDR must be first")
|
||||
crc = zlib.crc32(ctype)
|
||||
if ctype == b"IDAT":
|
||||
if idat_done or (color_type == 3 and not seen_plte):
|
||||
raise InvalidImage("IDAT order")
|
||||
remaining = length
|
||||
while remaining:
|
||||
piece = _read_exact(f, min(READ_CHUNK, remaining))
|
||||
remaining -= len(piece)
|
||||
crc = zlib.crc32(piece, crc)
|
||||
buf = piece
|
||||
while buf:
|
||||
if inflater.eof:
|
||||
raise InvalidImage("data after zlib stream")
|
||||
try:
|
||||
out = inflater.decompress(buf, INFLATE_STEP)
|
||||
except zlib.error:
|
||||
raise InvalidImage("zlib")
|
||||
produced += len(out)
|
||||
if produced > expected:
|
||||
raise InvalidImage("too much pixel data") # бомба/мусор
|
||||
buf = inflater.unconsumed_tail
|
||||
else:
|
||||
if last_type == b"IDAT":
|
||||
idat_done = True
|
||||
data = _read_exact(f, length)
|
||||
crc = zlib.crc32(data, crc)
|
||||
if ctype == b"IHDR":
|
||||
if width is not None or length != 13:
|
||||
raise InvalidImage("IHDR")
|
||||
width, height, depth, color_type, comp, filt, interlace = struct.unpack(">IIBBBBB", data)
|
||||
if not (1 <= width <= 0x7FFFFFFF and 1 <= height <= 0x7FFFFFFF):
|
||||
raise InvalidImage("dimensions")
|
||||
if width * height > max_pixels:
|
||||
raise TooManyPixels()
|
||||
if depth not in _PNG_DEPTHS.get(color_type, ()) or comp != 0 or filt != 0 or interlace not in (0, 1):
|
||||
raise InvalidImage("IHDR values")
|
||||
expected = _png_expected_bytes(width, height, _PNG_CHANNELS[color_type] * depth, interlace)
|
||||
inflater = zlib.decompressobj()
|
||||
elif ctype == b"PLTE":
|
||||
seen_plte = True
|
||||
elif ctype == b"IEND":
|
||||
pass
|
||||
elif ctype[0:1].isupper():
|
||||
raise InvalidImage("unknown critical chunk") # декодер обязан его понимать
|
||||
if struct.unpack(">I", _read_exact(f, 4))[0] != crc & 0xFFFFFFFF:
|
||||
raise InvalidImage("crc")
|
||||
pos += length + 4
|
||||
last_type = ctype
|
||||
if ctype == b"IEND":
|
||||
break
|
||||
if inflater is None or not inflater.eof or produced != expected:
|
||||
raise InvalidImage("incomplete pixel data")
|
||||
if pos != size:
|
||||
raise InvalidImage("trailing data") # полиглоты PNG+что-то ещё не принимаем
|
||||
return width, height
|
||||
|
||||
|
||||
def jpeg_dimensions(f, size):
|
||||
"""Размеры из первого SOF без декодирования. Ограничено размером файла."""
|
||||
if _read_exact(f, 2) != b"\xff\xd8":
|
||||
raise InvalidImage("signature")
|
||||
pos = 2
|
||||
while pos < size:
|
||||
b = _read_exact(f, 1)
|
||||
pos += 1
|
||||
if b != b"\xff":
|
||||
raise InvalidImage("marker")
|
||||
marker = 0xFF
|
||||
while marker == 0xFF:
|
||||
marker = _read_exact(f, 1)[0]
|
||||
pos += 1
|
||||
if marker == 0x01 or 0xD0 <= marker <= 0xD7:
|
||||
continue
|
||||
if marker in (0xD8, 0xD9, 0xDA):
|
||||
raise InvalidImage("no SOF before scan")
|
||||
seg_len = struct.unpack(">H", _read_exact(f, 2))[0]
|
||||
if seg_len < 2 or pos + seg_len > size:
|
||||
raise InvalidImage("segment length")
|
||||
if marker in _JPEG_SOF:
|
||||
if seg_len < 8:
|
||||
raise InvalidImage("SOF")
|
||||
_precision, height, width = struct.unpack(">BHH", _read_exact(f, 5))
|
||||
if width == 0 or height == 0:
|
||||
raise InvalidImage("dimensions") # DNL-высота не поддерживается
|
||||
return width, height
|
||||
f.seek(seg_len - 2, 1)
|
||||
pos += seg_len
|
||||
raise InvalidImage("no SOF")
|
||||
|
||||
|
||||
def validate_jpeg(f, size, max_pixels):
|
||||
width, height = jpeg_dimensions(f, size)
|
||||
if width * height > max_pixels:
|
||||
raise TooManyPixels()
|
||||
from PIL import Image # импорт по требованию: Pillow нужен только для JPEG
|
||||
Image.MAX_IMAGE_PIXELS = max_pixels
|
||||
f.seek(0)
|
||||
try:
|
||||
with Image.open(f, formats=("JPEG",)) as im:
|
||||
if im.size != (width, height):
|
||||
raise InvalidImage("size mismatch")
|
||||
im.draft("RGB", (max(1, width // 8), max(1, height // 8)))
|
||||
im.load() # обрезанные/битые энтропийные данные -> OSError
|
||||
except InvalidImage:
|
||||
raise
|
||||
except Exception:
|
||||
# Pillow бросает разные исключения (OSError, SyntaxError, ValueError,
|
||||
# DecompressionBombError...) — для клиента это одинаково «не JPEG».
|
||||
raise InvalidImage("decode")
|
||||
return width, height
|
||||
|
||||
|
||||
def validate(f, size, content_type, max_pixels):
|
||||
"""(width, height) или InvalidImage/TooManyPixels. f — seekable файл, позиция 0."""
|
||||
f.seek(0)
|
||||
if content_type == "image/png":
|
||||
return validate_png(f, size, max_pixels)
|
||||
if content_type == "image/jpeg":
|
||||
return validate_jpeg(f, size, max_pixels)
|
||||
raise InvalidImage("type")
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сверка PostgreSQL <-> S3 и очистка неучтённых объектов (compose-сервис `janitor`).
|
||||
|
||||
Инвариант записи (src/server.py): pending-строка фиксируется ДО S3 PUT, ready — после.
|
||||
Поэтому любой объект в bucket либо имеет строку в attachments, либо остался от сбоя.
|
||||
|
||||
За один проход (под pg_try_advisory_lock — параллельные janitor не мешают друг другу):
|
||||
1. abandoned: pending-строки старше grace -> удалить объект (идемпотентно), затем строку;
|
||||
2. orphan: объекты originals/* старше grace без строки в БД -> удалить объект;
|
||||
3. missing: ready-строки без объекта -> ТОЛЬКО отчёт (метаданные не удаляются
|
||||
автоматически: это потеря данных, нужен человек).
|
||||
|
||||
Grace period (ATTACHMENT_GRACE_SECONDS, по умолчанию 3600 с) многократно больше
|
||||
времени жизни загрузки (UPLOAD_TIMEOUT_SECONDS=60 + таймауты S3), поэтому ещё идущая
|
||||
загрузка не может быть принята за брошенную. Даже если это случится, API переводит
|
||||
строку в ready только из pending (UPDATE ... WHERE status='pending') и при неудаче
|
||||
удаляет свой объект и отвечает 503 — ready-вложение janitor не трогает никогда.
|
||||
|
||||
Права: отдельные S3 credentials janitor = List+Write на bucket (без Read), API их не имеет.
|
||||
|
||||
python src/janitor.py --once --dry-run # только отчёт
|
||||
python src/janitor.py --once # отчёт + исправление
|
||||
python src/janitor.py --interval 300 # фоновый режим (сервис janitor)
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from server import OBJ, STORE
|
||||
|
||||
log = logging.getLogger("messenger.janitor")
|
||||
JANITOR_LOCK_ID = 727002
|
||||
PREFIX = "originals/"
|
||||
HEARTBEAT = "/tmp/janitor.heartbeat" # healthcheck compose: файл обновляется не реже 30 с
|
||||
|
||||
|
||||
def heartbeat():
|
||||
with open(HEARTBEAT, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
|
||||
|
||||
def run_once(grace_seconds, dry_run):
|
||||
started = time.monotonic()
|
||||
report = {"dry_run": dry_run, "grace_seconds": grace_seconds,
|
||||
"abandoned_pending": 0, "orphan_objects": 0, "missing_objects": 0,
|
||||
"deleted_objects": 0, "deleted_rows": 0, "errors": 0}
|
||||
with STORE.pool.connection() as conn:
|
||||
conn.autocommit = True
|
||||
if not conn.execute("SELECT pg_try_advisory_lock(%s) AS ok", (JANITOR_LOCK_ID,)).fetchone()["ok"]:
|
||||
report["skipped"] = "another janitor is running"
|
||||
return report
|
||||
try:
|
||||
now_db = conn.execute("SELECT now() AS t").fetchone()["t"]
|
||||
cutoff = now_db - dt.timedelta(seconds=grace_seconds)
|
||||
counts = conn.execute(
|
||||
"SELECT status, count(*) AS n FROM attachments GROUP BY status").fetchall()
|
||||
report["rows_by_status"] = {r["status"]: r["n"] for r in counts}
|
||||
|
||||
# 1. брошенные pending (сбой между записью намерения и ready)
|
||||
abandoned = conn.execute(
|
||||
"""SELECT id, object_key FROM attachments
|
||||
WHERE status = 'pending' AND created_at < %s ORDER BY created_at""",
|
||||
(cutoff,)).fetchall()
|
||||
report["abandoned_pending"] = len(abandoned)
|
||||
report["abandoned_ids"] = [str(r["id"]) for r in abandoned[:20]]
|
||||
for row in abandoned:
|
||||
if dry_run:
|
||||
continue
|
||||
try:
|
||||
OBJ.delete(row["object_key"]) # сначала объект (идемпотентно)
|
||||
report["deleted_objects"] += 1
|
||||
deleted = conn.execute(
|
||||
"DELETE FROM attachments WHERE id = %s AND status = 'pending'",
|
||||
(row["id"],)).rowcount # потом строка
|
||||
report["deleted_rows"] += deleted
|
||||
except Exception as exc:
|
||||
report["errors"] += 1
|
||||
log.warning("abandoned %s not cleaned (%s)", row["id"], type(exc).__name__)
|
||||
|
||||
# 2/3. обход bucket и сравнение с БД. Момент начала обхода фиксируем по часам БД:
|
||||
# строка, ставшая ready раньше, обязана иметь объект в листинге (PUT до ready).
|
||||
list_started = conn.execute("SELECT now() AS t").fetchone()["t"]
|
||||
listed = {}
|
||||
for obj in OBJ.client.list_objects(OBJ.bucket, prefix=PREFIX, recursive=True):
|
||||
listed[obj.object_name] = obj.last_modified
|
||||
report["objects_total"] = len(listed)
|
||||
known = set()
|
||||
keys = list(listed)
|
||||
for i in range(0, len(keys), 1000):
|
||||
batch = keys[i:i + 1000]
|
||||
for r in conn.execute("SELECT object_key FROM attachments WHERE object_key = ANY(%s)", (batch,)):
|
||||
known.add(r["object_key"])
|
||||
orphans = [k for k, mtime in listed.items()
|
||||
if k not in known and mtime is not None and mtime < cutoff]
|
||||
report["orphan_objects"] = len(orphans)
|
||||
report["orphan_keys_sample"] = sorted(orphans)[:5]
|
||||
for key in orphans:
|
||||
if dry_run:
|
||||
continue
|
||||
try:
|
||||
OBJ.delete(key)
|
||||
report["deleted_objects"] += 1
|
||||
except Exception as exc:
|
||||
report["errors"] += 1
|
||||
log.warning("orphan object not deleted (%s)", type(exc).__name__)
|
||||
|
||||
missing = [str(r["id"]) for r in conn.execute(
|
||||
"""SELECT id, object_key FROM attachments WHERE status = 'ready' AND updated_at < %s""",
|
||||
(list_started,)) if r["object_key"] not in listed]
|
||||
report["missing_objects"] = len(missing)
|
||||
report["missing_ids_sample"] = missing[:5]
|
||||
if missing:
|
||||
log.error("ready attachments without object: %d (manual investigation needed)", len(missing))
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (JANITOR_LOCK_ID,))
|
||||
report["duration_ms"] = round((time.monotonic() - started) * 1000, 1)
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--once", action="store_true")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
parser.add_argument("--grace-seconds", type=int,
|
||||
default=int(os.environ.get("ATTACHMENT_GRACE_SECONDS", "3600")))
|
||||
parser.add_argument("--interval", type=int, default=int(os.environ.get("JANITOR_INTERVAL_SECONDS", "300")))
|
||||
args = parser.parse_args()
|
||||
if args.grace_seconds < 1:
|
||||
parser.error("grace period must be positive")
|
||||
STORE.open()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
print(json.dumps(run_once(args.grace_seconds, args.dry_run), ensure_ascii=False), flush=True)
|
||||
except Exception as exc:
|
||||
log.warning("janitor pass failed (%s)", type(exc).__name__)
|
||||
if args.once:
|
||||
return 1
|
||||
if args.once:
|
||||
return 0
|
||||
wake = time.monotonic() + args.interval
|
||||
while time.monotonic() < wake:
|
||||
heartbeat()
|
||||
time.sleep(min(30, max(0.1, wake - time.monotonic())))
|
||||
finally:
|
||||
STORE.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Однократное применение миграций (compose-сервис `migrate`).
|
||||
|
||||
Запускается ОДИН раз до старта/замены API-реплик, а не каждой репликой.
|
||||
Дополнительно миграции выполняются под pg_advisory_xact_lock: даже если
|
||||
оператор случайно запустит job дважды параллельно, гонки не будет.
|
||||
Каждый файл применяется в своей транзакции и фиксируется в schema_migrations.
|
||||
"""
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from server import MIGRATIONS_DIR, STORE
|
||||
|
||||
log = logging.getLogger("messenger.migrate")
|
||||
|
||||
|
||||
def main():
|
||||
STORE.open()
|
||||
try:
|
||||
before = STORE.pending_migrations(MIGRATIONS_DIR)
|
||||
STORE.migrate(MIGRATIONS_DIR)
|
||||
log.info("migrations done; applied now: %s", ", ".join(before) or "nothing")
|
||||
finally:
|
||||
STORE.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
"""Доступ к S3-совместимому хранилищу (SeaweedFS) через клиент minio-py.
|
||||
|
||||
API работает с bucket под ОТДЕЛЬНЫМИ credentials с правами только Read+Write на этот
|
||||
bucket (без List, без создания/удаления bucket, без политик и IAM) — см.
|
||||
scripts/init-secrets.sh и REPORT.md. Публичных URL/redirect нет: байты всегда идут
|
||||
через авторизованный API.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import urllib3
|
||||
from minio import Minio
|
||||
from minio.error import S3Error
|
||||
|
||||
log = logging.getLogger("messenger.s3")
|
||||
|
||||
# minio-py для объектов больше part_size делает multipart и держит в памяти
|
||||
# один part. 5 MiB — минимум S3: файл 10 MiB -> 2 части по 5 MiB.
|
||||
PART_SIZE = 5 * 1024 * 1024
|
||||
STREAM_CHUNK = 64 * 1024
|
||||
# Служебные объекты S3Health: health/<реплика> (вне prefix originals/, janitor их не трогает).
|
||||
HEALTH_PREFIX = "health/"
|
||||
|
||||
|
||||
class StorageUnavailable(Exception):
|
||||
"""S3 недоступен/таймаут/ошибка сервера -> 503."""
|
||||
|
||||
|
||||
class ObjectMissing(Exception):
|
||||
"""Метаданные есть, объекта нет (рассогласование) -> 503 + лог."""
|
||||
|
||||
|
||||
def _secret(name):
|
||||
path = os.environ.get(name + "_FILE")
|
||||
if path:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return f.read().strip()
|
||||
return os.environ.get(name, "")
|
||||
|
||||
|
||||
def make_client(access_env="S3_ACCESS_KEY_ID", secret_env="S3_SECRET_ACCESS_KEY",
|
||||
connect_timeout=None, read_timeout=None):
|
||||
endpoint = urlsplit(os.environ.get("S3_ENDPOINT", "http://s3:8333"))
|
||||
connect_timeout = connect_timeout or float(os.environ.get("S3_CONNECT_TIMEOUT_SECONDS", "2"))
|
||||
read_timeout = read_timeout or float(os.environ.get("S3_READ_TIMEOUT_SECONDS", "5"))
|
||||
# Короткие таймауты и без собственных повторов: зависший S3 не держит поток
|
||||
# дольше таймаута LB, повтор решает клиент (для upload — новым запросом).
|
||||
http = urllib3.PoolManager(
|
||||
timeout=urllib3.Timeout(connect=connect_timeout, read=read_timeout),
|
||||
retries=urllib3.Retry(total=0, connect=0, read=0, redirect=0, status=0),
|
||||
maxsize=int(os.environ.get("S3_POOL_SIZE", "16")),
|
||||
block=False)
|
||||
return Minio(endpoint.netloc, access_key=_secret(access_env), secret_key=_secret(secret_env),
|
||||
secure=endpoint.scheme == "https", region=os.environ.get("S3_REGION", "us-east-1"),
|
||||
http_client=http)
|
||||
|
||||
|
||||
def _is_transport_error(exc):
|
||||
return isinstance(exc, (urllib3.exceptions.HTTPError, OSError))
|
||||
|
||||
|
||||
class ObjectStore:
|
||||
def __init__(self, client, bucket):
|
||||
self.client = client
|
||||
self.bucket = bucket
|
||||
|
||||
def put(self, key, fileobj, length, content_type):
|
||||
try:
|
||||
self.client.put_object(self.bucket, key, fileobj, length, content_type=content_type,
|
||||
part_size=PART_SIZE)
|
||||
except S3Error as exc:
|
||||
log.warning("s3 put failed: %s", exc.code)
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
log.warning("s3 put failed: %s", type(exc).__name__)
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def open(self, key):
|
||||
"""Поток объекта (urllib3 response). Закрывать: resp.close(); resp.release_conn()."""
|
||||
try:
|
||||
return self.client.get_object(self.bucket, key)
|
||||
except S3Error as exc:
|
||||
if exc.code in ("NoSuchKey", "NoSuchObject"):
|
||||
raise ObjectMissing()
|
||||
log.warning("s3 get failed: %s", exc.code)
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
log.warning("s3 get failed: %s", type(exc).__name__)
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def delete(self, key):
|
||||
"""Идемпотентно: отсутствие объекта — не ошибка (S3 DELETE так и работает)."""
|
||||
try:
|
||||
self.client.remove_object(self.bucket, key)
|
||||
except S3Error as exc:
|
||||
if exc.code in ("NoSuchKey", "NoSuchObject"):
|
||||
return
|
||||
raise StorageUnavailable()
|
||||
except Exception as exc:
|
||||
if _is_transport_error(exc):
|
||||
raise StorageUnavailable()
|
||||
raise
|
||||
|
||||
def ping(self, probe_key):
|
||||
"""PUT + GET маленького служебного объекта health/<реплика>: проверяет S3,
|
||||
credentials и РЕАЛЬНЫЕ пути записи и чтения. HEAD bucket/healthz для этого мало:
|
||||
у SeaweedFS после рестарта они успешны, а первая запись ещё ~5 с висит
|
||||
(выбор raft-лидера master, выдача volume под запись)."""
|
||||
import io
|
||||
self.client.put_object(self.bucket, probe_key, io.BytesIO(b"ok"), 2, content_type="text/plain")
|
||||
resp = self.client.get_object(self.bucket, probe_key)
|
||||
try:
|
||||
if resp.read() != b"ok":
|
||||
raise RuntimeError("probe mismatch")
|
||||
finally:
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
return True
|
||||
|
||||
|
||||
class S3Health:
|
||||
"""Фоновая проверка S3, как DbHealth для PostgreSQL.
|
||||
|
||||
S3 НЕ входит в /health/ready: он общий для всех реплик, и его отказ не лечится
|
||||
исключением реплики из LB, а текстовые сообщения без него работают. Флаг нужен,
|
||||
чтобы upload при известном отказе S3 сразу получал 503, не принимая 10 MiB."""
|
||||
|
||||
def __init__(self, store, interval, stale_after, instance_id):
|
||||
self.store = store
|
||||
self.probe_key = HEALTH_PREFIX + instance_id
|
||||
self.interval = interval
|
||||
self.stale_after = stale_after
|
||||
self.last_ok = None
|
||||
self._stop = threading.Event()
|
||||
self._ok_event = threading.Event() # выставлен, пока последняя проверка успешна
|
||||
|
||||
def start(self):
|
||||
threading.Thread(target=self._loop, name="s3-health", daemon=True).start()
|
||||
|
||||
def stop(self):
|
||||
self._stop.set()
|
||||
|
||||
def ok(self):
|
||||
last = self.last_ok
|
||||
return last is not None and time.monotonic() - last <= self.stale_after
|
||||
|
||||
def wait_startup(self, timeout):
|
||||
"""Только на старте реплики (успешной проверки ещё не было): подождать до timeout,
|
||||
пока S3 станет доступен для записи. При подтверждённом отказе — не ждать."""
|
||||
if self.last_ok is None:
|
||||
self._ok_event.wait(timeout)
|
||||
return self.ok()
|
||||
|
||||
def known_down(self):
|
||||
"""S3 был доступен и перестал отвечать. На старте реплики (успешной проверки ещё
|
||||
не было) — False: чтение может работать раньше, чем прогреется запись."""
|
||||
last = self.last_ok
|
||||
return last is not None and time.monotonic() - last > self.stale_after
|
||||
|
||||
def _loop(self):
|
||||
healthy = None
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
self.store.ping(self.probe_key)
|
||||
self.last_ok = time.monotonic()
|
||||
self._ok_event.set()
|
||||
if healthy is not True:
|
||||
log.info("s3 health: ok")
|
||||
healthy = True
|
||||
except Exception as exc:
|
||||
self._ok_event.clear()
|
||||
if healthy is not False:
|
||||
log.warning("s3 health: failing (%s)", type(exc).__name__)
|
||||
healthy = False
|
||||
self._stop.wait(self.interval)
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Идемпотентный bootstrap S3 (однократный compose-job `s3-init`).
|
||||
|
||||
Работает под admin-credentials, которые есть ТОЛЬКО у этого job (API и janitor их не
|
||||
получают). Повторный запуск ничего не ломает:
|
||||
1. ждёт доступности S3 (до 60 с);
|
||||
2. создаёт bucket, если его нет (уже существующий — не ошибка);
|
||||
3. проверяет приватность: анонимные GET объекта и ListBucket должны получить 403.
|
||||
Если bucket вдруг публичен — exit 1, и API не стартует (depends_on).
|
||||
Права пользователей (api: Read+Write, janitor: List+Write) задаются декларативно в
|
||||
secrets/s3_identities.json (генерирует scripts/init-secrets.sh).
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from minio.error import S3Error
|
||||
|
||||
import objstore
|
||||
|
||||
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
log = logging.getLogger("messenger.s3-init")
|
||||
|
||||
|
||||
def anonymous_status(url):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=3) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
# Первый PUT в новый bucket ждёт, пока SeaweedFS выделит volume-ы коллекции: таймаут больше.
|
||||
client = objstore.make_client(read_timeout=30)
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
exists = client.bucket_exists(bucket)
|
||||
break
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("s3 not ready (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
created = False
|
||||
if not exists:
|
||||
try:
|
||||
client.make_bucket(bucket)
|
||||
created = True
|
||||
except S3Error as exc:
|
||||
if exc.code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"):
|
||||
raise
|
||||
# Контрольный объект: на нём проверяем, что анонимный GET не проходит.
|
||||
probe = "bootstrap/probe"
|
||||
for attempt in range(1, 6):
|
||||
try:
|
||||
client.put_object(bucket, probe, io.BytesIO(b"private"), 7, content_type="text/plain")
|
||||
break
|
||||
except Exception as exc:
|
||||
if attempt == 5:
|
||||
raise
|
||||
log.info("probe put failed (%s), retry %d", type(exc).__name__, attempt)
|
||||
time.sleep(2)
|
||||
checks = {
|
||||
"anonymous_get_object": anonymous_status("%s/%s/%s" % (endpoint, bucket, probe)),
|
||||
"anonymous_list_bucket": anonymous_status("%s/%s?list-type=2" % (endpoint, bucket)),
|
||||
}
|
||||
client.remove_object(bucket, probe)
|
||||
private = all(code in (401, 403) for code in checks.values())
|
||||
print(json.dumps({"bucket": bucket, "created": created, "already_existed": exists,
|
||||
"anonymous_http_status": checks, "private": private}), flush=True)
|
||||
return 0 if private else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Пароли (scrypt из стандартной библиотеки) и сессионные токены."""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
|
||||
# Параметры scrypt: N=2^15, r=8, p=1 (~32 МБ памяти и ~0.1 с на проверку).
|
||||
SCRYPT_LOG_N = 15
|
||||
SCRYPT_R = 8
|
||||
SCRYPT_P = 1
|
||||
_MAXMEM = 128 * 1024 * 1024
|
||||
|
||||
|
||||
def _scrypt(password, salt, log_n, r, p):
|
||||
return hashlib.scrypt(password.encode("utf-8"), salt=salt, n=2 ** log_n, r=r, p=p,
|
||||
maxmem=_MAXMEM, dklen=32)
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
"""Возвращает строку scrypt$logN$r$p$salt$hash; plaintext нигде не хранится."""
|
||||
salt = os.urandom(16)
|
||||
digest = _scrypt(password, salt, SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P)
|
||||
return "scrypt$%d$%d$%d$%s$%s" % (
|
||||
SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P,
|
||||
base64.b64encode(salt).decode(), base64.b64encode(digest).decode())
|
||||
|
||||
|
||||
def verify_password(password, stored):
|
||||
try:
|
||||
scheme, log_n, r, p, salt, digest = stored.split("$")
|
||||
if scheme != "scrypt":
|
||||
return False
|
||||
expected = base64.b64decode(digest)
|
||||
actual = _scrypt(password, base64.b64decode(salt), int(log_n), int(r), int(p))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return hmac.compare_digest(actual, expected) # сравнение за постоянное время
|
||||
|
||||
|
||||
# Хеш несуществующего пользователя: неверный логин тратит столько же времени,
|
||||
# сколько неверный пароль, и не выдаёт, существует ли username.
|
||||
DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
|
||||
|
||||
|
||||
def new_token():
|
||||
"""Непрозрачный случайный токен: 32 байта = 256 бит энтропии."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
"""В БД лежит только SHA-256 токена: утечка таблицы не даёт готовых сессий."""
|
||||
return hashlib.sha256(token.encode("utf-8")).digest()
|
||||
+1055
File diff suppressed because it is too large
Load Diff
+380
@@ -0,0 +1,380 @@
|
||||
"""Работа с PostgreSQL: пользователи, чаты, сообщения, сессии, метаданные вложений.
|
||||
|
||||
Источник истины — база данных. В памяти процесса состояния нет, поэтому
|
||||
перезапуск API (и самой БД с сохранённым volume) не теряет данные.
|
||||
"""
|
||||
import datetime as dt
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
log = logging.getLogger("messenger.store")
|
||||
|
||||
EPOCH = dt.datetime(1970, 1, 1, tzinfo=dt.timezone.utc)
|
||||
MIGRATIONS_LOCK_ID = 727001 # произвольный номер advisory-блокировки для миграций
|
||||
|
||||
|
||||
class Conflict(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class UnknownMember(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AttachmentNotFound(Exception):
|
||||
"""Вложение неизвестно, не готово или принадлежит другому чату -> 404."""
|
||||
|
||||
|
||||
def format_ts(value):
|
||||
"""datetime -> RFC 3339 UTC с микросекундами и суффиксом Z."""
|
||||
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
def to_micros(value):
|
||||
delta = value - EPOCH
|
||||
return (delta.days * 86400 + delta.seconds) * 1_000_000 + delta.microseconds
|
||||
|
||||
|
||||
def from_micros(micros):
|
||||
return EPOCH + dt.timedelta(microseconds=micros)
|
||||
|
||||
|
||||
def _user(row):
|
||||
# Пароль/hash и сессионные данные никогда не входят в User.
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _chat(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(m) for m in row["member_ids"]],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def _message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"attachment_ids": [str(a) for a in (row["attachment_ids"] or [])],
|
||||
}
|
||||
|
||||
|
||||
def _attachment(row):
|
||||
# Наружу не отдаются object_key, bucket и внутренние адреса.
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": [],
|
||||
"error_code": None,
|
||||
"created_at": format_ts(row["created_at"]),
|
||||
"updated_at": format_ts(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
ATTACHMENT_COLUMNS = """a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.status, a.object_key, a.created_at, a.updated_at"""
|
||||
|
||||
|
||||
MESSAGE_COLUMNS = """m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
(SELECT array_agg(ma.attachment_id ORDER BY ma.position) FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id) AS attachment_ids"""
|
||||
|
||||
CHAT_COLUMNS = """c.id, c.title, c.created_at,
|
||||
(SELECT array_agg(m.user_id ORDER BY m.position) FROM chat_members m WHERE m.chat_id = c.id) AS member_ids"""
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, conninfo, pool_size=10, pool_timeout=3):
|
||||
# check: перед выдачей соединение проверяется. После перезапуска PostgreSQL
|
||||
# «мёртвые» соединения отбрасываются, и запрос не получает ложный 503.
|
||||
self.pool = ConnectionPool(
|
||||
conninfo, min_size=1, max_size=pool_size, timeout=pool_timeout,
|
||||
kwargs={"row_factory": dict_row}, open=False,
|
||||
check=ConnectionPool.check_connection)
|
||||
|
||||
# --- запуск ---
|
||||
def open(self, wait_seconds=60):
|
||||
"""Ждём готовности БД (она может стартовать дольше API) и открываем пул."""
|
||||
self.pool.open()
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
while True:
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
return
|
||||
except Exception as exc:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
log.info("database is not ready yet (%s), retrying", type(exc).__name__)
|
||||
time.sleep(1)
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
|
||||
def migrate(self, directory):
|
||||
"""Применяет *.sql по порядку имён; каждая миграция — одна транзакция, один раз."""
|
||||
files = sorted(Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
# Advisory-блокировка (сессионная): параллельный повторный запуск job не устроит гонку.
|
||||
conn.autocommit = True
|
||||
conn.execute("SELECT pg_advisory_lock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
try:
|
||||
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())""")
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")}
|
||||
for path in files:
|
||||
if path.name in done:
|
||||
continue
|
||||
# Миграция и её отметка — одна транзакция: либо целиком, либо никак.
|
||||
with conn.transaction():
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,))
|
||||
log.info("migration applied: %s", path.name)
|
||||
finally:
|
||||
conn.execute("SELECT pg_advisory_unlock(%s)", (MIGRATIONS_LOCK_ID,))
|
||||
conn.autocommit = False
|
||||
|
||||
def pending_migrations(self, directory):
|
||||
"""Миграции из каталога образа, ещё не применённые к БД (API их НЕ применяет)."""
|
||||
files = sorted(p.name for p in Path(directory).glob("*.sql"))
|
||||
with self.pool.connection() as conn:
|
||||
exists = conn.execute("SELECT to_regclass('schema_migrations') IS NOT NULL AS ok").fetchone()["ok"]
|
||||
done = {r["version"] for r in conn.execute("SELECT version FROM schema_migrations")} if exists else set()
|
||||
return [f for f in files if f not in done]
|
||||
|
||||
def ping(self):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
|
||||
# --- пользователи ---
|
||||
def create_user(self, username, display_name, password_hash):
|
||||
try:
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, username, display_name, created_at""",
|
||||
(uuid.uuid4(), username, display_name, password_hash)).fetchone()
|
||||
except psycopg.errors.UniqueViolation:
|
||||
# Уникальность гарантирует сама БД — гонка двух регистраций безопасна.
|
||||
raise Conflict()
|
||||
return _user(row)
|
||||
|
||||
def get_credentials(self, username):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,)).fetchone()
|
||||
if row is None:
|
||||
return None, None
|
||||
return _user(row), row["password_hash"]
|
||||
|
||||
# --- сессии ---
|
||||
def create_session(self, user_id, token_hash, ttl_seconds):
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO sessions (token_hash, user_id, created_at, expires_at)
|
||||
VALUES (%s, %s, now(), now() + make_interval(secs => %s))
|
||||
RETURNING expires_at""",
|
||||
(token_hash, user_id, ttl_seconds)).fetchone()
|
||||
return format_ts(row["expires_at"])
|
||||
|
||||
def get_session_user(self, token_hash):
|
||||
"""Пользователь действующей сессии или None (неизвестна/истекла/отозвана)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""SELECT u.id, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.revoked_at IS NULL AND s.expires_at > now()""",
|
||||
(token_hash,)).fetchone()
|
||||
return _user(row) if row else None
|
||||
|
||||
def revoke_session(self, token_hash):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"UPDATE sessions SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
(token_hash,))
|
||||
|
||||
# --- чаты ---
|
||||
def create_chat(self, title, member_ids):
|
||||
"""Чат и его участники создаются в одной транзакции (атомарно)."""
|
||||
chat_id = uuid.uuid4()
|
||||
with self.pool.connection() as conn:
|
||||
found = conn.execute(
|
||||
"SELECT count(*) AS n FROM users WHERE id = ANY(%s::uuid[])", (member_ids,)).fetchone()["n"]
|
||||
if found != len(member_ids):
|
||||
raise UnknownMember()
|
||||
conn.execute(
|
||||
"INSERT INTO chats (id, title, created_at) VALUES (%s, %s, clock_timestamp())",
|
||||
(chat_id, title))
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id, position) VALUES (%s, %s, %s)",
|
||||
[(chat_id, m, i) for i, m in enumerate(member_ids)])
|
||||
row = conn.execute("SELECT " + CHAT_COLUMNS + " FROM chats c WHERE c.id = %s", (chat_id,)).fetchone()
|
||||
return _chat(row)
|
||||
|
||||
def get_chat_for(self, user_id, chat_id):
|
||||
"""Чат, если пользователь — участник; иначе None (чужой и несуществующий неразличимы)."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)""",
|
||||
(chat_id, user_id)).fetchone()
|
||||
return _chat(row) if row else None
|
||||
|
||||
def list_chats(self, user_id, after, limit):
|
||||
params = [user_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (c.created_at, c.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1) # +1 запись: узнаём, есть ли следующая страница
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + CHAT_COLUMNS + """ FROM chats c
|
||||
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
|
||||
WHERE true """ + where + " ORDER BY c.created_at, c.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _chat)
|
||||
|
||||
# --- сообщения ---
|
||||
def add_message(self, user_id, chat_id, text, attachment_ids, idem_key, request_hash, idem_ttl_seconds):
|
||||
"""Идемпотентная отправка. Возвращает (message, replayed) или None, если чата нет/он чужой.
|
||||
|
||||
Всё в ОДНОЙ транзакции: проверка доступа, поиск ключа, вставка сообщения и запись
|
||||
ключа. Либо фиксируется и сообщение, и ключ, либо ничего (транзиентная ошибка
|
||||
не запоминается как результат — клиент повторит с тем же ключом).
|
||||
Конкурентные запросы с одним ключом через разные реплики сериализуются
|
||||
блокировкой строки чата (FOR UPDATE), второй после COMMIT первого видит ключ.
|
||||
PK таблицы ключей — страховка: даже без блокировки дубль не зафиксируется.
|
||||
Lab4: в той же транзакции проверяется, что все attachment_ids — ready-вложения
|
||||
ЭТОГО чата (FOR SHARE: строка не исчезнет до COMMIT), и пишутся ссылки.
|
||||
"""
|
||||
with self.pool.connection() as conn:
|
||||
# FOR UPDATE по строке чата: вставки в один чат идут по очереди, поэтому
|
||||
# created_at растёт в порядке фиксации и keyset-курсор не пропускает записи.
|
||||
allowed = conn.execute(
|
||||
"""SELECT 1 FROM chats c WHERE c.id = %s AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = c.id AND m.user_id = %s)
|
||||
FOR UPDATE OF c""", (chat_id, user_id)).fetchone()
|
||||
if allowed is None:
|
||||
return None
|
||||
existing = conn.execute(
|
||||
"""SELECT k.request_hash, k.expires_at > now() AS alive, """ + MESSAGE_COLUMNS + """
|
||||
FROM idempotency_keys k JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id = %s AND k.chat_id = %s AND k.idem_key = %s""",
|
||||
(user_id, chat_id, idem_key)).fetchone()
|
||||
if existing is not None:
|
||||
if existing["alive"]:
|
||||
if bytes(existing["request_hash"]) != request_hash:
|
||||
raise Conflict()
|
||||
return _message(existing), True
|
||||
# Ключ старше TTL (24 ч) — освобождаем его и обрабатываем как новый.
|
||||
conn.execute(
|
||||
"DELETE FROM idempotency_keys WHERE user_id = %s AND chat_id = %s AND idem_key = %s",
|
||||
(user_id, chat_id, idem_key))
|
||||
if attachment_ids:
|
||||
found = conn.execute(
|
||||
"""SELECT id FROM attachments
|
||||
WHERE id = ANY(%s::uuid[]) AND chat_id = %s AND status = 'ready'
|
||||
FOR SHARE""", (attachment_ids, chat_id)).fetchall()
|
||||
if len(found) != len(attachment_ids):
|
||||
# Чужой чат, неизвестный или незавершённый id — одинаково 404.
|
||||
raise AttachmentNotFound()
|
||||
row = conn.execute(
|
||||
"""INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES (%s, %s, %s, %s, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||||
(uuid.uuid4(), chat_id, user_id, text)).fetchone()
|
||||
if attachment_ids:
|
||||
with conn.cursor() as cur:
|
||||
cur.executemany(
|
||||
"""INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s)""",
|
||||
[(row["id"], a, i) for i, a in enumerate(attachment_ids)])
|
||||
row = dict(row, attachment_ids=list(attachment_ids))
|
||||
conn.execute(
|
||||
"""INSERT INTO idempotency_keys (user_id, chat_id, idem_key, request_hash, message_id, expires_at)
|
||||
VALUES (%s, %s, %s, %s, %s, now() + make_interval(secs => %s))""",
|
||||
(user_id, chat_id, idem_key, request_hash, row["id"], idem_ttl_seconds))
|
||||
return _message(row), False
|
||||
|
||||
def list_messages(self, chat_id, after, limit):
|
||||
params = [chat_id]
|
||||
where = ""
|
||||
if after:
|
||||
where = "AND (m.created_at, m.id) > (%s, %s::uuid)"
|
||||
params += [from_micros(after[0]), after[1]]
|
||||
params.append(limit + 1)
|
||||
with self.pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT " + MESSAGE_COLUMNS + " FROM messages m WHERE m.chat_id = %s "
|
||||
+ where + " ORDER BY m.created_at, m.id LIMIT %s", params).fetchall()
|
||||
return self._page(rows, limit, _message)
|
||||
|
||||
# --- вложения ---
|
||||
def create_pending_attachment(self, att_id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, width, height, object_key):
|
||||
"""Шаг 1 из 3: намерение записывается и фиксируется ДО S3 PUT.
|
||||
Если дальше что-то упадёт, janitor найдёт pending-строку и удалит объект."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(
|
||||
"""INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, width, height, object_key, status, created_at, updated_at)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'pending', now(), now())""",
|
||||
(att_id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
width, height, object_key))
|
||||
|
||||
def mark_attachment_ready(self, att_id):
|
||||
"""Шаг 3 из 3 (после S3 PUT). None, если строку уже убрал janitor."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"""UPDATE attachments a SET status = 'ready', updated_at = now()
|
||||
WHERE a.id = %s AND a.status = 'pending'
|
||||
RETURNING """ + ATTACHMENT_COLUMNS, (att_id,)).fetchone()
|
||||
return _attachment(row) if row else None
|
||||
|
||||
def delete_pending_attachment(self, att_id):
|
||||
"""Компенсация: убрать незавершённое намерение (объект в S3 удалён/не создан)."""
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("DELETE FROM attachments WHERE id = %s AND status = 'pending'", (att_id,))
|
||||
|
||||
def get_attachment_for(self, user_id, att_id):
|
||||
"""(attachment, object_key) для участника чата; иначе None. Pending не виден."""
|
||||
with self.pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT " + ATTACHMENT_COLUMNS + """ FROM attachments a
|
||||
WHERE a.id = %s AND a.status = 'ready' AND EXISTS (
|
||||
SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = %s)""",
|
||||
(att_id, user_id)).fetchone()
|
||||
return (_attachment(row), row["object_key"]) if row else None
|
||||
|
||||
@staticmethod
|
||||
def _page(rows, limit, convert):
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
last = (to_micros(rows[-1]["created_at"]), str(rows[-1]["id"])) if rows and has_more else None
|
||||
return [convert(r) for r in rows], last
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload -> остановка ИМЕННО обслужившей upload реплики -> download через другую.
|
||||
|
||||
python3 student-tests/attachment_failover.py [--output evidence/attachment-failover.json]
|
||||
|
||||
Для каждой API-реплики по очереди: загрузить файл так, чтобы его обслужила эта реплика
|
||||
(round-robin LB, повторяем до попадания), остановить её scripts/stop-one.sh
|
||||
(SIGTERM, контейнер остаётся остановленным), затем 5 раз скачать оригинал через LB и
|
||||
проверить SHA-256 и что отвечает уже другая реплика. Восстановление — scripts/start-all.sh.
|
||||
Доказывает, что на API нет обязательного локального файла оригинала.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
CONTENT = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
instances = set()
|
||||
for _ in range(10):
|
||||
instances.add(c.call("GET", "/health/ready")["headers"]["X-Instance-Id"])
|
||||
check(len(instances) >= 2, "need >=2 replicas")
|
||||
rounds = []
|
||||
for target in sorted(instances):
|
||||
for _ in range(20): # round-robin: попадаем в нужную реплику за пару попыток
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=failover.png" % chat["id"], 201, actor=alice,
|
||||
raw=CONTENT, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
if r["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise SystemExit("could not hit replica " + target)
|
||||
att = r["json"]
|
||||
stop = subprocess.run([str(ROOT / "scripts/stop-one.sh")], env=dict(os.environ, TARGET_INSTANCE_ID=target),
|
||||
capture_output=True, text=True, timeout=60)
|
||||
check(stop.returncode == 0, "stop-one failed")
|
||||
downloads = []
|
||||
for _ in range(5):
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
|
||||
downloads.append({"instance": d["headers"]["X-Instance-Id"],
|
||||
"sha256_ok": hashlib.sha256(d["bytes"]).hexdigest() == att["sha256"] == hashlib.sha256(CONTENT).hexdigest(),
|
||||
"ms": round(d["elapsed"] * 1000, 1)})
|
||||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
ok = all(x["sha256_ok"] and x["instance"] != target for x in downloads) and meta["status"] == "ready"
|
||||
rounds.append({"uploaded_by": target, "stopped": target, "downloads": downloads, "pass": ok})
|
||||
print(json.dumps(rounds[-1]), flush=True)
|
||||
subprocess.run([str(ROOT / "scripts/start-all.sh")], capture_output=True, timeout=120, check=True)
|
||||
time.sleep(4) # HAProxy: rise 2 * inter 1s
|
||||
summary = {"replicas": sorted(instances), "rounds": rounds, "pass": all(r["pass"] for r in rounds)}
|
||||
print(json.dumps({"pass": summary["pass"], "rounds": len(rounds)}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (уровень 4). Запуск на учебном стенде:
|
||||
|
||||
python3 student-tests/attachments_negative.py [--base-url http://localhost:8080] [--output evidence/attachments-negative.json]
|
||||
|
||||
Использует публичный tests/client.py: каждый ответ проверяется на код, X-Request-Id,
|
||||
X-Instance-Id и (для ошибок) формат {"error":{code,message,request_id}}. Отдельно
|
||||
проверяется, что ни один пользовательский ввод не дал 5xx. Все файлы синтетические и
|
||||
генерируются на лету (большие в Git не хранятся).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
JPEG = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes()
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
results = []
|
||||
|
||||
|
||||
def chunk(ctype, data):
|
||||
return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width, height, raw, color_type=2, depth=8):
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", raw) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Несжимаемый RGB PNG размером чуть меньше target_bytes (zlib level 0)."""
|
||||
width = 1024
|
||||
row = 1 + width * 3
|
||||
height = (target_bytes - 200) // (row + 6 * 0 + 1)
|
||||
while True:
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
data = png(width, height, zlib.compress(raw, 0))
|
||||
if len(data) <= target_bytes:
|
||||
return data
|
||||
height -= 16
|
||||
|
||||
|
||||
class Suite:
|
||||
def __init__(self, c):
|
||||
self.c = c
|
||||
|
||||
def case(self, name, method, path, expected, actor=None, **kw):
|
||||
try:
|
||||
r = self.c.call(method, path, expected, actor=actor, **kw)
|
||||
code = r["json"]["error"]["code"] if r["json"] and "error" in r["json"] else None
|
||||
results.append({"case": name, "expected": expected, "status": r["status"], "error_code": code, "pass": True})
|
||||
return r
|
||||
except Failure as exc:
|
||||
results.append({"case": name, "expected": expected, "error": str(exc), "pass": False})
|
||||
return None
|
||||
|
||||
def upload(self, name, actor, chat, data, expected, ctype="image/png", filename="f.png", raw_query=None):
|
||||
q = raw_query if raw_query is not None else "filename=" + quote(filename, safe="")
|
||||
return self.case(name, "POST", "/api/v1/chats/%s/attachments?%s" % (chat["id"], q), expected,
|
||||
actor=actor, raw=data, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=60)
|
||||
s = Suite(c)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "второй чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
||||
eve_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "чат Евы", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
|
||||
# --- позитивные контрольные ---
|
||||
ok_png = s.upload("valid PNG fixture", alice, chat, PNG, 201)
|
||||
ok_jpg = s.upload("valid JPEG", bob, chat, JPEG, 201, ctype="image/jpeg", filename="photo.jpg")
|
||||
uni = s.upload("unicode filename", alice, chat, PNG, 201, filename="фото отпуска 🙂.png")
|
||||
if uni:
|
||||
check(uni["json"]["filename"] == "фото отпуска 🙂.png", "unicode filename changed")
|
||||
if ok_jpg:
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % ok_jpg["json"]["id"], actor=alice)
|
||||
check(d["bytes"] == JPEG and d["headers"].get_content_type() == "image/jpeg", "jpeg download mismatch")
|
||||
check(d["headers"].get("X-Content-Type-Options") == "nosniff", "nosniff missing")
|
||||
near = noise_png(MAX_BYTES)
|
||||
big = s.upload("PNG near 10 MiB limit (%d B)" % len(near), alice, chat, near, 201, filename="big.png")
|
||||
if big:
|
||||
check(big["json"]["sha256"] == hashlib.sha256(near).hexdigest(), "big sha mismatch")
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % big["json"]["id"], actor=bob)
|
||||
check(hashlib.sha256(d["bytes"]).hexdigest() == big["json"]["sha256"], "big download mismatch")
|
||||
|
||||
# --- размер и пиксели ---
|
||||
s.upload("too large: 10 MiB + 1 B", alice, chat, near + b"\0" * (MAX_BYTES + 1 - len(near)), 413)
|
||||
s.upload("pixel bomb header 100000x100000", alice, chat, png(100000, 100000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("PNG 7000x6000 = 42 Mpx (> 40 Mpx)", alice, chat, png(7000, 6000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("zlib bomb: 100x100 header, 50 MB inflated", alice, chat,
|
||||
png(100, 100, zlib.compress(b"\0" * 50_000_000, 9), color_type=0), 415)
|
||||
|
||||
# --- повреждённые изображения ---
|
||||
flipped = bytearray(PNG); flipped[5000] ^= 0xFF
|
||||
s.upload("corrupted PNG (byte flipped, bad CRC)", alice, chat, bytes(flipped), 415)
|
||||
s.upload("truncated PNG", alice, chat, PNG[:-4000], 415)
|
||||
s.upload("PNG without IEND", alice, chat, PNG[:-12], 415)
|
||||
s.upload("PNG with appended ZIP (polyglot)", alice, chat, PNG + b"PK\x03\x04" + os.urandom(64), 415)
|
||||
s.upload("truncated JPEG", alice, chat, JPEG[:len(JPEG) // 2], 415, ctype="image/jpeg")
|
||||
s.upload("JPEG header only", alice, chat, JPEG[:200], 415, ctype="image/jpeg")
|
||||
s.upload("empty body", alice, chat, b"", 415)
|
||||
|
||||
# --- подмена MIME ---
|
||||
s.upload("JPEG bytes declared image/png", alice, chat, JPEG, 415)
|
||||
s.upload("PNG bytes declared image/jpeg", alice, chat, PNG, 415, ctype="image/jpeg")
|
||||
s.upload("text declared image/png", alice, chat, b"<html><script>alert(1)</script></html>" * 4, 415)
|
||||
s.upload("GIF declared image/png", alice, chat, b"GIF89a" + os.urandom(200), 415)
|
||||
s.upload("PNG declared text/html", alice, chat, PNG, 415, ctype="text/html")
|
||||
s.upload("PNG declared image/svg+xml", alice, chat, PNG, 415, ctype="image/svg+xml")
|
||||
s.upload("multipart/form-data instead of raw", alice, chat, b"--x\r\n\r\n" + PNG + b"\r\n--x--", 415,
|
||||
ctype="multipart/form-data; boundary=x")
|
||||
|
||||
# --- опасные filename ---
|
||||
for label, query in (("../etc/passwd", "filename=" + quote("../passwd.png", safe="")),
|
||||
("slash", "filename=" + quote("a/b.png", safe="")),
|
||||
("backslash", "filename=" + quote("a\\b.png", safe="")),
|
||||
("NUL", "filename=a%00.png"),
|
||||
("newline", "filename=a%0A.png"),
|
||||
("bidi override U+202E", "filename=" + quote("gnp.exe", safe="")),
|
||||
("..", "filename=.."),
|
||||
("empty", "filename="),
|
||||
("whitespace only", "filename=%20%20"),
|
||||
("256 code points", "filename=" + quote("я" * 256, safe="")),
|
||||
("missing filename", ""),
|
||||
("filename twice", "filename=a.png&filename=b.png"),
|
||||
("invalid UTF-8", "filename=%FF%FE.png")):
|
||||
s.upload("filename: " + label, alice, chat, PNG, 400, raw_query=query)
|
||||
|
||||
# --- доступ и чужие объекты ---
|
||||
eve_att = s.upload("eve uploads to her own chat", eve, eve_chat, PNG, 201)
|
||||
s.upload("non-member uploads to alice chat", eve, chat, PNG, 404)
|
||||
s.case("upload without session", "POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 401,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
s.upload("upload to unknown chat", alice, {"id": str(uuid.uuid4())}, PNG, 404)
|
||||
if eve_att and ok_png:
|
||||
eid, aid = eve_att["json"]["id"], ok_png["json"]["id"]
|
||||
s.case("foreign attachment metadata", "GET", "/api/v1/attachments/" + eid, 404, actor=alice)
|
||||
s.case("foreign attachment content", "GET", "/api/v1/attachments/%s/content" % eid, 404, actor=alice)
|
||||
s.case("eve reads alice attachment", "GET", "/api/v1/attachments/%s/content" % aid, 404, actor=eve)
|
||||
key = lambda: {"Idempotency-Key": uuid.uuid4().hex} # noqa: E731
|
||||
s.case("message with foreign attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [eid]}, headers=key())
|
||||
s.case("message mixing own and foreign ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid, eid]}, headers=key())
|
||||
s.case("attachment of OTHER chat of the same user", "POST", "/api/v1/chats/%s/messages" % chat2["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid]}, headers=key())
|
||||
s.case("unknown attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4())]}, headers=key())
|
||||
s.case("malformed attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": ["not-a-uuid"]}, headers=key())
|
||||
s.case("duplicate attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [aid, aid]}, headers=key())
|
||||
s.case("11 attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, headers=key())
|
||||
s.case("attachment_ids not a list", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": aid}, headers=key())
|
||||
s.case("empty text without attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
||||
actor=alice, body={"text": " "}, headers=key())
|
||||
m = s.case("empty text with attachment (bob links alice's file)", "POST",
|
||||
"/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob,
|
||||
body={"text": "", "attachment_ids": [aid]}, headers=key(), schema="Message")
|
||||
if m:
|
||||
check(m["json"]["attachment_ids"] == [aid], "attachment_ids lost")
|
||||
k = key()
|
||||
s.case("idempotent send with attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"attachment_ids": [aid], "text": "повтор"}, headers=k, schema="Message")
|
||||
s.case("same key, same body (key order changed)", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": [aid]}, headers=k, schema="Message")
|
||||
s.case("same key, different attachment_ids -> 409", "POST", "/api/v1/chats/%s/messages" % chat["id"], 409,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": []}, headers=k)
|
||||
s.case("variant=thumbnail (no variants in lab4)", "GET",
|
||||
"/api/v1/attachments/%s/content?variant=thumbnail" % aid, 404, actor=bob)
|
||||
s.case("variant=bogus", "GET", "/api/v1/attachments/%s/content?variant=bogus" % aid, 400, actor=bob)
|
||||
s.case("variant=original", "GET", "/api/v1/attachments/%s/content?variant=original" % aid, 200, actor=bob)
|
||||
s.case("malformed attachment id in path", "GET", "/api/v1/attachments/zzz", 400, actor=bob)
|
||||
s.case("unknown attachment id", "GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=bob)
|
||||
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
server_errors = [r for r in results if r.get("status", 0) >= 500]
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-55s -> %s %s" % (
|
||||
r["case"], r.get("status", "-"), r.get("error_code") or r.get("error", "")))
|
||||
summary = {"cases": len(results), "failed": len(failed), "server_errors_5xx": len(server_errors),
|
||||
"pass": not failed and not server_errors}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"summary": summary, "results": results}, ensure_ascii=False, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказы между записью в S3 и PostgreSQL и очистка janitor (уровень 4).
|
||||
|
||||
Требует API с FAULT_INJECTION=1 (учебный хук, по умолчанию выключен):
|
||||
FAULT_INJECTION=1 docker compose --env-file .env up -d --no-deps --wait api
|
||||
python3 student-tests/consistency_faults.py --output evidence/consistency-faults.json
|
||||
docker compose --env-file .env up -d --no-deps --wait api # вернуть FAULT_INJECTION=0
|
||||
|
||||
Сценарии (каждый — реальный HTTP upload через LB):
|
||||
db-fail-after-s3-put PUT прошёл, «COMMIT» ready упал -> 503; компенсация удаляет объект
|
||||
и pending-строку -> ничего не остаётся;
|
||||
crash-after-s3-put процесс API умирает (os._exit) после PUT -> pending + объект;
|
||||
crash-after-pending процесс умирает до PUT -> pending без объекта;
|
||||
обрыв клиента Content-Length 5 MiB, отправлен 1 MiB, сокет закрыт -> ничего;
|
||||
orphan pending-строку удаляем вручную -> объект без строки;
|
||||
missing объект ready-вложения удаляем в S3 -> только отчёт, download = 503.
|
||||
Затем janitor: dry-run и боевой проход с grace 3600 (свежее не трогает), ожидание
|
||||
grace-seconds, dry-run -> боевой -> повторный (идемпотентность). Контрольное ready-вложение
|
||||
должно остаться доступным побайтно.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
log = []
|
||||
|
||||
|
||||
def sh(*cmd, timeout=120):
|
||||
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit("command failed: %s\n%s" % (" ".join(cmd[:4]), r.stderr[-500:]))
|
||||
return r.stdout
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return sh("docker", "compose", "exec", "-T", "db", "sh", "-c",
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tAc "$0"', sql).strip()
|
||||
|
||||
|
||||
def janitor(grace, dry_run):
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "janitor", "python", "/app/src/janitor.py",
|
||||
"--once", "--grace-seconds", str(grace)] + (["--dry-run"] if dry_run else [])
|
||||
out = sh(*cmd)
|
||||
report = json.loads([line for line in out.splitlines() if line.startswith("{")][-1])
|
||||
keep = ("dry_run", "grace_seconds", "rows_by_status", "objects_total", "abandoned_pending",
|
||||
"orphan_objects", "missing_objects", "deleted_objects", "deleted_rows", "errors", "duration_ms")
|
||||
return {k: report.get(k) for k in keep}
|
||||
|
||||
|
||||
def step(name, **data):
|
||||
entry = dict(step=name, t=round(time.time(), 1), **data)
|
||||
log.append(entry)
|
||||
print(json.dumps(entry, ensure_ascii=False), flush=True)
|
||||
return entry
|
||||
|
||||
|
||||
def wait_api_healthy():
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
states = sh("docker", "compose", "ps", "-a", "--format", "{{.Health}}", "api").split()
|
||||
if states and all(s == "healthy" for s in states):
|
||||
time.sleep(3) # HAProxy rise
|
||||
return
|
||||
time.sleep(1)
|
||||
raise SystemExit("api did not become healthy")
|
||||
|
||||
|
||||
def upload(c, actor, chat, fault=None, expected=201):
|
||||
h = {"Content-Type": "image/png"}
|
||||
if fault:
|
||||
h["X-Fault-Inject"] = fault
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=f.png" % chat["id"], expected,
|
||||
actor=actor, raw=PNG, headers=h, schema="Attachment" if expected == 201 else None)
|
||||
return r["status"], r["json"]
|
||||
except Exception as exc: # обрыв соединения при crash-* тоже допустимый исход
|
||||
return type(exc).__name__, str(exc)[:120]
|
||||
|
||||
|
||||
def interrupted_upload(base, token, chat_id):
|
||||
host, port = base.split("//")[1].split(":")
|
||||
s = socket.create_connection((host, int(port)), timeout=10)
|
||||
s.sendall(("POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: %d\r\n\r\n"
|
||||
% (chat_id, host, token, 5 * 1024 * 1024)).encode())
|
||||
s.sendall(PNG[:8] + b"\0" * (1024 * 1024 - 8))
|
||||
s.close() # клиент «пропал» на середине
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--grace-seconds", type=int, default=20)
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
env = sh("docker", "compose", "exec", "-T", "api", "printenv", "FAULT_INJECTION").strip()
|
||||
check(env == "1", "start api with FAULT_INJECTION=1 first (see docstring)")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
started = psql("SELECT now()")
|
||||
base = janitor(3600, True)
|
||||
step("baseline janitor dry-run", report=base)
|
||||
|
||||
_, control = upload(c, alice, chat)
|
||||
_, victim = upload(c, alice, chat)
|
||||
step("control + victim uploaded (ready)", control=control["id"], victim=victim["id"])
|
||||
|
||||
st, body = upload(c, alice, chat, "db-fail-after-s3-put", expected=503)
|
||||
after_comp = janitor(3600, True)
|
||||
step("db-fail-after-s3-put -> compensation", status=st, report=after_comp,
|
||||
leftover_pending=after_comp["rows_by_status"].get("pending", 0) - base["rows_by_status"].get("pending", 0),
|
||||
leftover_objects=after_comp["objects_total"] - base["objects_total"] - 2)
|
||||
|
||||
for fault in ("crash-after-s3-put", "crash-after-s3-put", "crash-after-pending"):
|
||||
st, body = upload(c, alice, chat, fault, expected=[502, 503])
|
||||
step(fault, client_saw=st)
|
||||
wait_api_healthy()
|
||||
|
||||
interrupted_upload(args.base_url, alice["token"], chat["id"])
|
||||
time.sleep(2)
|
||||
step("client aborted upload at 1 of 5 MiB", report=janitor(3600, True))
|
||||
|
||||
pending = psql("SELECT id || ' ' || (object_key IS NOT NULL) FROM attachments WHERE status='pending' "
|
||||
"AND created_at >= '%s' ORDER BY created_at" % started).splitlines()
|
||||
step("pending rows left by crashes", pending=len(pending))
|
||||
check(len(pending) == 3, "expected 3 pending rows from crashes")
|
||||
orphan_id = pending[0].split()[0]
|
||||
psql("DELETE FROM attachments WHERE id = '%s'" % orphan_id)
|
||||
step("orphan injected: pending row deleted, object kept", row=orphan_id)
|
||||
victim_key = psql("SELECT object_key FROM attachments WHERE id = '%s'" % victim["id"])
|
||||
sh("docker", "compose", "--profile", "tools", "run", "--rm", "--entrypoint", "python", "s3-check", "-c",
|
||||
"import sys; sys.argv=['x']; exec(open('/app/student-tests/s3_private_check.py').read().split('results = []')[0]);"
|
||||
"client('api').remove_object(BUCKET, %r)" % victim_key)
|
||||
dl = c.call("GET", "/api/v1/attachments/%s/content" % victim["id"], 503, actor=bob)
|
||||
step("missing injected: victim object deleted in S3", download_status=dl["status"])
|
||||
|
||||
fresh_dry = janitor(3600, True)
|
||||
fresh_run = janitor(3600, False)
|
||||
step("janitor grace=3600 (all fresh): dry-run", report=fresh_dry)
|
||||
step("janitor grace=3600 (all fresh): real run deletes nothing", report=fresh_run)
|
||||
check(fresh_run["deleted_objects"] == 0 and fresh_run["deleted_rows"] == 0, "fresh data deleted")
|
||||
|
||||
time.sleep(args.grace_seconds + 2)
|
||||
dry = janitor(args.grace_seconds, True)
|
||||
step("after grace: dry-run", report=dry)
|
||||
real = janitor(args.grace_seconds, False)
|
||||
step("after grace: real run", report=real)
|
||||
again = janitor(args.grace_seconds, False)
|
||||
step("after grace: repeated run (idempotent)", report=again)
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % control["id"], actor=bob)
|
||||
control_ok = hashlib.sha256(d["bytes"]).hexdigest() == control["sha256"]
|
||||
still = psql("SELECT count(*) FROM attachments WHERE status='pending' AND created_at >= '%s'" % started)
|
||||
step("control attachment still intact", sha256_ok=control_ok, pending_left=int(still))
|
||||
|
||||
ok = (log[2]["leftover_pending"] == 0 and log[2]["leftover_objects"] == 0
|
||||
and dry["abandoned_pending"] >= 2 and dry["orphan_objects"] >= 1 and dry["missing_objects"] >= 1
|
||||
and dry["deleted_objects"] == 0
|
||||
and real["deleted_rows"] >= 2 and again["abandoned_pending"] == 0 and again["orphan_objects"] == 0
|
||||
and again["deleted_objects"] == 0 and again["missing_objects"] >= 1
|
||||
and control_ok and int(still) == 0)
|
||||
print(json.dumps({"pass": ok}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"pass": ok, "steps": log}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка диапазона дат cursor: некорректная дата должна давать 400, а не 500."""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, ca_file=args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
checks = 0
|
||||
for kind, scope, path in (
|
||||
("messages", chat["id"], "/api/v1/chats/" + chat["id"] + "/messages"),
|
||||
("chats", alice["id"], "/api/v1/chats"),
|
||||
):
|
||||
for timestamp, expected in ((-10**17, 400), (-62135596800000001, 400), (0, 200)):
|
||||
payload = {"k": kind, "s": scope, "t": timestamp, "i": str(uuid.uuid4())}
|
||||
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
client.call("GET", path + "?cursor=" + quote(cursor, safe=""), expected, actor=alice)
|
||||
checks += 1
|
||||
print("PASS: %d cursor date boundary checks; invalid dates return 400." % checks)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказ/замена API-реплики ПОД НАГРУЗКОЙ: RPS, ошибки, время обнаружения и восстановления (lab3, уровень 4).
|
||||
|
||||
Что делает:
|
||||
* CONCURRENCY потоков в closed-loop шлют смесь запросов через LB: POST сообщения
|
||||
(с Idempotency-Key) и GET истории (limit=20) в пропорции 1:1;
|
||||
* после неуспешного/неопределённого POST поток повторяет ТОТ ЖЕ ключ и тело (как
|
||||
требует контракт), поэтому подтверждённых дублей быть не должно;
|
||||
* на секунде --action-at запускается --action (например, docker stop/kill контейнера
|
||||
или scripts/rolling-update.sh), его stdout/stderr пишутся в отдельный лог;
|
||||
* параллельно каждые 200 мс опрашивается CSV статистики HAProxy: фиксируются моменты
|
||||
UP -> DOWN / DOWN -> UP серверов backend (время обнаружения отказа LB);
|
||||
* в конце читается вся история чата (тем же токеном) и проверяется: все подтверждённые
|
||||
сообщения на месте, дублей нет.
|
||||
|
||||
Метрики (все времена — от старта action):
|
||||
errors_total / error_rate — неуспешные попытки (HTTP != ожидаемого, timeout, разрыв);
|
||||
error_window_s — от первой до последней ошибки после старта action;
|
||||
recovery_s — конец окна ошибок (дальше все запросы успешны), 0 если ошибок нет;
|
||||
post_action_ok_rps/capacity_ratio — успешный RPS после действия и его доля от базового;
|
||||
lb_down_detected_s — когда HAProxy пометил сервер DOWN;
|
||||
target_last_seen_s — последний ответ от остановленной реплики.
|
||||
|
||||
Ограничения: closed-loop генератор (coordinated omission), клиент на том же хосте, что и
|
||||
стенд; цифры RPS сравнимы только между прогонами этого же скрипта на этом же ноутбуке.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
TIMEOUT = 2.0
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
s = sorted(values)
|
||||
return round(s[min(len(s) - 1, int(round(p / 100 * (len(s) - 1))))] * 1000, 1)
|
||||
|
||||
|
||||
class Bench:
|
||||
def __init__(self, a):
|
||||
self.a = a
|
||||
self.base = a.base_url.rstrip("/")
|
||||
self.lock = threading.Lock()
|
||||
self.t0 = None
|
||||
self.stop = threading.Event()
|
||||
self.per_sec = defaultdict(lambda: {"ok": 0, "err": 0, "inst": Counter(), "ver": Counter()})
|
||||
self.errors = [] # (t, kind)
|
||||
self.lat = [] # успешные задержки, с
|
||||
self.confirmed = {} # message id -> text
|
||||
self.retried_posts = 0
|
||||
self.lb_events = []
|
||||
self.inst_last_seen = {}
|
||||
|
||||
def now(self):
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def record(self, ok, dt, inst=None, ver=None, kind=None):
|
||||
t = self.now()
|
||||
with self.lock:
|
||||
b = self.per_sec[int(t)]
|
||||
if ok:
|
||||
b["ok"] += 1
|
||||
self.lat.append(dt)
|
||||
if inst:
|
||||
b["inst"][inst] += 1
|
||||
self.inst_last_seen[inst] = t
|
||||
if ver:
|
||||
b["ver"][ver] += 1
|
||||
else:
|
||||
b["err"] += 1
|
||||
self.errors.append((round(t, 3), kind))
|
||||
|
||||
def request(self, method, path, body=None, headers=None, expected=200):
|
||||
h = {"Authorization": "Bearer " + self.token}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(self.base + path, data=data, method=method, headers=h)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
payload = json.loads(r.read())
|
||||
ok = r.status == expected
|
||||
self.record(ok, time.monotonic() - start, r.headers.get("X-Instance-Id"),
|
||||
r.headers.get("X-App-Version"), None if ok else "http_%d" % r.status)
|
||||
return payload if ok else None
|
||||
except urllib.error.HTTPError as e:
|
||||
self.record(False, 0, kind="http_%d" % e.code)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.record(False, 0, kind=type(e).__name__)
|
||||
return None
|
||||
|
||||
def worker(self, n):
|
||||
chat_path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
key = text = None
|
||||
i = 0
|
||||
while not self.stop.is_set():
|
||||
i += 1
|
||||
if i % 2:
|
||||
if key is None: # новый логический запрос; после ошибки ключ НЕ меняется
|
||||
key = "bench-%d-%s" % (n, uuid.uuid4().hex)
|
||||
text = "Нагрузка " + key
|
||||
else:
|
||||
with self.lock:
|
||||
self.retried_posts += 1
|
||||
msg = self.request("POST", chat_path, {"text": text}, {"Idempotency-Key": key}, 201)
|
||||
if msg is not None:
|
||||
with self.lock:
|
||||
self.confirmed[msg["id"]] = msg["text"]
|
||||
key = None
|
||||
else:
|
||||
self.request("GET", chat_path + "?limit=20")
|
||||
|
||||
def poll_lb(self):
|
||||
prev = {}
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
with urllib.request.urlopen(self.a.stats_url, timeout=1) as r:
|
||||
rows = list(csv.reader(io.StringIO(r.read().decode().lstrip("# "))))
|
||||
head = rows[0]
|
||||
ix = {k: head.index(k) for k in ("pxname", "svname", "status", "addr")}
|
||||
for row in rows[1:]:
|
||||
if len(row) <= ix["addr"] or row[ix["pxname"]] != "be_api" or row[ix["svname"]] == "BACKEND":
|
||||
continue
|
||||
sv, st, addr = row[ix["svname"]], row[ix["status"]].split(" ")[0], row[ix["addr"]]
|
||||
if sv in prev and prev[sv] != (st, addr):
|
||||
self.lb_events.append({"t": round(self.now(), 2), "server": sv, "addr": addr,
|
||||
"from": prev[sv][0], "to": st})
|
||||
prev[sv] = (st, addr)
|
||||
except Exception: # noqa: BLE001 — статистика вспомогательная
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
def history(self):
|
||||
c, path, items = self.client, "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100", []
|
||||
while True:
|
||||
page = c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
if page["next_cursor"] is None:
|
||||
return items
|
||||
path = "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
def run(self):
|
||||
a = self.a
|
||||
self.client = Client(self.base, timeout=10)
|
||||
self.alice, _bob, _eve, self.chat = self.client.bootstrap()
|
||||
self.token = self.alice["token"]
|
||||
self.t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(a.concurrency)]
|
||||
threads.append(threading.Thread(target=self.poll_lb, daemon=True))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.action_at)
|
||||
action = {"command": a.action, "started_s": round(self.now(), 3)}
|
||||
log = open(a.action_log, "w", encoding="utf-8") if a.action_log else subprocess.DEVNULL
|
||||
proc = subprocess.Popen(shlex.split(a.action), stdout=log, stderr=subprocess.STDOUT)
|
||||
rc = proc.wait(timeout=a.duration)
|
||||
action.update(finished_s=round(self.now(), 3), exit_code=rc)
|
||||
remaining = a.duration - self.now()
|
||||
if remaining > 0:
|
||||
time.sleep(remaining)
|
||||
self.stop.set()
|
||||
for t in threads:
|
||||
t.join(timeout=TIMEOUT + 1)
|
||||
return self.summarize(action)
|
||||
|
||||
def summarize(self, action):
|
||||
a, t_act = self.a, action["started_s"]
|
||||
secs = sorted(self.per_sec)
|
||||
base = [self.per_sec[s]["ok"] for s in secs if 1 <= s < int(t_act)] # 1-я секунда — прогрев
|
||||
baseline = sum(base) / len(base) if base else 0
|
||||
after = [(round(t - t_act, 3), k) for t, k in self.errors if t >= t_act]
|
||||
# Восстановление = конец окна ошибок: после этого момента все запросы до конца
|
||||
# прогона успешны. Если ошибок не было — 0. Мощность после отказа меряем отдельно:
|
||||
# при меньшем числе реплик RPS законно ниже (лимиты CPU на реплику).
|
||||
recovery = after[-1][0] if after else 0.0
|
||||
tail_secs = [s for s in secs if int(action.get("finished_s", t_act)) + 2 <= s < a.duration - 1]
|
||||
post = [self.per_sec[s]["ok"] for s in tail_secs]
|
||||
post_rps = sum(post) / len(post) if post else 0
|
||||
writes_after = any(self.per_sec[s]["ok"] > 0 for s in tail_secs)
|
||||
target = a.target_instance
|
||||
hist = self.history()
|
||||
ids = [m["id"] for m in hist]
|
||||
texts = [m["text"] for m in hist]
|
||||
lost = [i for i in self.confirmed if i not in set(ids)]
|
||||
timeline = [{"t": s, "ok": self.per_sec[s]["ok"], "err": self.per_sec[s]["err"],
|
||||
"instances": dict(self.per_sec[s]["inst"]), "versions": dict(self.per_sec[s]["ver"])}
|
||||
for s in secs]
|
||||
total_ok = sum(b["ok"] for b in self.per_sec.values())
|
||||
total_err = len(self.errors)
|
||||
summary = {
|
||||
"label": a.label,
|
||||
"concurrency": a.concurrency, "duration_s": a.duration, "request_timeout_s": TIMEOUT,
|
||||
"action": action,
|
||||
"baseline_ok_rps": round(baseline, 1),
|
||||
"overall_ok_rps": round(total_ok / a.duration, 1),
|
||||
"requests_ok": total_ok, "errors_total": total_err,
|
||||
"error_rate": round(total_err / max(1, total_ok + total_err), 5),
|
||||
"errors_by_kind": dict(Counter(k for _, k in self.errors)),
|
||||
"error_window_s": [after[0][0], after[-1][0]] if after else None,
|
||||
"recovery_s": recovery,
|
||||
"post_action_ok_rps": round(post_rps, 1),
|
||||
"capacity_ratio": round(post_rps / baseline, 2) if baseline else None,
|
||||
"latency_ok_ms": {"p50": percentile(self.lat, 50), "p95": percentile(self.lat, 95),
|
||||
"p99": percentile(self.lat, 99)},
|
||||
"target_instance": target,
|
||||
"target_last_seen_s": (round(self.inst_last_seen[target] - t_act, 3)
|
||||
if target in self.inst_last_seen else None),
|
||||
"lb_events": [dict(e, t=round(e["t"] - t_act, 2)) for e in self.lb_events],
|
||||
"posts_retried_same_key": self.retried_posts,
|
||||
"confirmed_messages": len(self.confirmed),
|
||||
"history_messages": len(hist), "lost_confirmed": len(lost),
|
||||
"duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"timeline": timeline,
|
||||
}
|
||||
summary["pass"] = (summary["lost_confirmed"] == 0 and summary["duplicate_ids"] == 0
|
||||
and summary["duplicate_texts"] == 0 and action["exit_code"] == 0
|
||||
and writes_after and recovery <= 10)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Отказ/замена реплики под нагрузкой")
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--stats-url", default="http://127.0.0.1:8404/stats;csv")
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--duration", type=float, default=40)
|
||||
p.add_argument("--action-at", type=float, default=10)
|
||||
p.add_argument("--action", required=True, help="команда без shell, например 'docker stop -t 20 <id>'")
|
||||
p.add_argument("--action-log")
|
||||
p.add_argument("--target-instance", help="X-Instance-Id реплики, которую останавливает action")
|
||||
p.add_argument("--label", default="")
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
s = Bench(a).run()
|
||||
brief = {k: v for k, v in s.items() if k != "timeline"}
|
||||
print(json.dumps(brief, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(s, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if s["pass"] else "FAIL")
|
||||
return 0 if s["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4).
|
||||
|
||||
Сценарий на каждый раунд:
|
||||
A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело.
|
||||
Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик,
|
||||
в истории ровно одно сообщение с этим текстом.
|
||||
B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно
|
||||
тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет.
|
||||
|
||||
Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их
|
||||
по репликам. Токены только в памяти; синтетические пользователи создаются заново.
|
||||
|
||||
python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата)
|
||||
|
||||
|
||||
def post(base, token, chat_id, key, text, barrier, out, idx):
|
||||
data = json.dumps({"text": text}).encode()
|
||||
req = urllib.request.Request(
|
||||
base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json",
|
||||
"Idempotency-Key": key, "Connection": "close"})
|
||||
barrier.wait()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text)
|
||||
except urllib.error.HTTPError as e:
|
||||
out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text)
|
||||
except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку
|
||||
out[idx] = (0, repr(e), None, text)
|
||||
|
||||
|
||||
def burst(base, token, chat_id, key, texts):
|
||||
barrier = threading.Barrier(len(texts))
|
||||
out = [None] * len(texts)
|
||||
threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i))
|
||||
for i, t in enumerate(texts)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return out
|
||||
|
||||
|
||||
def history_texts(c, actor, chat):
|
||||
from urllib.parse import quote
|
||||
texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
while True:
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
if page["next_cursor"] is None:
|
||||
return texts
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--rounds", type=int, default=20)
|
||||
p.add_argument("--parallel", type=int, default=16)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
c = Client(base)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
token = alice["token"]
|
||||
problems, instances = [], Counter()
|
||||
stats = {"same_body": Counter(), "conflicting_body": Counter()}
|
||||
|
||||
for rnd in range(a.rounds):
|
||||
# A) одинаковое тело
|
||||
key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex
|
||||
res = burst(base, token, chat["id"], key, [text] * a.parallel)
|
||||
stats["same_body"].update(str(r[0]) for r in res)
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
seen = {r[2] for r in res if r[2]}
|
||||
instances.update(r[2] for r in res if r[2])
|
||||
if any(r[0] != 201 for r in res) or len(ids) != 1:
|
||||
problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids)))
|
||||
if len(seen) < 2:
|
||||
problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen)))
|
||||
|
||||
# B) тот же ключ, два разных тела вперемешку
|
||||
key = "mixed-" + uuid.uuid4().hex
|
||||
t1, t2 = "Тело A " + key, "Тело B " + key
|
||||
res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2))
|
||||
stats["conflicting_body"].update(str(r[0]) for r in res)
|
||||
winners = {r[3] for r in res if r[0] == 201}
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
bad = [r[0] for r in res if r[0] not in (201, 409)]
|
||||
losers_ok = all(r[0] == 409 for r in res if r[3] not in winners)
|
||||
if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok:
|
||||
problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad))
|
||||
|
||||
texts = history_texts(c, alice, chat)
|
||||
dupes = [t for t, n in Counter(texts).items() if n > 1]
|
||||
if dupes:
|
||||
problems.append("duplicated messages in history: %d" % len(dupes))
|
||||
summary = {
|
||||
"rounds": a.rounds, "parallel_per_burst": a.parallel,
|
||||
"requests_total": a.rounds * a.parallel * 2,
|
||||
"status_counts": {k: dict(v) for k, v in stats.items()},
|
||||
"replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()),
|
||||
"messages_in_history": len(texts), "expected_messages": a.rounds * 2,
|
||||
"duplicates": len(dupes), "problems": problems,
|
||||
}
|
||||
if len(texts) != a.rounds * 2:
|
||||
problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2))
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if not problems else "FAIL")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Шторм входов: много параллельных POST /auth/sessions с неверным паролем через LB.
|
||||
|
||||
Зачем: scrypt (N=2^15, r=8) берёт ~32 MiB на одну проверку пароля, лимит API-реплики
|
||||
256 MiB. Без ограничения параллельных проверок несколько одновременных входов
|
||||
приводят к OOM-kill реплики. Скрипт показывает, переживают ли реплики такой шторм.
|
||||
|
||||
Что измеряется:
|
||||
* статусы ответов шторма (ожидаем 401 и, при перегрузке, 503 с Retry-After) и
|
||||
ответы не в JSON-формате ошибки контракта (например HTML-страницы HAProxy);
|
||||
* «жертва»: параллельный поток раз в 50 мс читает /users/me действующим токеном —
|
||||
обычные пользователи не должны получать ошибки из-за шторма входов;
|
||||
* состояние API-контейнеров до/после: OOMKilled, RestartCount, StartedAt.
|
||||
|
||||
Пример: python3 student-tests/login_flood.py --parallel 24 --duration 20 --output evidence/login-flood.json
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
TIMEOUT = 10.0
|
||||
|
||||
|
||||
def http(base, method, path, headers=None, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = dict(headers or {})
|
||||
if data is not None:
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
return r.status, r.headers, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers, e.read()
|
||||
|
||||
|
||||
def is_contract_error(headers, raw):
|
||||
if not (headers.get("Content-Type") or "").startswith("application/json"):
|
||||
return False
|
||||
try:
|
||||
err = json.loads(raw)["error"]
|
||||
return bool(err["code"] and err["message"] and err["request_id"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def api_containers():
|
||||
ids = subprocess.run(["docker", "compose", "ps", "-a", "-q", "api"], capture_output=True,
|
||||
text=True, check=True).stdout.split()
|
||||
out = {}
|
||||
for cid in ids:
|
||||
info = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, text=True,
|
||||
check=True).stdout)[0]
|
||||
out[info["Name"].lstrip("/")] = {
|
||||
"status": info["State"]["Status"], "oom_killed": info["State"]["OOMKilled"],
|
||||
"restart_count": info["RestartCount"], "started_at": info["State"]["StartedAt"]}
|
||||
return out
|
||||
|
||||
|
||||
def oom_events(since):
|
||||
"""Имена контейнеров, получивших OOM с момента since (unix time): флаг OOMKilled
|
||||
сбрасывается после рестарта по restart-policy, поэтому смотрим события Docker."""
|
||||
out = subprocess.run(["docker", "events", "--since", str(int(since)), "--until", str(int(time.time()) + 1),
|
||||
"--filter", "type=container", "--filter", "event=oom",
|
||||
"--format", "{{.Actor.Attributes.name}}"], capture_output=True, text=True).stdout
|
||||
return sorted(Counter(out.split()).items())
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--parallel", type=int, default=24)
|
||||
p.add_argument("--duration", type=float, default=20)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
|
||||
username = "flood_" + uuid.uuid4().hex[:10]
|
||||
password = "correct-horse-" + uuid.uuid4().hex[:8]
|
||||
st, _, _ = http(base, "POST", "/api/v1/users",
|
||||
body={"username": username, "display_name": "Flood", "password": password})
|
||||
assert st == 201, st
|
||||
basic = base64.b64encode(("%s:%s" % (username, password)).encode()).decode()
|
||||
st, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
assert st == 201, st
|
||||
token = json.loads(raw)["token"]
|
||||
bad = base64.b64encode(("%s:wrong-password-123" % username).encode()).decode()
|
||||
|
||||
before = api_containers()
|
||||
wall0 = time.time()
|
||||
stop = threading.Event()
|
||||
lock = threading.Lock()
|
||||
flood, victim = Counter(), Counter()
|
||||
non_json_errors = Counter()
|
||||
retry_after_503 = [0, 0] # [503 всего, из них с Retry-After]
|
||||
|
||||
def record(counter, status, headers, raw):
|
||||
with lock:
|
||||
counter[str(status)] += 1
|
||||
if status >= 400 and not is_contract_error(headers, raw):
|
||||
non_json_errors[str(status)] += 1
|
||||
if status == 503 and counter is flood:
|
||||
retry_after_503[0] += 1
|
||||
retry_after_503[1] += bool(headers.get("Retry-After"))
|
||||
|
||||
def flooder():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(flood, *http(base, "POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + bad}))
|
||||
except Exception as exc: # обрыв соединения, timeout
|
||||
with lock:
|
||||
flood["exc:" + type(exc).__name__] += 1
|
||||
|
||||
def prober():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(victim, *http(base, "GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token}))
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
victim["exc:" + type(exc).__name__] += 1
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=flooder, daemon=True) for _ in range(a.parallel)]
|
||||
threads.append(threading.Thread(target=prober, daemon=True))
|
||||
t0 = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.duration)
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join(TIMEOUT + 1)
|
||||
elapsed = time.monotonic() - t0
|
||||
time.sleep(3) # дать restart-policy отработать, если реплика упала
|
||||
after = api_containers()
|
||||
|
||||
restarted = [n for n in after if n in before and (
|
||||
after[n]["restart_count"] != before[n]["restart_count"]
|
||||
or after[n]["started_at"] != before[n]["started_at"])]
|
||||
victim_ok = victim.get("200", 0)
|
||||
victim_total = sum(victim.values())
|
||||
summary = {
|
||||
"parallel": a.parallel, "duration_s": round(elapsed, 1),
|
||||
"flood_statuses": dict(flood), "flood_rps": round(sum(flood.values()) / elapsed, 1),
|
||||
"flood_503_with_retry_after": "%d/%d" % (retry_after_503[1], retry_after_503[0]),
|
||||
"victim_statuses": dict(victim),
|
||||
"victim_error_rate": round(1 - victim_ok / victim_total, 4) if victim_total else None,
|
||||
"non_contract_error_bodies": dict(non_json_errors),
|
||||
"containers_before": before, "containers_after": after,
|
||||
"oom_events": dict(oom_events(wall0)),
|
||||
"restarted": restarted,
|
||||
}
|
||||
summary["pass"] = (not summary["oom_events"] and not restarted and victim_total > 0
|
||||
and victim_ok == victim_total and not non_json_errors)
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
with open(a.output, "w", encoding="utf-8") as f:
|
||||
f.write(text + "\n")
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Недоступность S3: stop (порт закрыт) и pause (S3 «завис», TCP не отвечает).
|
||||
|
||||
python3 student-tests/s3_outage.py [--output evidence/s3-outage.json]
|
||||
|
||||
Ожидания: upload и download — быстрый 503 unavailable c Retry-After (не 500 и не
|
||||
таймаут LB), текстовые сообщения и /health/ready продолжают работать (S3 не входит в
|
||||
readiness), после восстановления S3 загрузка снова 201 без перезапуска API.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
log = []
|
||||
|
||||
|
||||
def probe(c, alice, chat, att):
|
||||
out = {}
|
||||
for name, args in (
|
||||
("upload", ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"])),
|
||||
("download", ("GET", "/api/v1/attachments/%s/content" % att["id"])),
|
||||
("text_message", ("POST", "/api/v1/chats/%s/messages" % chat["id"])),
|
||||
("ready", ("GET", "/health/ready"))):
|
||||
kw = {}
|
||||
if name == "upload":
|
||||
kw = {"raw": PNG, "headers": {"Content-Type": "image/png"}}
|
||||
if name == "text_message":
|
||||
kw = {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}
|
||||
t = time.monotonic()
|
||||
r = c.call(*args, [200, 201, 503, 502, 504], actor=alice if name != "ready" else None, **kw)
|
||||
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
|
||||
"code": (r["json"] or {}).get("error", {}).get("code"),
|
||||
"retry_after": r["headers"].get("Retry-After")}
|
||||
return out
|
||||
|
||||
|
||||
def phase(name, c, alice, chat, att):
|
||||
entry = {"phase": name, "probe": probe(c, alice, chat, att)}
|
||||
log.append(entry)
|
||||
print(json.dumps(entry, ensure_ascii=False), flush=True)
|
||||
return entry
|
||||
|
||||
|
||||
def recover(c, alice, chat, started):
|
||||
while time.monotonic() - started < 120:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=r.png" % chat["id"], [201, 503], actor=alice,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
if r["status"] == 201:
|
||||
return round(time.monotonic() - started, 1)
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 201, actor=alice, raw=PNG,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||
phase("baseline", c, alice, chat, att)
|
||||
for action, undo in ((["stop", "s3"], ["start", "s3"]), (["pause", "s3"], ["unpause", "s3"])):
|
||||
subprocess.run(["docker", "compose"] + action, cwd=ROOT, check=True, capture_output=True)
|
||||
time.sleep(1)
|
||||
phase("immediately after `%s` (S3Health not yet stale)" % " ".join(action), c, alice, chat, att)
|
||||
time.sleep(4)
|
||||
phase("S3 down for 5 s (`%s`)" % " ".join(action), c, alice, chat, att)
|
||||
subprocess.run(["docker", "compose"] + undo, cwd=ROOT, check=True, capture_output=True)
|
||||
t0 = time.monotonic()
|
||||
rec = recover(c, alice, chat, t0)
|
||||
log.append({"phase": "recovery after `%s`" % " ".join(undo), "upload_201_after_s": rec})
|
||||
print(json.dumps(log[-1]), flush=True)
|
||||
# Оставляем стенд рабочим: ждём, пока healthcheck S3 снова станет healthy (после pause
|
||||
# он несколько проверок подряд был unhealthy, а `docker compose up api` при нездоровой
|
||||
# зависимости не запускает реплики).
|
||||
cid = subprocess.run(["docker", "compose", "ps", "-q", "s3"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
|
||||
t0 = time.monotonic()
|
||||
while time.monotonic() - t0 < 120:
|
||||
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True, text=True).stdout.strip()
|
||||
if st == "healthy":
|
||||
break
|
||||
time.sleep(1)
|
||||
log.append({"phase": "s3 healthcheck healthy again", "after_s": round(time.monotonic() - t0, 1), "status": st})
|
||||
print(json.dumps(log[-1]), flush=True)
|
||||
down = [e for e in log if e.get("phase", "").startswith("S3 down")]
|
||||
ok = all(e["probe"]["upload"]["status"] == 503 and e["probe"]["download"]["status"] == 503
|
||||
and e["probe"]["text_message"]["status"] == 201 and e["probe"]["ready"]["status"] == 200
|
||||
for e in down) and all(e.get("upload_201_after_s") is not None for e in log if "upload_201_after_s" in e)
|
||||
no5xx = all(p["status"] in (200, 201, 503) for e in log if "probe" in e for p in e["probe"].values())
|
||||
ok = ok and st == "healthy"
|
||||
print(json.dumps({"pass": ok and no5xx, "only_200_201_503": no5xx}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"pass": ok and no5xx, "phases": log}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok and no5xx else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка приватности bucket и ограничений ключей ВНЕ API (внутри backend-сети).
|
||||
|
||||
docker compose --profile tools run --rm s3-check
|
||||
|
||||
Проверяет напрямую на S3 (минуя API и его ACL):
|
||||
* анонимные GET объекта / ListBucket / PUT -> 403;
|
||||
* ключ api: Put/Get/Delete своего тестового объекта можно; ListBucket, CreateBucket,
|
||||
DeleteBucket, PutBucketPolicy — AccessDenied; другой bucket — AccessDenied;
|
||||
* ключ janitor: List и Delete можно; GetObject (чтение содержимого) — AccessDenied;
|
||||
* служебные порты SeaweedFS (master 9333, volume 8080, filer 8888, IAM 8111,
|
||||
Iceberg 8181, Lance 9101) из backend-сети недоступны — открыт только S3 :8333.
|
||||
Выход 0 только если все ожидания выполнены. Ключи не печатаются.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
sys.path.insert(0, "/app/src")
|
||||
from minio import Minio # noqa: E402
|
||||
from minio.error import S3Error # noqa: E402
|
||||
|
||||
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
HOST = urlsplit(ENDPOINT).netloc
|
||||
|
||||
|
||||
def key(name):
|
||||
with open("/run/secrets/" + name) as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
def client(who):
|
||||
return Minio(HOST, access_key=key("s3_%s_access_key" % who), secret_key=key("s3_%s_secret_key" % who),
|
||||
secure=False, region=os.environ.get("S3_REGION", "us-east-1"))
|
||||
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
def expect(name, should_succeed, fn):
|
||||
try:
|
||||
fn()
|
||||
ok, got = should_succeed, "allowed"
|
||||
except S3Error as exc:
|
||||
ok, got = not should_succeed, exc.code
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok, got = False, type(exc).__name__
|
||||
results.append({"check": name, "expected": "allowed" if should_succeed else "denied", "got": got, "pass": ok})
|
||||
|
||||
|
||||
def http_status(method, url, data=None):
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=3) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
api, janitor = client("api"), client("janitor")
|
||||
probe = "originals/s3check-" + uuid.uuid4().hex
|
||||
expect("api: PutObject в свой bucket", True, lambda: api.put_object(BUCKET, probe, io.BytesIO(b"x" * 16), 16))
|
||||
for name, method, url, data in (
|
||||
("anonymous GET object", "GET", "%s/%s/%s" % (ENDPOINT, BUCKET, probe), None),
|
||||
("anonymous ListBucket", "GET", "%s/%s?list-type=2" % (ENDPOINT, BUCKET), None),
|
||||
("anonymous ListAllMyBuckets", "GET", ENDPOINT + "/", None),
|
||||
("anonymous PUT object", "PUT", "%s/%s/anon-%s" % (ENDPOINT, BUCKET, uuid.uuid4().hex), b"z")):
|
||||
code = http_status(method, url, data)
|
||||
results.append({"check": name, "expected": "403", "got": code, "pass": code in (401, 403)})
|
||||
expect("api: GetObject", True, lambda: api.get_object(BUCKET, probe).read())
|
||||
expect("api: ListBucket", False, lambda: list(api.list_objects(BUCKET, recursive=True)))
|
||||
expect("api: CreateBucket", False, lambda: api.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteBucket", False, lambda: api.remove_bucket(BUCKET))
|
||||
expect("api: PutBucketPolicy (сделать публичным)", False, lambda: api.set_bucket_policy(BUCKET, json.dumps({
|
||||
"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": "*", "Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::%s/*" % BUCKET]}]})))
|
||||
expect("janitor: GetObject (чтение содержимого)", False, lambda: janitor.get_object(BUCKET, probe).read())
|
||||
expect("janitor: ListBucket", True, lambda: list(janitor.list_objects(BUCKET, prefix="originals/", recursive=True)))
|
||||
expect("janitor: CreateBucket", False, lambda: janitor.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteObject (компенсация)", True, lambda: api.remove_object(BUCKET, probe))
|
||||
s3_host = HOST.split(":")[0]
|
||||
for port, role in ((9333, "master UI/API"), (8080, "volume"), (8888, "filer UI/API"), (8111, "IAM API"),
|
||||
(8181, "Iceberg"), (9101, "Lance"), (8333, "S3 API")):
|
||||
try:
|
||||
socket.create_connection((s3_host, port), timeout=2).close()
|
||||
got = "open"
|
||||
except OSError:
|
||||
got = "closed"
|
||||
want = "open" if port == 8333 else "closed"
|
||||
results.append({"check": "port %d (%s) из backend-сети" % (port, role), "expected": want, "got": got,
|
||||
"pass": got == want})
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-45s expected=%-8s got=%s" % (r["check"], r["expected"], r["got"]))
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
print(json.dumps({"checks": len(results), "failed": len(failed)}))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Пик памяти API при одновременных загрузках крупных файлов (уровень 4).
|
||||
|
||||
python3 student-tests/upload_memory.py --concurrency 12 --rounds 3 --output evidence/upload-memory-c12.json
|
||||
|
||||
Гипотеза: потоковый приём (буфер 64 KiB -> безымянный временный файл), multipart PUT
|
||||
частями по 5 MiB и draft-декодирование JPEG держат RAM реплики ограниченной и не
|
||||
зависящей линейно от числа одновременных загрузок; 10+ загрузок по ~10 MiB не
|
||||
приближают процесс к лимиту контейнера 256 MiB.
|
||||
|
||||
Методика: перед прогоном API-реплики перезапускаются (VmHWM считается с нуля). В каждой
|
||||
реплике фоново (docker exec ... while sleep 0.05) читаются VmRSS процесса (PID 1) и
|
||||
anon/file из cgroup memory.stat. Нагрузка — concurrency потоков, каждый грузит свой
|
||||
файл через LB; файлы: несжимаемый PNG ~9.99 MiB и (если на хосте есть Pillow) JPEG
|
||||
6000x6000 = 36 Мпикс. В конце — VmHWM (пиковый RSS процесса) и memory.peak cgroup.
|
||||
file-память cgroup — page cache временных файлов, она вытесняема и OOM не вызывает.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from client import Client # noqa: E402
|
||||
from attachments_negative import noise_png # noqa: E402
|
||||
|
||||
SAMPLER = ("while true; do r=$(grep VmRSS /proc/1/status | tr -s ' ' | cut -d' ' -f2); "
|
||||
"a=$(grep '^anon ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); "
|
||||
"f=$(grep '^file ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); echo \"$r $a $f\"; sleep 0.05; done")
|
||||
|
||||
|
||||
def sh(*cmd):
|
||||
return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
def containers():
|
||||
return sh("docker", "compose", "ps", "-q", "api").split()
|
||||
|
||||
|
||||
def proc_status(cid, field):
|
||||
out = sh("docker", "exec", cid, "grep", field, "/proc/1/status")
|
||||
return int(out.split()[1]) // 1024 # kB -> MiB
|
||||
|
||||
|
||||
class Sampler:
|
||||
def __init__(self, cid):
|
||||
self.cid, self.samples = cid, []
|
||||
self.p = subprocess.Popen(["docker", "exec", cid, "sh", "-c", SAMPLER], stdout=subprocess.PIPE, text=True)
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self):
|
||||
for line in self.p.stdout:
|
||||
parts = line.split()
|
||||
if len(parts) == 3:
|
||||
self.samples.append((time.monotonic(), int(parts[0]) / 1024, int(parts[1]) / 2**20, int(parts[2]) / 2**20))
|
||||
|
||||
def stop(self):
|
||||
self.p.terminate()
|
||||
|
||||
|
||||
def make_jpeg():
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
return None
|
||||
im = Image.effect_noise((6000, 6000), 40).convert("RGB")
|
||||
for q in (60, 45, 30, 20):
|
||||
b = io.BytesIO()
|
||||
im.save(b, "JPEG", quality=q)
|
||||
if b.tell() <= 10 * 1024 * 1024:
|
||||
return b.getvalue()
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--concurrency", type=int, default=12)
|
||||
ap.add_argument("--rounds", type=int, default=3)
|
||||
ap.add_argument("--no-restart", action="store_true")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
files = [("image/png", noise_png(10 * 1024 * 1024))]
|
||||
jpeg = make_jpeg()
|
||||
if jpeg:
|
||||
files.append(("image/jpeg", jpeg))
|
||||
if not args.no_restart:
|
||||
sh("docker", "compose", "restart", "api")
|
||||
sh("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--wait", "api")
|
||||
time.sleep(4)
|
||||
c = Client(args.base_url, timeout=120)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
# прогрев: один upload каждого типа (импорт Pillow, пулы соединений)
|
||||
for ctype, data in files:
|
||||
c.call("POST", "/api/v1/chats/%s/attachments?filename=w" % chat["id"], 201, actor=alice, raw=data,
|
||||
headers={"Content-Type": ctype})
|
||||
cids = containers()
|
||||
idle = {cid[:12]: {"rss_mib": proc_status(cid, "VmRSS"), "hwm_mib_after_warmup": proc_status(cid, "VmHWM")}
|
||||
for cid in cids}
|
||||
s3_cid = sh("docker", "compose", "ps", "-q", "s3").split()[0]
|
||||
s3_before = {"rss_mib": proc_status(s3_cid, "VmRSS"), "oom_killed": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip()}
|
||||
samplers = [Sampler(cid) for cid in cids]
|
||||
s3_sampler = Sampler(s3_cid)
|
||||
time.sleep(1)
|
||||
results, lock = [], threading.Lock()
|
||||
|
||||
def worker(i):
|
||||
ctype, data = files[i % len(files)]
|
||||
t = time.monotonic()
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=m%d" % (chat["id"], i), [201, 503], actor=alice,
|
||||
raw=data, headers={"Content-Type": ctype}, schema=None)
|
||||
st, inst = r["status"], r["headers"].get("X-Instance-Id")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
st, inst = type(exc).__name__, None
|
||||
with lock:
|
||||
results.append({"type": ctype, "status": st, "instance": inst, "s": round(time.monotonic() - t, 2)})
|
||||
|
||||
started = time.monotonic()
|
||||
for _ in range(args.rounds):
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
|
||||
for th in threads:
|
||||
th.start()
|
||||
for th in threads:
|
||||
th.join()
|
||||
wall = time.monotonic() - started
|
||||
time.sleep(1)
|
||||
for s in samplers + [s3_sampler]:
|
||||
s.stop()
|
||||
per = {}
|
||||
for cid, s in zip(cids, samplers):
|
||||
k = cid[:12]
|
||||
per[k] = dict(idle[k],
|
||||
samples=len(s.samples),
|
||||
peak_rss_mib_sampled=round(max(x[1] for x in s.samples), 1),
|
||||
peak_anon_mib=round(max(x[2] for x in s.samples), 1),
|
||||
peak_file_cache_mib=round(max(x[3] for x in s.samples), 1),
|
||||
vmhwm_mib=proc_status(cid, "VmHWM"),
|
||||
cgroup_memory_peak_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.peak")) / 2**20, 1),
|
||||
memory_limit_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20),
|
||||
uploads_served=sum(1 for r in results if r["instance"] == k))
|
||||
durations = sorted(r["s"] for r in results if r["status"] == 201)
|
||||
summary = {
|
||||
"concurrency": args.concurrency, "rounds": args.rounds,
|
||||
"files": [{"type": t, "bytes": len(d), "sha256": hashlib.sha256(d).hexdigest()[:16]} for t, d in files],
|
||||
"uploads": len(results), "status_counts": {str(k): sum(1 for r in results if r["status"] == k)
|
||||
for k in {r["status"] for r in results}},
|
||||
"megabytes_uploaded_ok": round(sum(len(files[i % len(files)][1]) for i, r in enumerate(results)
|
||||
if r["status"] == 201) / 2**20, 1),
|
||||
"wall_s": round(wall, 1),
|
||||
"latency_s_p50_max": [durations[len(durations) // 2], durations[-1]] if durations else None,
|
||||
"replicas": per,
|
||||
"s3": dict(s3_before,
|
||||
peak_rss_mib_sampled=round(max(x[1] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||||
peak_anon_mib=round(max(x[2] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||||
restarts=int(sh("docker", "inspect", "-f", "{{.RestartCount}}", s3_cid)),
|
||||
oom_killed_after=sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip(),
|
||||
memory_limit_mib=round(int(sh("docker", "exec", s3_cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20)),
|
||||
"oom_kills": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", *cids).split(),
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user