diff --git a/README.md b/README.md index 465d80d..a607238 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ Научиться находить причину деградации через метрики, логи и трассы всей системы, включая фоновую обработку. -В этой реализации сохранён сервер Lab 5 и добавлены OpenTelemetry-инструментация, Collector, Prometheus, Loki, Tempo, Grafana, alert rules и эксперимент по sampling. Язык и framework свободные; UI не обязателен. +Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен. [Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md) ## Откуда начинаем -Бизнес-API и фоновый pipeline перенесены из lab5; контракт не меняется. Стенд сохраняет API-реплики, PostgreSQL, S3, RabbitMQ, publisher, worker и reconciler. +Перенесите минимум lab5. Бизнес-API не меняется. Должны оставаться API-реплики, БД, S3, broker и worker. **Архитектура:** API/worker → OTLP → OTel Collector → хранилища metrics/logs/traces → Grafana; queue context связывает API и worker. @@ -47,24 +47,23 @@ ## Как начать и проверить ```sh -# Локальный offline check, Python 3.9+: +# Работает прямо в skeleton, Python 3.9+; приложение не запускается: make check -python3 -m venv .venv -.venv/bin/python -m pip install -r requirements-dev.txt -cp .env.example .env -scripts/bootstrap-secrets.sh -docker compose --env-file .env config --quiet -docker compose --env-file .env up -d --build -# Дождитесь health/ready. По умолчанию API публикуется на localhost:8080. -make test PYTHON=.venv/bin/python BASE_URL=http://localhost:8080 +# После реализации запустите свой сервер/стенд по REPORT.md. +# По умолчанию тест использует http://localhost:8080. +make test ``` -`.env.example` содержит локальные настройки без секретов. Секреты генерируются в `secrets/` и не должны коммититься. `compose.example.yaml` — worksheet с пустым `services`, реальный запускаемый стенд — `compose.yaml`. Образы закреплены версиями, данные приложения и трёх backend хранятся в named volumes. +`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость. -Для полной OpenAPI-валидации установите `requirements-dev.txt` и выполните `make validate PYTHON=.venv/bin/python`. Основные локальные проверки pipeline: `make test-worker`, `make test-reconcile`, `make test-pipeline-faults`. Сводный отчёт о затратах sampling запускается после старта стенда командой `make benchmark-observability PYTHON=.venv/bin/python BASE_URL=http://localhost:8080`. - -Grafana доступна на `http://localhost:3000`; пароль администратора находится в локальном `secrets/grafana_admin_password`. OTLP endpoints и telemetry backends доступны только внутри Compose-сети. При занятом порте задайте другой `APP_PORT` в локальном `.env` и соответствующий `BASE_URL`. +```sh +# Compose-вариант после реализации: +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +# Дождитесь /health/ready; затем make test. +# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md. +``` Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): diff --git a/evidence/track1-observability-cost.json b/evidence/track1-observability-cost.json index 8a14325..63dd98f 100644 --- a/evidence/track1-observability-cost.json +++ b/evidence/track1-observability-cost.json @@ -8,7 +8,7 @@ "warmup_seconds": 3, "telemetry_flush_wait_seconds": 15, "hardware": { - "platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O", + "platform": "macOS-27.2.1-arm64-arm-64bit-Mach-O", "processor": "arm", "logical_cpus": 10 }, @@ -31,22 +31,22 @@ "workload": "paced synthetic POST messages; no automatic retries", "requested_duration_seconds": 15, "target_rps": 20, - "elapsed_seconds": 16.901, + "elapsed_seconds": 17.135, "concurrency": 2, "successful_requests": 300, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 17.75, + "successful_rps": 17.508, "successful_latency_ms": { - "p50": 7.449, - "p95": 12.198, - "p99": 14.054 + "p50": 8.449, + "p95": 15.118, + "p99": 21.618 }, "docker_resource_samples": 4, "docker_resources": { - "mean_cpu_percent_sum": 17.18, - "peak_cpu_percent_sum": 46.29, - "peak_memory_bytes_sum": 331140298, + "mean_cpu_percent_sum": 21.28, + "peak_cpu_percent_sum": 38.75, + "peak_memory_bytes_sum": 567678072, "services": [ "api", "worker", @@ -56,15 +56,15 @@ } }, "window_unix_seconds": { - "start": 1793781279, - "end": 1793781296 + "start": 1794559044, + "end": 1794559061 }, "sampled_message_trace_count": 0, "estimated_spans_per_message_trace": 0.0, "persistent_storage_bytes_delta": { - "prometheus": 25354, + "prometheus": 1492625, "loki": 0, - "tempo": 122589 + "tempo": 0 }, "estimated_spans_not_recorded": 2400.0 }, @@ -76,22 +76,22 @@ "workload": "paced synthetic POST messages; no automatic retries", "requested_duration_seconds": 15, "target_rps": 20, - "elapsed_seconds": 17.678, + "elapsed_seconds": 18.348, "concurrency": 2, "successful_requests": 300, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 16.97, + "successful_rps": 16.35, "successful_latency_ms": { - "p50": 8.22, - "p95": 14.766, - "p99": 37.456 + "p50": 8.284, + "p95": 15.915, + "p99": 18.98 }, "docker_resource_samples": 4, "docker_resources": { - "mean_cpu_percent_sum": 25.32, - "peak_cpu_percent_sum": 49.25, - "peak_memory_bytes_sum": 340199994, + "mean_cpu_percent_sum": 31.85, + "peak_cpu_percent_sum": 41.59, + "peak_memory_bytes_sum": 550523370, "services": [ "api", "worker", @@ -101,15 +101,15 @@ } }, "window_unix_seconds": { - "start": 1793781337, - "end": 1793781354 + "start": 1794559100, + "end": 1794559118 }, "sampled_message_trace_count": 300, "estimated_spans_per_message_trace": 8.0, "persistent_storage_bytes_delta": { - "prometheus": 27422, - "loki": 240231, - "tempo": 428182 + "prometheus": 36951, + "loki": 204007, + "tempo": 422028 }, "estimated_spans_not_recorded": 0.0 }, @@ -121,22 +121,22 @@ "workload": "paced synthetic POST messages; no automatic retries", "requested_duration_seconds": 15, "target_rps": 20, - "elapsed_seconds": 16.811, + "elapsed_seconds": 17.76, "concurrency": 2, "successful_requests": 300, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 17.845, + "successful_rps": 16.891, "successful_latency_ms": { - "p50": 6.822, - "p95": 12.894, - "p99": 14.415 + "p50": 7.793, + "p95": 14.838, + "p99": 16.862 }, "docker_resource_samples": 4, "docker_resources": { - "mean_cpu_percent_sum": 26.23, - "peak_cpu_percent_sum": 47.71, - "peak_memory_bytes_sum": 352195705, + "mean_cpu_percent_sum": 15.26, + "peak_cpu_percent_sum": 36.45, + "peak_memory_bytes_sum": 550554827, "services": [ "api", "worker", @@ -146,15 +146,15 @@ } }, "window_unix_seconds": { - "start": 1793781394, - "end": 1793781411 + "start": 1794559157, + "end": 1794559175 }, "sampled_message_trace_count": 88, "estimated_spans_per_message_trace": 8.0, "persistent_storage_bytes_delta": { - "prometheus": 27362, - "loki": -7107212, - "tempo": 4092487 + "prometheus": 40456, + "loki": 269949, + "tempo": 1026146 }, "estimated_spans_not_recorded": 1696.0 }, @@ -166,22 +166,22 @@ "workload": "paced synthetic POST messages; no automatic retries", "requested_duration_seconds": 15, "target_rps": 20, - "elapsed_seconds": 17.248, + "elapsed_seconds": 18.355, "concurrency": 2, "successful_requests": 300, "failed_requests": 0, "error_ratio": 0.0, - "successful_rps": 17.393, + "successful_rps": 16.344, "successful_latency_ms": { - "p50": 7.351, - "p95": 13.809, - "p99": 17.187 + "p50": 7.625, + "p95": 14.84, + "p99": 18.012 }, "docker_resource_samples": 4, "docker_resources": { - "mean_cpu_percent_sum": 28.82, - "peak_cpu_percent_sum": 49.75, - "peak_memory_bytes_sum": 339979794, + "mean_cpu_percent_sum": 22.53, + "peak_cpu_percent_sum": 39.51, + "peak_memory_bytes_sum": 550198311, "services": [ "api", "worker", @@ -191,17 +191,17 @@ } }, "window_unix_seconds": { - "start": 1793781454, - "end": 1793781471 + "start": 1794559215, + "end": 1794559233 }, - "sampled_message_trace_count": 25, + "sampled_message_trace_count": 38, "estimated_spans_per_message_trace": 8.0, "persistent_storage_bytes_delta": { - "prometheus": 31886, - "loki": 239322, - "tempo": 106458 + "prometheus": 42617, + "loki": 240135, + "tempo": 1924562 }, - "estimated_spans_not_recorded": 2200.0 + "estimated_spans_not_recorded": 2096.0 } ], "balanced_configuration": "sample-25-percent" diff --git a/infra/otel/README.md b/infra/otel/README.md index 58bf90b..c46fe89 100644 --- a/infra/otel/README.md +++ b/infra/otel/README.md @@ -1,11 +1,7 @@ -# OpenTelemetry deployment +# Конфигурация наблюдаемости — реализовать -The Compose stack pins Collector Contrib 0.163.2, Prometheus 2.55.1, Loki 3.3.2, Tempo 2.7.1, and Grafana 11.4.0. OTLP gRPC/HTTP listeners and backend query ports are private to the Compose network; only the API load balancer and Grafana UI bind to loopback. +Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend. -`collector.yaml` receives all three OTLP signals. Metrics are exposed to Prometheus on the private Collector endpoint; logs are exported to Loki's OTLP receiver and traces to Tempo. Memory limiter and batch processors bound Collector memory. Trace/log exporter queues are capped at 256 requests and retry for at most 30 seconds; SDK span/log queues are capped at 4096 records with batches of at most 512. On backend outage, telemetry is dropped after bounded retries rather than blocking API work indefinitely. Metrics are pull-exported and can be missed while Prometheus is unavailable. +Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`. -Loki, Tempo, and Prometheus retain local data in named volumes. Grafana datasources, the dashboard, and Prometheus alert rules are provisioned from this directory. Prometheus evaluates the 7-day rolling API availability SLI and local alerts; use the alert annotations and `REPORT.md` runbooks to investigate. - -API, publisher, and worker share a W3C trace context through the database outbox and the broker payload. Application logs contain only structured metadata, trace/span IDs, request IDs, route templates, and sanitized event names. Message bodies, credentials, filenames, and signed URLs are not exported. - -HTTP request duration, worker job duration, and attachment time-to-ready histograms use explicit second-based buckets. HTTP buckets are dense from 1 ms through 100 ms to resolve normal API latency; job buckets extend to 60 s and end-to-end readiness buckets to 600 s. This keeps Prometheus percentile interpolation useful across all three time scales. +Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён. diff --git a/infra/otel/grafana/dashboards/messenger.json b/infra/otel/grafana/dashboards/messenger.json index 04e026b..7e37518 100644 --- a/infra/otel/grafana/dashboards/messenger.json +++ b/infra/otel/grafana/dashboards/messenger.json @@ -119,7 +119,7 @@ "gridPos": {"h": 7, "w": 8, "x": 16, "y": 22}, "id": 10, "options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}}, - "targets": [{"expr": "max(messenger_process_memory_usage)", "legendFormat": "RSS", "refId": "A"}], + "targets": [{"expr": "max(messenger_process_memory_usage_bytes)", "legendFormat": "RSS", "refId": "A"}], "title": "Process memory", "type": "timeseries" }, @@ -129,7 +129,7 @@ "gridPos": {"h": 7, "w": 8, "x": 0, "y": 29}, "id": 11, "options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}}, - "targets": [{"expr": "max(messenger_process_cpu_utilization)", "legendFormat": "CPU / core", "refId": "A"}], + "targets": [{"expr": "max(messenger_process_cpu_utilization_ratio)", "legendFormat": "CPU / core", "refId": "A"}], "title": "Process CPU utilization", "type": "timeseries" },