From 59fc7b96eccdded1c11c317a0d5e2e48ebb8ba6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B8=D1=81=D0=B0=20=D0=A8=D1=83=D1=80=D0=BC?= =?UTF-8?q?=D0=B0=D0=BD?= Date: Thu, 12 Nov 2026 23:01:59 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9F=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D0=9B=D0=A04:=20=D1=81=D0=B1=D0=BE=D1=80=D0=BA?= =?UTF-8?q?=D0=B0=20MinIO=20=D0=B8=D0=B7=20=D0=B8=D1=81=D1=85=D0=BE=D0=B4?= =?UTF-8?q?=D0=BD=D0=B8=D0=BA=D0=BE=D0=B2=20=D0=B8=20=D1=80=D0=B5=D0=B7?= =?UTF-8?q?=D1=83=D0=BB=D1=8C=D1=82=D0=B0=D1=82=D1=8B=20=D0=BF=D0=BE=D0=BB?= =?UTF-8?q?=D0=BD=D0=BE=D0=B3=D0=BE=20=D0=BF=D1=80=D0=BE=D0=B3=D0=BE=D0=BD?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 80 ++++++++++++++++++++-------- compose.yaml | 10 +++- evidence/attachment-failover.txt | 39 ++++++++++++++ evidence/bootstrap-repeat.txt | 6 +++ evidence/check.txt | 2 + evidence/containers-after.txt | 7 +++ evidence/containers-before.txt | 7 +++ evidence/failover.txt | 4 ++ evidence/memory.json | 68 +++++++++++++++++++++++ evidence/memory.txt | 51 ++++++++++++++++++ evidence/outage.txt | 9 ++++ evidence/persistence.txt | 3 ++ evidence/smoke.txt | 2 + evidence/storage-checks.txt | 1 + evidence/student-tests.txt | 1 + evidence/unit.txt | 10 ++++ evidence/validate.txt | 4 ++ infra/s3/Dockerfile | 23 ++++++++ scripts/verify.py | 11 +++- student-tests/attachment_failover.py | 34 ++++++++++++ student-tests/storage_checks.py | 8 ++- student-tests/verify.py | 15 +++++- 22 files changed, 368 insertions(+), 27 deletions(-) create mode 100644 evidence/attachment-failover.txt create mode 100644 evidence/bootstrap-repeat.txt create mode 100644 evidence/check.txt create mode 100644 evidence/containers-after.txt create mode 100644 evidence/containers-before.txt create mode 100644 evidence/failover.txt create mode 100644 evidence/memory.json create mode 100644 evidence/memory.txt create mode 100644 evidence/outage.txt create mode 100644 evidence/persistence.txt create mode 100644 evidence/smoke.txt create mode 100644 evidence/storage-checks.txt create mode 100644 evidence/student-tests.txt create mode 100644 evidence/unit.txt create mode 100644 evidence/validate.txt create mode 100644 infra/s3/Dockerfile create mode 100644 student-tests/attachment_failover.py diff --git a/REPORT.md b/REPORT.md index 893d9249..3c215bc2 100644 --- a/REPORT.md +++ b/REPORT.md @@ -4,13 +4,12 @@ ## Статус проверки -Реализация подготовлена, но **полный Docker-прогон ещё не выполнен**. В среде подготовки -нет доступа к Docker socket. Проверены структура задания, Python-синтаксис, -Compose-конфигурация и пять локальных тестов валидации изображений. -Фактические локальные результаты находятся в `evidence/offline.txt`. -Smoke, сохранность, отказ реплики, доступ к приватному bucket, очистка после сбоя -и эксперимент с 10 загрузками необходимо выполнить приведённой ниже командой. -До этого выполнение всех критериев оценки 4 не подтверждено. +Полный прогон выполнен **12 ноября 2026 года** на macOS arm64 / Docker Desktop. +`make check`, полная валидация OpenAPI, 5 unit-тестов и весь `scripts/verify.py` +прошли. Реальные результаты находятся в `evidence/`: smoke, негативные сценарии, +приватность bucket, безопасная очистка, обрыв upload, отказ S3, повторный bootstrap, +persistence, failover и нагрузка. Контракт и публичные тесты не изменены. +Первоначальный `evidence/offline.txt` сохранён как историческая проверка до запуска Docker. ## Запуск @@ -19,11 +18,14 @@ API работает на Python 3.12.7. Новый стенд использу и Compose project `mtusi-lab4`, поэтому не занимает порт предыдущих работ. ```sh -cd labs/mtusi2026lab4 +cd mtusi2026lab4-fork +python3 -m venv .venv +.venv/bin/pip install -r requirements-dev.txt Pillow==11.1.0 python3 scripts/bootstrap.py docker compose config --quiet docker compose up -d --build --wait -BASE_URL=http://localhost:8084 python3 scripts/verify.py +BASE_URL=http://localhost:8084 .venv/bin/python scripts/verify.py +make validate PYTHON=.venv/bin/python ``` Команды выполняются из корня этой лабораторной. Если репозиторий склонирован отдельно, @@ -36,6 +38,14 @@ API: http://localhost:8084; Swagger: http://localhost:8084/docs. Остановка без потери данных: `docker compose down` (без `-v`). Возобновление: `docker compose up -d --wait`. +Готовые образы `minio/minio` и `minio/mc` оказались недоступны при проверке +12 ноября 2026 года (Docker Hub: pull access denied; Quay: 401). +Поэтому `infra/s3/Dockerfile` собирает официальные исходники закреплённых релизов +[MinIO RELEASE.2025-04-22T22-12-26Z](https://github.com/minio/minio/tree/RELEASE.2025-04-22T22-12-26Z) +и [mc RELEASE.2025-04-16T18-13-26Z](https://github.com/minio/mc/tree/RELEASE.2025-04-16T18-13-26Z) +в Go 1.24.2. Лицензии включены в образы. Первый запуск требует интернет и время +на скачивание Go-зависимостей и компиляцию; следующие сборки используют Docker cache. + ## Архитектура HAProxy → две FastAPI-реплики → общий PostgreSQL и приватный MinIO. @@ -100,23 +110,39 @@ Root credentials доступны только MinIO и init, API их не по Readiness зависит от PostgreSQL и MinIO. Valkey имеет fallback в PostgreSQL. Секреты находятся в исключённом из Git каталоге `secrets/`. +| Роль / service | Версия | Готовность | Постоянные данные | Доступ / credentials | +|---|---|---|---|---| +| LB / `lb` | HAProxy 3.0.8-alpine | HTTP `/health/ready` обеих API | нет | только `127.0.0.1:8084` | +| API / `api1`, `api2` | Python 3.12.7; `app/requirements.txt` | PostgreSQL + MinIO | нет | внутренняя сеть; DB/S3 через secrets | +| БД / `postgres` | PostgreSQL 16.6-bookworm | `pg_isready` | `postgres-data` | внутренняя сеть; password secret | +| Кэш / `valkey` | Valkey 8.0.2-alpine | некритичен, fallback в БД | `valkey-data` (AOF) | внутренняя сеть | +| S3 / `s3` | MinIO RELEASE.2025-04-22T22-12-26Z | `/minio/health/live` | `s3-data` | внутренняя сеть; root secrets | +| Bootstrap / `s3-init` | mc RELEASE.2025-04-16T18-13-26Z | успешное завершение | bucket/policy в S3 | root + API secrets | +| Миграции / `migrate` | образ API | успешное завершение | `schema_migrations` в БД | secrets, advisory lock, checksum миграций | +| Очистка / `cleaner` | образ API | повтор каждые 60 s | pending в БД | ограниченные API S3 credentials | + +Все сервисы находятся в отдельной Compose-сети `mtusi-lab4_default`. +Повторный `bootstrap.py` сохраняет секреты; повторные `migrate` и `s3-init` +не удаляют данные и выполняются при `docker compose up`. + ## Проверки и доказательства -| Критерий | Проверка | Статус на момент подготовки | +| Критерий | Проверка | Результат 12.11.2026 | |---|---|---| | Структура и синтаксис | `make check`, AST всех новых Python-файлов | выполнено | | Конфигурация | `docker compose config --quiet` | выполнено | | Реальные PNG/JPEG, MIME, повреждение, пиксели | `python3 student-tests/unit.py` | 5 тестов пройдено | -| Обязательный API и checksum | `make test BASE_URL=http://localhost:8084` | требуется запуск Docker | -| Ошибки файлов и ACL, конкуренция ключа | `BASE_URL=http://localhost:8084 python3 student-tests/verify.py` | требуется запуск Docker | -| Приватность bucket и безопасная очистка | `student-tests/storage_checks.py` внутри API через общий runner | требуется запуск Docker | -| Обрыв загрузки и отказ S3 | `student-tests/outage.py` | требуется запуск Docker | -| Повторный bootstrap | повтор `docker compose run --rm s3-init` | требуется запуск Docker | -| Перезапуск всех сервисов | persistence + `scripts/restart.sh` | требуется запуск Docker | -| Остановка обслужившей реплики | failover + `scripts/stop-one.sh` | требуется запуск Docker | -| 10 одновременных загрузок и RSS | `student-tests/memory.py` | измерения ещё не получены | +| Обязательный API и checksum | `make test BASE_URL=http://localhost:8084` | PASS; вывод в `evidence/` | +| Ошибки файлов и ACL, конкуренция ключа | `BASE_URL=http://localhost:8084 python3 student-tests/verify.py` | PASS; вывод в `evidence/` | +| Приватность bucket и безопасная очистка | `student-tests/storage_checks.py` внутри API через общий runner | PASS; вывод в `evidence/` | +| Обрыв загрузки и отказ S3 | `student-tests/outage.py` | PASS; вывод в `evidence/` | +| Повторный bootstrap | повтор `docker compose run --rm s3-init` | PASS; вывод в `evidence/` | +| Перезапуск всех сервисов | persistence + `scripts/restart.sh` | PASS; вывод в `evidence/` | +| Остановка обслужившей реплики | failover + `scripts/stop-one.sh` | PASS; 89 записей, 3 неудачные попытки, восстановление 2.8 s | +| Остановка именно загрузившей реплики | `student-tests/attachment_failover.py` | PASS; upload api1 → download api2; bytes совпадают | +| 10 одновременных загрузок и RSS | `student-tests/memory.py` | 8 × 201, 2 × 503; пик RSS 132796 / 133912 KiB | -`python3 scripts/verify.py` выполняет проверки и сохраняет реальные результаты в evidence, +`.venv/bin/python scripts/verify.py` выполняет проверки и сохраняет реальные результаты в evidence, останавливаясь при первом провале. Тест очистки создаёт только синтетические строки и объекты, моделирует rollback финализации после PUT, проверяет grace period и сохранность ready. Он удаляет только свои синтетические данные. До запуска убедитесь, что это учебный стенд. @@ -125,7 +151,11 @@ Memory-тест создаёт PNG примерно 9 MiB и одновреме Он пишет коды ответов, длительность, выборки VmRSS процессов API и измеренный максимум. Отказы 503 из-за ограничения слотов учитываются явно; они не записываются как успешные загрузки. Последовательная выборка `/proc/1/status` может пропустить короткий пик, поэтому результат — -максимум наблюдений, а не гарантированный абсолютный пик. Числа не подставлены заранее. +максимум наблюдений, а не гарантированный абсолютный пик. Фактический эксперимент: 10 одновременных запросов по 9 201 866 байт, +8 ответов 201 и 2 ответа 503; время ответа 0.427–0.680 s. Наблюдаемый пик RSS: +api1 — 132 796 KiB (129.7 MiB), api2 — 133 912 KiB (130.8 MiB), при лимите +768 MiB на реплику. Полные выборки сохранены в `evidence/memory.json`. +Это проверка ограниченности ресурсов, а не обещание принять любую конкуренцию без 503. ## Ограничения @@ -134,4 +164,12 @@ Memory-тест создаёт PNG примерно 9 MiB и одновреме становится 503; после восстановления новые обращения повторяются клиентом. Обрыв S3 посреди уже начатого download закрывает поток, поэтому клиент проверяет длину/checksum. Нет UI, обработки изображений в очереди, presigned URL и исследовательских треков. -Проверка реальных контейнеров и образов остаётся обязательной перед сдачей. +Проверка реальных контейнеров выполнена; при переносе на другую машину её нужно повторить. + +## Источники и использование ИИ + +Основа — собственные предыдущие лабораторные и skeleton преподавателя; +API и критерии взяты из `contracts/` и `README.md`. MinIO/mc собираются из официальных +исходников по ссылкам выше. При проверке и исправлении работы использован Codex: +анализ кода, исправление сборки S3, дополнительные тесты, запуск стенда и оформление +фактических результатов. Результаты получены запуском, а не сгенерированы. diff --git a/compose.yaml b/compose.yaml index 18894b02..9f1c0669 100644 --- a/compose.yaml +++ b/compose.yaml @@ -35,7 +35,10 @@ services: command: [valkey-server, --appendonly, 'yes', --maxmemory, 64mb, --maxmemory-policy, allkeys-lru] volumes: [valkey-data:/data] s3: - image: minio/minio:RELEASE.2025-04-22T22-12-26Z + build: + context: ./infra/s3 + target: server + image: mtusi-minio:RELEASE.2025-04-22T22-12-26Z command: [server, /data, --console-address, '127.0.0.1:9001'] environment: MINIO_ROOT_USER_FILE: /run/secrets/s3_root_user @@ -48,7 +51,10 @@ services: timeout: 3s retries: 30 s3-init: - image: minio/mc:RELEASE.2025-04-16T18-13-26Z + build: + context: ./infra/s3 + target: client + image: mtusi-mc:RELEASE.2025-04-16T18-13-26Z entrypoint: [/bin/sh, /config/init.sh] volumes: ['./infra/s3:/config:ro'] secrets: [s3_root_user, s3_root_password, s3_access_key_id, s3_secret_access_key] diff --git a/evidence/attachment-failover.txt b/evidence/attachment-failover.txt new file mode 100644 index 00000000..57b32d8e --- /dev/null +++ b/evidence/attachment-failover.txt @@ -0,0 +1,39 @@ + Container mtusi-lab4-api1-1 Stopping + Container mtusi-lab4-api1-1 Stopped + Container mtusi-lab4-valkey-1 Running + Container mtusi-lab4-s3-1 Running + Container mtusi-lab4-api2-1 Running + Container mtusi-lab4-postgres-1 Running + Container mtusi-lab4-postgres-1 Waiting + Container mtusi-lab4-s3-1 Waiting + Container mtusi-lab4-s3-1 Healthy + Container mtusi-lab4-postgres-1 Healthy + Container mtusi-lab4-s3-init-1 Starting + Container mtusi-lab4-migrate-1 Starting + Container mtusi-lab4-s3-init-1 Started + Container mtusi-lab4-migrate-1 Started + Container mtusi-lab4-migrate-1 Waiting + Container mtusi-lab4-s3-init-1 Waiting + Container mtusi-lab4-migrate-1 Waiting + Container mtusi-lab4-s3-init-1 Waiting + Container mtusi-lab4-s3-init-1 Exited + Container mtusi-lab4-migrate-1 Exited + Container mtusi-lab4-migrate-1 Exited + Container mtusi-lab4-s3-init-1 Exited + Container mtusi-lab4-api1-1 Starting + Container mtusi-lab4-api1-1 Started + Container mtusi-lab4-migrate-1 Waiting + Container mtusi-lab4-api1-1 Waiting + Container mtusi-lab4-s3-init-1 Waiting + Container mtusi-lab4-valkey-1 Waiting + Container mtusi-lab4-s3-1 Waiting + Container mtusi-lab4-api2-1 Waiting + Container mtusi-lab4-postgres-1 Waiting + Container mtusi-lab4-postgres-1 Healthy + Container mtusi-lab4-api2-1 Healthy + Container mtusi-lab4-s3-init-1 Exited + Container mtusi-lab4-migrate-1 Exited + Container mtusi-lab4-valkey-1 Healthy + Container mtusi-lab4-s3-1 Healthy + Container mtusi-lab4-api1-1 Healthy +PASS: upload=api1, download=api2, sha256=99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 diff --git a/evidence/bootstrap-repeat.txt b/evidence/bootstrap-repeat.txt new file mode 100644 index 00000000..f5da271c --- /dev/null +++ b/evidence/bootstrap-repeat.txt @@ -0,0 +1,6 @@ + Container mtusi-lab4-s3-1 Running + Container mtusi-lab4-s3-1 Waiting + Container mtusi-lab4-s3-1 Healthy + Container mtusi-lab4-s3-init-run-6bff1f84d1f3 Creating + Container mtusi-lab4-s3-init-run-6bff1f84d1f3 Created +Private bucket and restricted API user ready diff --git a/evidence/check.txt b/evidence/check.txt new file mode 100644 index 00000000..9a553306 --- /dev/null +++ b/evidence/check.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/containers-after.txt b/evidence/containers-after.txt new file mode 100644 index 00000000..8ad42cba --- /dev/null +++ b/evidence/containers-after.txt @@ -0,0 +1,7 @@ +{"Service": "api1", "ID": "dfb599607e63", "Image": "mtusi-messenger:lab4", "State": "running", "Health": "healthy", "Status": "Up 9 seconds (healthy)", "Ports": "8080/tcp"} +{"Service": "api2", "ID": "0f6254d1d00b", "Image": "mtusi-messenger:lab4", "State": "running", "Health": "healthy", "Status": "Up 9 seconds (healthy)", "Ports": "8080/tcp"} +{"Service": "cleaner", "ID": "91c5a5e1aecb", "Image": "mtusi-messenger:lab4", "State": "running", "Health": "", "Status": "Up Less than a second", "Ports": "8080/tcp"} +{"Service": "lb", "ID": "2b763a6b13e7", "Image": "haproxy:3.0.8-alpine", "State": "running", "Health": "", "Status": "Up 10 seconds", "Ports": "127.0.0.1:8084->8080/tcp"} +{"Service": "postgres", "ID": "1f7074602484", "Image": "postgres:16.6-bookworm", "State": "running", "Health": "healthy", "Status": "Up 10 seconds (healthy)", "Ports": "5432/tcp"} +{"Service": "s3", "ID": "52d093feabad", "Image": "mtusi-minio:RELEASE.2025-04-22T22-12-26Z", "State": "running", "Health": "healthy", "Status": "Up 10 seconds (healthy)", "Ports": ""} +{"Service": "valkey", "ID": "54a602e6f545", "Image": "valkey/valkey:8.0.2-alpine", "State": "running", "Health": "", "Status": "Up 10 seconds", "Ports": "6379/tcp"} diff --git a/evidence/containers-before.txt b/evidence/containers-before.txt new file mode 100644 index 00000000..d7fa1062 --- /dev/null +++ b/evidence/containers-before.txt @@ -0,0 +1,7 @@ +{"Service": "api1", "ID": "dfb599607e63", "Image": "mtusi-messenger:lab4", "State": "running", "Health": "healthy", "Status": "Up 42 seconds (healthy)", "Ports": "8080/tcp"} +{"Service": "api2", "ID": "0f6254d1d00b", "Image": "mtusi-messenger:lab4", "State": "running", "Health": "healthy", "Status": "Up 42 seconds (healthy)", "Ports": "8080/tcp"} +{"Service": "cleaner", "ID": "91c5a5e1aecb", "Image": "mtusi-messenger:lab4", "State": "running", "Health": "", "Status": "Up 8 seconds", "Ports": "8080/tcp"} +{"Service": "lb", "ID": "2b763a6b13e7", "Image": "haproxy:3.0.8-alpine", "State": "running", "Health": "", "Status": "Up 36 seconds", "Ports": "127.0.0.1:8084->8080/tcp"} +{"Service": "postgres", "ID": "1f7074602484", "Image": "postgres:16.6-bookworm", "State": "running", "Health": "healthy", "Status": "Up 46 seconds (healthy)", "Ports": "5432/tcp"} +{"Service": "s3", "ID": "52d093feabad", "Image": "mtusi-minio:RELEASE.2025-04-22T22-12-26Z", "State": "running", "Health": "healthy", "Status": "Up 4 seconds (healthy)", "Ports": ""} +{"Service": "valkey", "ID": "54a602e6f545", "Image": "valkey/valkey:8.0.2-alpine", "State": "running", "Health": "", "Status": "Up 46 seconds", "Ports": "6379/tcp"} diff --git a/evidence/failover.txt b/evidence/failover.txt new file mode 100644 index 00000000..31722c72 --- /dev/null +++ b/evidence/failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:8084" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 89, "failed_attempts": 3, "first_recovery_seconds": 2.8} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/memory.json b/evidence/memory.json new file mode 100644 index 00000000..dcc861f7 --- /dev/null +++ b/evidence/memory.json @@ -0,0 +1,68 @@ +{ + "concurrency": 10, + "file_bytes": 9201866, + "results": [ + { + "status": 503, + "seconds": 0.597 + }, + { + "status": 201, + "seconds": 0.489 + }, + { + "status": 201, + "seconds": 0.68 + }, + { + "status": 201, + "seconds": 0.624 + }, + { + "status": 201, + "seconds": 0.427 + }, + { + "status": 201, + "seconds": 0.673 + }, + { + "status": 503, + "seconds": 0.57 + }, + { + "status": 201, + "seconds": 0.493 + }, + { + "status": 201, + "seconds": 0.455 + }, + { + "status": 201, + "seconds": 0.645 + } + ], + "samples": [ + { + "seconds": 0.0, + "api1_rss_kib": 107580, + "api2_rss_kib": 109104 + }, + { + "seconds": 0.309, + "api1_rss_kib": 128832, + "api2_rss_kib": 133908 + }, + { + "seconds": 0.639, + "api1_rss_kib": 132796, + "api2_rss_kib": 133912 + } + ], + "peak_rss_kib": { + "api1": 132796, + "api2": 133912 + }, + "sampling_note": "Sequential /proc sampling; very brief peaks may be missed. 503 is explicit admission control." +} \ No newline at end of file diff --git a/evidence/memory.txt b/evidence/memory.txt new file mode 100644 index 00000000..b3783434 --- /dev/null +++ b/evidence/memory.txt @@ -0,0 +1,51 @@ +{ + "concurrency": 10, + "file_bytes": 9201866, + "results": [ + { + "status": 503, + "seconds": 0.597 + }, + { + "status": 201, + "seconds": 0.489 + }, + { + "status": 201, + "seconds": 0.68 + }, + { + "status": 201, + "seconds": 0.624 + }, + { + "status": 201, + "seconds": 0.427 + }, + { + "status": 201, + "seconds": 0.673 + }, + { + "status": 503, + "seconds": 0.57 + }, + { + "status": 201, + "seconds": 0.493 + }, + { + "status": 201, + "seconds": 0.455 + }, + { + "status": 201, + "seconds": 0.645 + } + ], + "peak_rss_kib": { + "api1": 132796, + "api2": 133912 + }, + "sampling_note": "Sequential /proc sampling; very brief peaks may be missed. 503 is explicit admission control." +} diff --git a/evidence/outage.txt b/evidence/outage.txt new file mode 100644 index 00000000..20efbe40 --- /dev/null +++ b/evidence/outage.txt @@ -0,0 +1,9 @@ +PASS: interrupted upload did not create an attachment + Container mtusi-lab4-s3-1 Stopping + Container mtusi-lab4-s3-1 Stopped +PASS: unavailable S3 returns 503 from API + Container mtusi-lab4-s3-1 Starting + Container mtusi-lab4-s3-1 Started + Container mtusi-lab4-s3-1 Waiting + Container mtusi-lab4-s3-1 Healthy +PASS: S3 recovery preserves the original bytes diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..1ce9c3f0 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:8084" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..fac765a8 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "http://localhost:8084" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/storage-checks.txt b/evidence/storage-checks.txt new file mode 100644 index 00000000..a061083f --- /dev/null +++ b/evidence/storage-checks.txt @@ -0,0 +1 @@ +PASS: private bucket, failed finalization recovery, active lock protection, grace period, ready protection, repeated cleanup diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 00000000..612422ba --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1 @@ +PASS: JPEG round-trip, invalid files, ACL, cross-chat references, concurrent idempotency diff --git a/evidence/unit.txt b/evidence/unit.txt new file mode 100644 index 00000000..dba2b417 --- /dev/null +++ b/evidence/unit.txt @@ -0,0 +1,10 @@ +test_mime_substitution (__main__.Images) ... ok +test_not_image (__main__.Images) ... ok +test_pixel_limit_before_decode (__main__.Images) ... ok +test_png_and_jpeg (__main__.Images) ... ok +test_truncated_pixels (__main__.Images) ... ok + +---------------------------------------------------------------------- +Ran 5 tests in 0.714s + +OK diff --git a/evidence/validate.txt b/evidence/validate.txt new file mode 100644 index 00000000..16fc60b5 --- /dev/null +++ b/evidence/validate.txt @@ -0,0 +1,4 @@ +.venv/bin/python scripts/validate_openapi.py +/Users/sleepy13/Desktop/projects/vp/mtusi2026lab4/.venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020 + warnings.warn( +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. diff --git a/infra/s3/Dockerfile b/infra/s3/Dockerfile new file mode 100644 index 00000000..90713ce6 --- /dev/null +++ b/infra/s3/Dockerfile @@ -0,0 +1,23 @@ +# Build the pinned upstream releases: public MinIO registry images are unavailable. +FROM golang:1.24.2-bookworm AS minio-build +WORKDIR /src +RUN curl -fsSL https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-04-22T22-12-26Z | tar xz --strip-components=1 +RUN CGO_ENABLED=0 go build -trimpath -o /out/minio . + +FROM golang:1.24.2-bookworm AS mc-build +WORKDIR /src +RUN curl -fsSL https://codeload.github.com/minio/mc/tar.gz/refs/tags/RELEASE.2025-04-16T18-13-26Z | tar xz --strip-components=1 +RUN CGO_ENABLED=0 go build -trimpath -o /out/mc . + +FROM debian:bookworm-20250407-slim AS runtime +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && rm -rf /var/lib/apt/lists/* + +FROM runtime AS server +COPY --from=minio-build /out/minio /usr/local/bin/minio +COPY --from=minio-build /src/LICENSE /usr/share/licenses/minio/LICENSE +ENTRYPOINT ["minio"] + +FROM runtime AS client +COPY --from=mc-build /out/mc /usr/local/bin/mc +COPY --from=mc-build /src/LICENSE /usr/share/licenses/mc/LICENSE +ENTRYPOINT ["mc"] diff --git a/scripts/verify.py b/scripts/verify.py index 23b958a0..e152bd88 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -1,5 +1,6 @@ """Run all checks and save actual outputs. Stop on the first failure.""" import os +import json from pathlib import Path import subprocess import sys @@ -10,8 +11,13 @@ os.environ.setdefault('BASE_URL','http://localhost:8084') def run(name, args, stdin=None): result=subprocess.run(args,input=stdin,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT) - (root/'evidence'/name).write_text(result.stdout) - print(result.stdout,end='') + output = result.stdout + if name.startswith('containers-') and result.returncode == 0: + fields = ('Service', 'ID', 'Image', 'State', 'Health', 'Status', 'Ports') + output = '\n'.join(json.dumps({key: row.get(key) for key in fields}) + for row in map(json.loads, output.splitlines())) + '\n' + (root/'evidence'/name).write_text(output) + print(output,end='') if result.returncode: raise SystemExit(result.returncode) @@ -36,5 +42,6 @@ finally: subprocess.run(['docker','compose','start','api1','api2'],check=True) # Compose waits for the API's actual readiness after restoring the replica. subprocess.run(['docker','compose','up','-d','--wait','api1','api2'],check=True) +run('attachment-failover.txt',[sys.executable,'student-tests/attachment_failover.py']) run('memory.txt',[sys.executable,'student-tests/memory.py']) print('All requested checks passed; actual results are in evidence/.') diff --git a/student-tests/attachment_failover.py b/student-tests/attachment_failover.py new file mode 100644 index 00000000..50179327 --- /dev/null +++ b/student-tests/attachment_failover.py @@ -0,0 +1,34 @@ +"""Stop the exact replica that accepted the upload, then compare original bytes.""" +import hashlib +from pathlib import Path +import subprocess +import sys +import time + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) +from client import Client, Failure, check + +c = Client(timeout=10) +a, b, _, chat = c.bootstrap() +png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes() +result = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png', + 201, actor=a, raw=png, headers={'Content-Type': 'image/png'}, schema='Attachment') +target = result['headers']['X-Instance-Id'] +check(target in ('api1', 'api2'), 'unknown upload replica') +try: + subprocess.run(['docker', 'compose', 'stop', target], check=True) + deadline = time.monotonic() + 20 + while True: + try: + downloaded = c.call('GET', '/api/v1/attachments/' + result['json']['id'] + '/content', actor=b) + break + except Failure: + if time.monotonic() >= deadline: + raise + time.sleep(0.5) + check(downloaded['headers']['X-Instance-Id'] != target, 'uploader still serves download') + check(downloaded['bytes'] == png, 'original changed after uploader stopped') + print('PASS: upload=' + target + ', download=' + downloaded['headers']['X-Instance-Id'] + + ', sha256=' + hashlib.sha256(png).hexdigest()) +finally: + subprocess.run(['docker', 'compose', 'up', '-d', '--wait', 'api1', 'api2'], check=True) diff --git a/student-tests/storage_checks.py b/student-tests/storage_checks.py index a6a7b446..4a19b376 100644 --- a/student-tests/storage_checks.py +++ b/student-tests/storage_checks.py @@ -38,6 +38,12 @@ try: with psycopg.connect(dsn) as db: db.execute("UPDATE attachments SET status='ready' WHERE id=%s", (ids[0],)) db.rollback() + # Even an old intent must survive while a live finalization holds its lock. + with psycopg.connect(dsn) as active: + active.execute('SELECT id FROM attachments WHERE id=%s FOR UPDATE', (ids[0],)) + sweep() + storage.client.head_object(Bucket=storage.BUCKET, Key=keys[0]) + assert active.execute('SELECT status FROM attachments WHERE id=%s', (ids[0],)).fetchone()[0] == 'pending' sweep() sweep() # Idempotent after completion. with psycopg.connect(dsn) as db: @@ -50,7 +56,7 @@ try: assert error.response['ResponseMetadata']['HTTPStatusCode']==404 for key in keys[1:]: storage.client.head_object(Bucket=storage.BUCKET,Key=key) - print('PASS: private bucket, failed finalization recovery, grace period, ready protection, repeated cleanup') + print('PASS: private bucket, failed finalization recovery, active lock protection, grace period, ready protection, repeated cleanup') finally: for key in keys: storage.client.delete_object(Bucket=storage.BUCKET,Key=key) diff --git a/student-tests/verify.py b/student-tests/verify.py index e4a2e384..78721bce 100644 --- a/student-tests/verify.py +++ b/student-tests/verify.py @@ -1,11 +1,13 @@ """Black-box grade-4 checks; creates only synthetic data on the local lab.""" from concurrent.futures import ThreadPoolExecutor import hashlib +import io import json from pathlib import Path import sys import threading import uuid +from PIL import Image from urllib.parse import quote sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, check @@ -14,6 +16,17 @@ c = Client(timeout=45) a,b,e,chat = c.bootstrap() base = '/api/v1/chats/' + chat['id'] att, png = c.attachment(a, chat) +# Exercise the second supported format through both stores, not only Pillow. +jpeg_file = io.BytesIO() +Image.new('RGB', (320, 200), (20, 30, 40)).save(jpeg_file, 'JPEG') +jpeg = jpeg_file.getvalue() +jpeg_att = c.call('POST', base+'/attachments?filename=photo.jpg', 201, actor=a, + raw=jpeg, headers={'Content-Type': 'image/jpeg'}, schema='Attachment')['json'] +check(jpeg_att['sha256'] == hashlib.sha256(jpeg).hexdigest(), 'JPEG checksum differs') +check(jpeg_att['size_bytes'] == len(jpeg), 'JPEG length differs') +jpeg_download = c.call('GET', '/api/v1/attachments/'+jpeg_att['id']+'/content', actor=b) +check(jpeg_download['bytes'] == jpeg, 'JPEG original differs') +check(jpeg_download['headers'].get_content_type() == 'image/jpeg', 'JPEG MIME differs') for name in ['../x.png', 'a\\b.png', '\x00.png', '\n.png']: c.call('POST', base+'/attachments?filename='+quote(name, safe=''), 400, actor=a, raw=png, headers={'Content-Type':'image/png'}) @@ -43,4 +56,4 @@ c.call('POST',base+'/messages',409,actor=a,body={'text':'different'},headers={'I # Default [] and explicit [] are equivalent. c.call('POST',base+'/messages',201,actor=a,body={'text':'one logical message','attachment_ids':[]}, headers={'Idempotency-Key':key},schema='Message') -print('PASS: invalid files, ACL, cross-chat references, concurrent idempotency') +print('PASS: JPEG round-trip, invalid files, ACL, cross-chat references, concurrent idempotency')