reyalysed grade 3
This commit is contained in:
+3
-9
@@ -98,13 +98,7 @@ IMAGE_CPU_SECONDS=20
|
|||||||
JOB_RETRY_MAX_SECONDS=120
|
JOB_RETRY_MAX_SECONDS=120
|
||||||
FAILED_STAGING_RETENTION_SECONDS=604800
|
FAILED_STAGING_RETENTION_SECONDS=604800
|
||||||
|
|
||||||
# Дополнительные предложения skeleton lab6; пока не подключены к перенесённому стенду.
|
# Наблюдаемость: SDK экспортирует HTTP/protobuf в Collector.
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
OTEL_ENABLED=true
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
|
||||||
MAX_UPLOAD_BYTES=10485760
|
|
||||||
MAX_IMAGE_PIXELS=40000000
|
|
||||||
BROKER_URL_FILE=/run/secrets/broker_url
|
|
||||||
OTEL_SERVICE_NAME=messenger-api
|
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
GRAFANA_HOST_PORT=13000
|
||||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
|
||||||
|
|||||||
@@ -36,3 +36,5 @@ venv/
|
|||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
/docs/
|
/docs/
|
||||||
|
|
||||||
|
.verification-error.log
|
||||||
|
|||||||
@@ -13,9 +13,11 @@ TEST_PROJECT ?= messenger-test
|
|||||||
TEST_LB_PORT ?= 28080
|
TEST_LB_PORT ?= 28080
|
||||||
TEST_DB_PORT ?= $(DB_HOST_PORT)
|
TEST_DB_PORT ?= $(DB_HOST_PORT)
|
||||||
TEST_REDIS_PORT ?= $(REDIS_HOST_PORT)
|
TEST_REDIS_PORT ?= $(REDIS_HOST_PORT)
|
||||||
|
TEST_GRAFANA_PORT ?= 23000
|
||||||
|
GRAFANA_URL ?= http://localhost:$(or $(GRAFANA_HOST_PORT),13000)
|
||||||
TEST_BASE_URL = http://localhost:$(TEST_LB_PORT)
|
TEST_BASE_URL = http://localhost:$(TEST_LB_PORT)
|
||||||
TEST_ENV = COMPOSE_PROJECT_NAME=$(TEST_PROJECT) COMPOSE_FILE=compose.yaml:compose.test.yaml \
|
TEST_ENV = COMPOSE_PROJECT_NAME=$(TEST_PROJECT) COMPOSE_FILE=compose.yaml:compose.test.yaml \
|
||||||
LB_HOST_PORT=$(TEST_LB_PORT) DB_HOST_PORT=$(TEST_DB_PORT) REDIS_HOST_PORT=$(TEST_REDIS_PORT)
|
LB_HOST_PORT=$(TEST_LB_PORT) DB_HOST_PORT=$(TEST_DB_PORT) REDIS_HOST_PORT=$(TEST_REDIS_PORT) GRAFANA_HOST_PORT=$(TEST_GRAFANA_PORT)
|
||||||
TEST_COMPOSE = $(TEST_ENV) $(COMPOSE)
|
TEST_COMPOSE = $(TEST_ENV) $(COMPOSE)
|
||||||
|
|
||||||
TEST_DB_PASSWORD = $(if $(wildcard secrets/db_password),$(file <secrets/db_password),$(DB_PASSWORD))
|
TEST_DB_PASSWORD = $(if $(wildcard secrets/db_password),$(file <secrets/db_password),$(DB_PASSWORD))
|
||||||
@@ -28,7 +30,7 @@ export TEST_DATABASE_URL TEST_REDIS_HOST TEST_REDIS_PORT TEST_REDIS_PASSWORD TES
|
|||||||
.PHONY: help init up down restart ps logs migrate migration worker-stop worker-start \
|
.PHONY: help init up down restart ps logs migrate migration worker-stop worker-start \
|
||||||
cleanup-dry-run cleanup-apply check validate test load test-unit test-pipeline \
|
cleanup-dry-run cleanup-apply check validate test load test-unit test-pipeline \
|
||||||
test-nginx test-storage test-outbox test-jobs test-persistence test-failover \
|
test-nginx test-storage test-outbox test-jobs test-persistence test-failover \
|
||||||
test-suite test-stand-up test-stand-destroy
|
test-suite test-stand-up test-stand-destroy test-telemetry test-observability verify clean-stands
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "Запуск: init | up | down | restart | ps | logs SERVICE=worker"
|
@echo "Запуск: init | up | down | restart | ps | logs SERVICE=worker"
|
||||||
@@ -39,12 +41,13 @@ help:
|
|||||||
@echo "Сервисы: test-nginx | test-storage | test-outbox | test-jobs"
|
@echo "Сервисы: test-nginx | test-storage | test-outbox | test-jobs"
|
||||||
@echo "Отказы API (по запросу): test-persistence | test-failover"
|
@echo "Отказы API (по запросу): test-persistence | test-failover"
|
||||||
@echo "Автономный прогон с удалением тестового стенда: test-suite"
|
@echo "Автономный прогон с удалением тестового стенда: test-suite"
|
||||||
|
@echo "Наблюдаемость: test-observability; полный прогон с очисткой: verify"
|
||||||
|
|
||||||
init:
|
init:
|
||||||
$(PYTHON) scripts/init_local.py
|
$(PYTHON) scripts/init_local.py
|
||||||
|
|
||||||
up:
|
up:
|
||||||
$(COMPOSE) up -d --build --wait --wait-timeout 120
|
$(COMPOSE) up -d --build --wait --wait-timeout 180
|
||||||
|
|
||||||
down:
|
down:
|
||||||
$(COMPOSE) down
|
$(COMPOSE) down
|
||||||
@@ -88,6 +91,21 @@ test:
|
|||||||
load:
|
load:
|
||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
test-telemetry:
|
||||||
|
$(PYTHON) -m pytest -q student-tests/test_telemetry.py
|
||||||
|
|
||||||
|
# Проверка на уже запущенном стенде; явно включает два ограниченных отказа.
|
||||||
|
test-observability:
|
||||||
|
$(PYTHON) -m scripts.check_observability --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)" --incidents --restart-telemetry
|
||||||
|
|
||||||
|
# Один стенд, один прогон, удаление контейнеров/томов/образов даже при ошибке.
|
||||||
|
verify:
|
||||||
|
$(PYTHON) -m scripts.deployment verify
|
||||||
|
|
||||||
|
# Удаление основного и тестового стендов; .env/secrets сохраняются.
|
||||||
|
clean-stands:
|
||||||
|
$(PYTHON) -m scripts.deployment clean --apply
|
||||||
|
|
||||||
# Все сохранённые регрессионные тесты запускаются явно; PYTEST_ARGS выбирает подмножество.
|
# Все сохранённые регрессионные тесты запускаются явно; PYTEST_ARGS выбирает подмножество.
|
||||||
test-unit:
|
test-unit:
|
||||||
$(TEST_ENV) $(PYTHON) -m pytest -q $(PYTEST_ARGS)
|
$(TEST_ENV) $(PYTHON) -m pytest -q $(PYTEST_ARGS)
|
||||||
@@ -115,7 +133,7 @@ test-failover:
|
|||||||
|
|
||||||
# Отдельные PostgreSQL/Redis нужны для локальных тестов; тестовая БД создаётся явно.
|
# Отдельные PostgreSQL/Redis нужны для локальных тестов; тестовая БД создаётся явно.
|
||||||
test-stand-up:
|
test-stand-up:
|
||||||
$(TEST_COMPOSE) up -d --build --wait --wait-timeout 120
|
$(TEST_COMPOSE) up -d --build --wait --wait-timeout 180
|
||||||
$(TEST_COMPOSE) exec -T postgres sh -c 'psql -U "$$POSTGRES_USER" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname = '\''$${POSTGRES_DB}_test'\''" | grep -q 1 || createdb -U "$$POSTGRES_USER" "$${POSTGRES_DB}_test"'
|
$(TEST_COMPOSE) exec -T postgres sh -c 'psql -U "$$POSTGRES_USER" -d postgres -tAc "SELECT 1 FROM pg_database WHERE datname = '\''$${POSTGRES_DB}_test'\''" | grep -q 1 || createdb -U "$$POSTGRES_USER" "$${POSTGRES_DB}_test"'
|
||||||
|
|
||||||
test-stand-destroy:
|
test-stand-destroy:
|
||||||
|
|||||||
@@ -1,46 +1,90 @@
|
|||||||
# Отчёт — лабораторная 6
|
# Отчёт
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор: Григорян Илья Мурадович, БПИ2303.
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Цель: **оценка 4**. Расширения, которые ещё предстоит выполнить, отмечены TODO.
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: TODO после публикации.
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Источники и помощь: OpenTelemetry SDK 1.45.1, FastAPI, SQLAlchemy, Grafana;
|
||||||
|
официальная документация компонентов, помощь Codex.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск
|
||||||
|
|
||||||
Перенесённый стенд lab5 и команды его запуска описаны в [RUNNING.md](RUNNING.md).
|
Python 3.12 и Docker Compose v2. Зависимости закреплены в `requirements.txt`,
|
||||||
Это основа для lab6; телеметрия текущей лабораторной пока не реализована.
|
версии образов — в Dockerfile/Compose. Подробности: [RUNNING.md](RUNNING.md).
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
```sh
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||||
|
make init
|
||||||
|
make up
|
||||||
|
make test
|
||||||
|
make down
|
||||||
|
```
|
||||||
|
|
||||||
## Архитектура и решения
|
API: http://localhost:18081. Grafana: http://localhost:13000/d/messenger-overview.
|
||||||
|
`make init` создаёт отсутствующие `.env`/`secrets/`, миграции и MinIO bootstrap
|
||||||
|
выполняются при запуске. `make down` сохраняет данные; `make clean-stands` намеренно
|
||||||
|
удаляет контейнеры, сети, тома и образы приложения, сохраняя настройки и базовые образы.
|
||||||
|
|
||||||
Из lab5 перенесена реализация уровня 4: API, миграции, PostgreSQL/Redis,
|
## Реализация
|
||||||
MinIO, RabbitMQ, outbox publisher, worker, очистка, crop/WebP, ограниченные
|
|
||||||
повторы с задержкой, failed registry и ручной replay, собственные тесты и
|
|
||||||
проверки отказов. Контракты, публичные проверки и задание lab6 сохранены.
|
|
||||||
Результаты проверок lab5 не считаются доказательствами прохождения lab6.
|
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Две API-реплики за nginx, PostgreSQL, Redis-сессии, приватный MinIO, RabbitMQ,
|
||||||
|
outbox publisher, отдельный worker и cleanup. Сохранены thumbnail/crop/WebP,
|
||||||
|
ограниченные повторы, идемпотентность, failed registry и ручной replay.
|
||||||
|
PostgreSQL — источник истины для metadata/заданий, S3 — для файлов.
|
||||||
|
HTTP 202 возвращается после устойчивого приёма, ack — после фиксации результата.
|
||||||
|
|
||||||
## Доказательства критериев
|
API/worker → OTLP HTTP/protobuf → Collector → Prometheus / Loki / Tempo → Grafana.
|
||||||
|
Prometheus хранит метрики, Loki — структурные логи, Tempo — реальные spans;
|
||||||
|
Grafana читает эти хранилища. История находится в named volumes, retention — 3 дня.
|
||||||
|
Collector: 0.165.0, Prometheus: 3.16.0, Loki: 3.7.10, Tempo: 2.9.0, Grafana: 13.3.1.
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
Dashboard и datasources импортируются из `infra/otel/grafana/`. HTTP:
|
||||||
| --- | --- | --- | --- |
|
`messenger_http_requests_total`, `messenger_http_duration_seconds_*`; worker:
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
`messenger_job_attempts_total`, `messenger_job_duration_seconds_*`.
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
`outcome` относится к фактической попытке, а не уникальной job. Histogram — в секундах;
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
p50/p95/p99 считаются по buckets всех реплик. Error ratio: 5xx / бизнес-запросы без health.
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
Точные PromQL, единицы и остальные сигналы заданы в dashboard JSON.
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
Resource fields: service.name/version/instance.id и deployment.environment.name из
|
||||||
|
APP_ENV. Метрики используют шаблоны маршрутов, method/status class, job type/outcome;
|
||||||
|
пользовательские ID не становятся labels. Логи содержат timestamp, severity, event,
|
||||||
|
trace/span ID; X-Request-Id связывает HTTP-ответ с логом. Тела, credentials, filename,
|
||||||
|
SQL и тексты исключений не отправляются в OTLP. Readiness API не зависит от telemetry.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Проверки и наблюдения
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
`make verify` один раз поднимает отдельный стенд, выполняет регрессию, публичный smoke,
|
||||||
|
проверяет dashboard, корреляцию логов/traces, privacy, сохранность истории и отказы,
|
||||||
|
затем обязательно удаляет стенды и образы приложения. Нагрузка: 10 сообщений/с,
|
||||||
|
10 секунд, до 2 одновременных запросов. Результаты — в `evidence/verification.json`
|
||||||
|
и `evidence/observability.json`, без привязки к учебным критериям.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
Проверенные инциденты: остановка PostgreSQL → 503 и ERROR span со связанным логом;
|
||||||
| --- | --- | --- | --- |
|
постоянная ошибка обработки → failed, счётчик ошибки, затем replay → ready.
|
||||||
| TODO | TODO | TODO | TODO |
|
Диагностика: метрики → Loki event/request ID → trace ID → Tempo status/duration.
|
||||||
|
Точные результаты последнего прогона и CPU/RAM находятся в evidence.
|
||||||
|
Последний прогон: 206 passed in 112.44s (0:01:52); API/наблюдаемость/persistence/failover — PASS.
|
||||||
|
Нагрузка: 100 успешных запросов, 0 ошибок; p50/p95/p99 —
|
||||||
|
31.394 / 63.623 / 70.12 мс. Стенды, тома и образы приложения удалены.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
## TODO для завершения
|
||||||
|
|
||||||
|
- TODO: перенос W3C context API → outbox/broker → worker; producer/consumer spans,
|
||||||
|
DB/S3 spans и цепочка upload → результат с retry.
|
||||||
|
- TODO: queue depth/возраст старейшей job, DB pool, worker saturation и время до ready;
|
||||||
|
добавить запросы и единицы в dashboard.
|
||||||
|
- TODO: определить SLI/SLO и окно; alert rules для error rate и queue lag,
|
||||||
|
проверить firing/resolved и написать краткий runbook.
|
||||||
|
- TODO: проверить недоступность telemetry backend под нагрузкой: бизнес-путь,
|
||||||
|
ограниченность RAM/очередей и потери telemetry; оформить два разбора инцидентов
|
||||||
|
с остановкой worker и деградацией БД.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
Один Docker-host, без HA и защиты от потери диска. HTTP и анонимный Grafana Viewer —
|
||||||
|
только для локального стенда; Tempo использует root для записи в volume.
|
||||||
|
Сейчас API/worker traces независимы, alerts и сквозная связь ещё не реализованы.
|
||||||
|
SDK и Collector имеют ограниченные очереди, но длительный отказ backend пока не измерялся.
|
||||||
|
По наблюдению автора, долгий запуск контейнеров нагревает CPU примерно до 80 °C и выше:
|
||||||
|
проверки выполняются последовательно на одном стенде с немедленной очисткой.
|
||||||
|
|||||||
+37
-65
@@ -1,90 +1,62 @@
|
|||||||
# Запуск перенесённой реализации lab5
|
# Запуск Messenger
|
||||||
|
|
||||||
В lab6 перенесена реализация lab5 для оценки 4: API-реплики за nginx,
|
Нужны Python 3.12 и Docker Compose v2. Версии закреплены в requirements.txt и Compose.
|
||||||
PostgreSQL, Redis для сессий, MinIO для файлов, RabbitMQ, outbox publisher,
|
|
||||||
worker и очистка объектов. Сохранены миграции и собственные тесты.
|
|
||||||
OpenTelemetry, Collector и Grafana из задания lab6 пока не реализованы.
|
|
||||||
|
|
||||||
## Основной стенд
|
|
||||||
|
|
||||||
Нужны Python 3.12 и Docker с Compose v2. Версии Python-зависимостей закреплены
|
|
||||||
в `requirements.txt`, образы — в Dockerfile и Compose.
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
.venv/bin/python -m pip install -r requirements.txt -r requirements-dev.txt
|
.venv/bin/python -m pip install -r requirements.txt -r requirements-dev.txt
|
||||||
make init
|
make init
|
||||||
make check validate
|
|
||||||
make up
|
make up
|
||||||
make test
|
make test
|
||||||
```
|
```
|
||||||
|
|
||||||
`make init` создаёт отсутствующие `.env` и случайные файловые секреты в `secrets/`.
|
`make init` создаёт только отсутствующие `.env` и случайные файловые секреты.
|
||||||
Секреты и данные из lab5 не копируются. Настройки берутся из `.env.example`;
|
Миграции PostgreSQL и приватный bucket/политика MinIO создаются автоматически.
|
||||||
дополнительные переменные skeleton lab6 в конце файла пока не подключены.
|
Основной проект — `messenger`, тестовый — `messenger-test`.
|
||||||
Миграции БД и настройка MinIO выполняются при запуске.
|
|
||||||
`make up` ожидает готовности сервисов. По умолчанию API доступен по
|
- API: http://localhost:18081 (`LB_HOST_PORT`).
|
||||||
http://localhost:18081 (`LB_HOST_PORT`); `make test` и `make load` используют
|
- Grafana: http://localhost:13000/d/messenger-overview (`GRAFANA_HOST_PORT`).
|
||||||
этот порт. Его можно переопределить через `BASE_URL`.
|
- Просмотр Grafana — анонимный Viewer; admin password — `secrets/grafana_admin_password`.
|
||||||
|
- Внутренние API/OTLP/Prometheus/Loki/Tempo порты на хост не публикуются.
|
||||||
|
|
||||||
|
`OTEL_ENABLED` включает экспорт трёх сигналов, `OTEL_EXPORTER_OTLP_ENDPOINT` задаёт
|
||||||
|
Collector, `APP_ENV` — окружение resource attributes. Имена сервисов — messenger-api
|
||||||
|
и messenger-worker. Конфигурация — в `infra/otel/`, метрики/логи/трассы сохраняются в volumes.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
make ps
|
make ps
|
||||||
make logs SERVICE=worker
|
make logs SERVICE=worker
|
||||||
make load
|
make down # данные сохраняются
|
||||||
make down
|
make clean-stands # удалить оба стенда, тома и образы приложения
|
||||||
```
|
```
|
||||||
|
|
||||||
`make down` сохраняет данные. Для **намеренного удаления всех учебных данных**:
|
`.env`, `secrets/`, базовые образы и evidence при очистке сохраняются.
|
||||||
`docker compose --env-file .env down --volumes`.
|
План удаления без применения: `.venv/bin/python -m scripts.deployment clean`.
|
||||||
Compose-проект по умолчанию называется `messenger`, как в lab5: останавливайте
|
|
||||||
предыдущий стенд перед запуском либо используйте отдельный `COMPOSE_PROJECT_NAME`
|
|
||||||
и свободный `LB_HOST_PORT`. Одинаковое имя проекта подключает существующие volumes;
|
|
||||||
для независимого стенда lab6 задайте новое имя до первого запуска.
|
|
||||||
|
|
||||||
## Перенесённые возможности уровня 4
|
## Проверки
|
||||||
|
|
||||||
Загрузка изображения асинхронная: API сохраняет исходник в staging MinIO и
|
`make verify` выполняет один последовательный прогон на одном тестовом стенде:
|
||||||
задание/outbox в PostgreSQL, publisher отправляет задание в устойчивую очередь
|
контракт/OpenAPI, полная регрессия с Redis restart, smoke, короткая нагрузка,
|
||||||
RabbitMQ, worker сохраняет варианты и результат в БД, затем подтверждает доставку.
|
проверки телеметрии и двух отказов, persistence/failover. Очистка выполняется
|
||||||
Сохранены original, JPEG thumbnail, центральный JPEG crop и WebP, ограничения
|
в `finally`, включая ошибку. Результаты — два JSON в `evidence/`.
|
||||||
размера, пикселей, времени, памяти и CPU обработки.
|
Не выполняйте одновременно команды, управляющие тем же стендом.
|
||||||
|
|
||||||
Повторы ограничены бюджетом, задержка растёт со случайным разбросом.
|
Отдельные проверки: `make test-telemetry` без Docker; `make test-observability`
|
||||||
Идемпотентность, lease (временное право worker обрабатывать задание),
|
на уже запущенном стенде (включает ограниченные отказы и восстановление).
|
||||||
реестр неудачных заданий и ручной replay защищают обработку при повторной доставке.
|
`make test-unit` использует тестовую БД; сначала `make test-stand-up`, затем
|
||||||
Очистка сохраняет исходники активных заданий и учитывает сроки хранения ready/failed.
|
`make test-stand-destroy`. Тестовые порты: API 28080, Grafana 23000,
|
||||||
|
PostgreSQL 25432, Redis 26379, только localhost.
|
||||||
|
|
||||||
|
## Задания и файлы
|
||||||
|
|
||||||
|
Загрузка асинхронная: staging/outbox → RabbitMQ → worker → original и JPEG/WebP
|
||||||
|
варианты. Повторы ограничены, готовность — после фиксации объектов и metadata.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
docker compose run --rm --no-deps worker python -m app.core.job_admin list-failed
|
docker compose run --rm --no-deps worker python -m app.core.job_admin list-failed
|
||||||
docker compose run --rm --no-deps worker python -m app.core.job_admin replay JOB_ID --request-id REQUEST_UUID --actor operator --reason dependency_restored
|
docker compose run --rm --no-deps worker python -m app.core.job_admin replay JOB_ID --request-id REQUEST_UUID --actor operator --reason dependency_restored
|
||||||
```
|
```
|
||||||
|
|
||||||
`JOB_ID` и `REQUEST_UUID` замените UUID. Повтор replay с тем же request-id безопасен.
|
Замените UUID; повтор replay с тем же request-id безопасен.
|
||||||
|
`make load` — унаследованный генератор без ограничения частоты, он может упереться
|
||||||
## Проверки
|
в nginx 50 запросов/с. Для штатной проверки используется 10 запросов/с на 10 секунд.
|
||||||
|
|
||||||
`make check` проверяет структуру контракта, `make validate` — OpenAPI.
|
|
||||||
`make test` запускает актуальные публичные тесты lab6 на основном стенде.
|
|
||||||
Собственные тесты lab5 находятся в `student-tests/`:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
make test-stand-up
|
|
||||||
make test-unit
|
|
||||||
make test-pipeline
|
|
||||||
make test BASE_URL=http://localhost:28080
|
|
||||||
make test-stand-destroy
|
|
||||||
```
|
|
||||||
|
|
||||||
Тестовый стенд использует отдельный проект `messenger-test` и порт 28080,
|
|
||||||
а PostgreSQL/Redis публикуются только локально через `compose.test.yaml`.
|
|
||||||
`make test-stand-destroy` удаляет данные тестового стенда.
|
|
||||||
`make test-suite` автоматически поднимает этот стенд, проверяет pipeline,
|
|
||||||
публичный smoke, S3, outbox и очередь, затем удаляет его вместе с данными.
|
|
||||||
Полная регрессия запускается отдельно через `make test-unit`.
|
|
||||||
|
|
||||||
Проверки с намеренными отказами запускаются явно:
|
|
||||||
`make test-jobs`, `make test-outbox`, `make test-persistence`, `make test-failover`.
|
|
||||||
Они останавливают или перезапускают компоненты выбранного Compose-проекта.
|
|
||||||
Для собственных тестов с перезапусками контейнеров: `DOCKER_TESTS=1 make test-unit`.
|
|
||||||
Стенд рассчитан на один Docker-хост; репликация хранилищ и защита от потери диска
|
|
||||||
не реализованы.
|
|
||||||
|
|||||||
+24
-12
@@ -10,6 +10,8 @@ import signal
|
|||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from PIL import features
|
from PIL import features
|
||||||
|
from opentelemetry.context import Context
|
||||||
|
from opentelemetry.trace import SpanKind
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from app.core.background import (
|
from app.core.background import (
|
||||||
@@ -21,6 +23,7 @@ from app.core.background import (
|
|||||||
from app.core.config import Settings
|
from app.core.config import Settings
|
||||||
from app.core.database import create_db_engine, create_session_factory
|
from app.core.database import create_db_engine, create_session_factory
|
||||||
from app.core.jobs import JobSettings
|
from app.core.jobs import JobSettings
|
||||||
|
from app.core.telemetry import Telemetry
|
||||||
from app.domain.attachment_jobs import process_attachment_job
|
from app.domain.attachment_jobs import process_attachment_job
|
||||||
from app.errors.exceptions import ProcessingError
|
from app.errors.exceptions import ProcessingError
|
||||||
from app.schemas.job import JobMessage
|
from app.schemas.job import JobMessage
|
||||||
@@ -67,6 +70,7 @@ async def consume_connected(
|
|||||||
settings: JobSettings,
|
settings: JobSettings,
|
||||||
stop: asyncio.Event,
|
stop: asyncio.Event,
|
||||||
faults: Faults,
|
faults: Faults,
|
||||||
|
telemetry: Telemetry | None = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
consumer = uuid4().hex
|
consumer = uuid4().hex
|
||||||
while not stop.is_set():
|
while not stop.is_set():
|
||||||
@@ -81,15 +85,21 @@ async def consume_connected(
|
|||||||
await broker.reject_invalid(delivery.id)
|
await broker.reject_invalid(delivery.id)
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
async with factory() as session:
|
telemetry = telemetry or Telemetry("messenger-worker", enabled=False)
|
||||||
acknowledge = await process_attachment_job(
|
with telemetry.tracer.start_as_current_span(
|
||||||
session,
|
"attachment.process.v1", context=Context(), kind=SpanKind.CONSUMER,
|
||||||
storage,
|
record_exception=False, set_status_on_exception=False,
|
||||||
message,
|
attributes={"messaging.system": "rabbitmq", "job.type": message.type},
|
||||||
settings,
|
):
|
||||||
after_object=faults.after_object,
|
telemetry.event("job.received", job_id=str(message.job_id),
|
||||||
before_processing=faults.before_processing,
|
attachment_id=str(message.attachment_id))
|
||||||
)
|
async with factory() as session:
|
||||||
|
acknowledge = await process_attachment_job(
|
||||||
|
session, storage, message, settings,
|
||||||
|
after_object=faults.after_object,
|
||||||
|
before_processing=faults.before_processing,
|
||||||
|
telemetry=telemetry,
|
||||||
|
)
|
||||||
except ProcessingError:
|
except ProcessingError:
|
||||||
await broker.reject_invalid(delivery.id)
|
await broker.reject_invalid(delivery.id)
|
||||||
else:
|
else:
|
||||||
@@ -104,10 +114,10 @@ async def consume_connected(
|
|||||||
await wait_or_stop(stop, settings.publisher_poll_seconds)
|
await wait_or_stop(stop, settings.publisher_poll_seconds)
|
||||||
|
|
||||||
|
|
||||||
async def consume(factory, storage, settings, stop, faults) -> None:
|
async def consume(factory, storage, settings, stop, faults, telemetry=None) -> None:
|
||||||
broker = JobBroker(settings)
|
broker = JobBroker(settings)
|
||||||
try:
|
try:
|
||||||
await consume_connected(factory, storage, broker, settings, stop, faults)
|
await consume_connected(factory, storage, broker, settings, stop, faults, telemetry)
|
||||||
finally:
|
finally:
|
||||||
await broker.aclose()
|
await broker.aclose()
|
||||||
|
|
||||||
@@ -115,6 +125,7 @@ async def consume(factory, storage, settings, stop, faults) -> None:
|
|||||||
async def run_worker(faults: Faults) -> None:
|
async def run_worker(faults: Faults) -> None:
|
||||||
settings = Settings()
|
settings = Settings()
|
||||||
jobs = JobSettings()
|
jobs = JobSettings()
|
||||||
|
telemetry = Telemetry("messenger-worker")
|
||||||
logging.basicConfig(level=settings.log_level)
|
logging.basicConfig(level=settings.log_level)
|
||||||
if not features.check("webp"):
|
if not features.check("webp"):
|
||||||
logging.error("Pillow requires WebP support for the image worker")
|
logging.error("Pillow requires WebP support for the image worker")
|
||||||
@@ -127,7 +138,7 @@ async def run_worker(faults: Faults) -> None:
|
|||||||
factory = create_session_factory(engine)
|
factory = create_session_factory(engine)
|
||||||
async with asyncio.TaskGroup() as group:
|
async with asyncio.TaskGroup() as group:
|
||||||
tasks = [
|
tasks = [
|
||||||
group.create_task(consume(factory, storage, jobs, stop, faults))
|
group.create_task(consume(factory, storage, jobs, stop, faults, telemetry))
|
||||||
for _ in range(jobs.worker_concurrency)
|
for _ in range(jobs.worker_concurrency)
|
||||||
]
|
]
|
||||||
await stop.wait()
|
await stop.wait()
|
||||||
@@ -138,6 +149,7 @@ async def run_worker(faults: Faults) -> None:
|
|||||||
if storage is not None:
|
if storage is not None:
|
||||||
await storage.aclose()
|
await storage.aclose()
|
||||||
await engine.dispose()
|
await engine.dispose()
|
||||||
|
await asyncio.to_thread(telemetry.shutdown)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
"""Явная OTLP-инструментация: экспортируются только выбранные технические поля."""
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
|
||||||
|
from opentelemetry import trace
|
||||||
|
from opentelemetry.context import Context
|
||||||
|
from opentelemetry._logs import SeverityNumber
|
||||||
|
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||||
|
from opentelemetry.sdk._logs import LoggerProvider
|
||||||
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
|
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||||
|
from opentelemetry.sdk.resources import Resource
|
||||||
|
from opentelemetry.sdk.trace import TracerProvider
|
||||||
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
|
||||||
|
HTTP_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
|
||||||
|
JOB_BUCKETS = (0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60)
|
||||||
|
|
||||||
|
|
||||||
|
class Telemetry:
|
||||||
|
def __init__(self, service: str, instance: str | None = None, *, enabled=None):
|
||||||
|
self.enabled = (os.getenv("OTEL_ENABLED", "false").lower() == "true"
|
||||||
|
if enabled is None else enabled)
|
||||||
|
self.service = service
|
||||||
|
if not self.enabled:
|
||||||
|
self.tracer = trace.NoOpTracerProvider().get_tracer("messenger")
|
||||||
|
return
|
||||||
|
endpoint = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||||
|
resource = Resource({
|
||||||
|
"service.name": service,
|
||||||
|
"service.version": "1.6.0",
|
||||||
|
"service.instance.id": instance or socket.gethostname(),
|
||||||
|
"deployment.environment.name": os.getenv("APP_ENV", "development"),
|
||||||
|
})
|
||||||
|
self.traces = TracerProvider(resource=resource)
|
||||||
|
self.traces.add_span_processor(BatchSpanProcessor(
|
||||||
|
OTLPSpanExporter(endpoint=endpoint + "/v1/traces", timeout=2),
|
||||||
|
max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=1000,
|
||||||
|
))
|
||||||
|
self.tracer = self.traces.get_tracer("messenger", "1.6.0")
|
||||||
|
self.logs = LoggerProvider(resource=resource)
|
||||||
|
self.logs.add_log_record_processor(BatchLogRecordProcessor(
|
||||||
|
OTLPLogExporter(endpoint=endpoint + "/v1/logs", timeout=2),
|
||||||
|
max_queue_size=512, max_export_batch_size=128, schedule_delay_millis=1000,
|
||||||
|
))
|
||||||
|
self.logger = self.logs.get_logger("messenger", "1.6.0")
|
||||||
|
self.metrics = MeterProvider(resource=resource, metric_readers=[
|
||||||
|
PeriodicExportingMetricReader(
|
||||||
|
OTLPMetricExporter(endpoint=endpoint + "/v1/metrics", timeout=2),
|
||||||
|
export_interval_millis=5000, export_timeout_millis=3000,
|
||||||
|
)
|
||||||
|
], views=[
|
||||||
|
View(instrument_name="messenger.http.duration", aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS)),
|
||||||
|
View(instrument_name="messenger.job.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
|
||||||
|
])
|
||||||
|
meter = self.metrics.get_meter("messenger", "1.6.0")
|
||||||
|
self.http_requests = meter.create_counter("messenger.http.requests", unit="1")
|
||||||
|
self.http_duration = meter.create_histogram("messenger.http.duration", unit="s")
|
||||||
|
self.jobs = meter.create_counter("messenger.job.attempts", unit="1")
|
||||||
|
self.job_duration = meter.create_histogram("messenger.job.duration", unit="s")
|
||||||
|
|
||||||
|
def event(self, event: str, *, error=False, **fields):
|
||||||
|
if not self.enabled:
|
||||||
|
return
|
||||||
|
context = trace.get_current_span().get_span_context()
|
||||||
|
body = {
|
||||||
|
"timestamp": datetime.now(timezone.utc).isoformat(),
|
||||||
|
"severity": "ERROR" if error else "INFO",
|
||||||
|
"service_name": self.service, "event": event,
|
||||||
|
"trace_id": f"{context.trace_id:032x}", "span_id": f"{context.span_id:016x}",
|
||||||
|
**fields,
|
||||||
|
}
|
||||||
|
text = json.dumps(body, ensure_ascii=False)
|
||||||
|
# Не подключаем root logging: SDK/SQL-исключения могут содержать секреты.
|
||||||
|
self.logger.emit(body=text, severity_text=body["severity"],
|
||||||
|
severity_number=SeverityNumber.ERROR if error else SeverityNumber.INFO,
|
||||||
|
attributes={"event": event})
|
||||||
|
print(text, flush=True)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def job_attempt(self):
|
||||||
|
started = time.monotonic()
|
||||||
|
result = {"outcome": "success"}
|
||||||
|
try:
|
||||||
|
yield result
|
||||||
|
except BaseException:
|
||||||
|
result["outcome"] = "error"
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if self.enabled:
|
||||||
|
attrs = {"job.type": "attachment.process.v1", "outcome": result["outcome"]}
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
self.jobs.add(1, attrs)
|
||||||
|
self.job_duration.record(elapsed, attrs)
|
||||||
|
span = trace.get_current_span()
|
||||||
|
span.set_attribute("outcome", result["outcome"])
|
||||||
|
span.set_status(Status(StatusCode.ERROR if result["outcome"] == "error" else StatusCode.OK))
|
||||||
|
self.event("job.processed", error=result["outcome"] == "error",
|
||||||
|
job_type="attachment.process.v1", duration_seconds=elapsed, **result)
|
||||||
|
|
||||||
|
def shutdown(self):
|
||||||
|
if self.enabled:
|
||||||
|
self.metrics.shutdown(timeout_millis=5000)
|
||||||
|
self.logs.shutdown()
|
||||||
|
self.traces.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
class HttpTelemetryMiddleware:
|
||||||
|
def __init__(self, app, telemetry: Telemetry):
|
||||||
|
self.app = app
|
||||||
|
self.telemetry = telemetry
|
||||||
|
|
||||||
|
async def __call__(self, scope, receive, send):
|
||||||
|
if scope["type"] != "http" or not self.telemetry.enabled:
|
||||||
|
return await self.app(scope, receive, send)
|
||||||
|
telemetry = self.telemetry
|
||||||
|
method = scope["method"]
|
||||||
|
if method not in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}:
|
||||||
|
method = "OTHER"
|
||||||
|
started = time.monotonic()
|
||||||
|
status = 500
|
||||||
|
request_id = ""
|
||||||
|
with telemetry.tracer.start_as_current_span(
|
||||||
|
"HTTP", context=Context(), kind=SpanKind.SERVER,
|
||||||
|
record_exception=False, set_status_on_exception=False,
|
||||||
|
) as span:
|
||||||
|
async def observed_send(message):
|
||||||
|
nonlocal status, request_id
|
||||||
|
if message["type"] == "http.response.start":
|
||||||
|
status = message["status"]
|
||||||
|
headers = list(message.get("headers", []))
|
||||||
|
request_id = next((v.decode() for k, v in headers if k.lower() == b"x-request-id"), "")
|
||||||
|
headers.append((b"x-trace-id", f"{span.get_span_context().trace_id:032x}".encode()))
|
||||||
|
message = {**message, "headers": headers}
|
||||||
|
await send(message)
|
||||||
|
try:
|
||||||
|
await self.app(scope, receive, observed_send)
|
||||||
|
finally:
|
||||||
|
request_id = request_id or scope.get("state", {}).get("request_id", "")
|
||||||
|
route = getattr(scope.get("route"), "path", "unmatched")
|
||||||
|
attrs = {"http.request.method": method, "http.route": route,
|
||||||
|
"http.response.status_class": f"{status // 100}xx"}
|
||||||
|
elapsed = time.monotonic() - started
|
||||||
|
telemetry.http_requests.add(1, attrs)
|
||||||
|
telemetry.http_duration.record(elapsed, attrs)
|
||||||
|
span.update_name(f"{method} {route}")
|
||||||
|
span.set_attributes({**attrs, "http.response.status_code": status})
|
||||||
|
span.set_status(Status(StatusCode.ERROR if status >= 500 else StatusCode.OK))
|
||||||
|
telemetry.event("http.request", error=status >= 500, method=method, route=route,
|
||||||
|
status_code=status, request_id=request_id, duration_seconds=elapsed)
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
from contextlib import nullcontext
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
@@ -12,6 +13,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|||||||
from urllib3.exceptions import HTTPError as StorageHTTPError
|
from urllib3.exceptions import HTTPError as StorageHTTPError
|
||||||
|
|
||||||
from app.core.jobs import JobSettings
|
from app.core.jobs import JobSettings
|
||||||
|
from app.core.telemetry import Telemetry
|
||||||
from app.domain.job_retry import classify_failure, retry_delay
|
from app.domain.job_retry import classify_failure, retry_delay
|
||||||
from app.domain.job_files import fetch_original, render_variants
|
from app.domain.job_files import fetch_original, render_variants
|
||||||
from app.errors.exceptions import ProcessingError
|
from app.errors.exceptions import ProcessingError
|
||||||
@@ -201,26 +203,30 @@ async def process_attachment_job(
|
|||||||
*,
|
*,
|
||||||
after_object: Callable[[UUID, str], None] | None = None,
|
after_object: Callable[[UUID, str], None] | None = None,
|
||||||
before_processing: Callable[[UUID], None] | None = None,
|
before_processing: Callable[[UUID], None] | None = None,
|
||||||
|
telemetry: Telemetry | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
claim = await claim_job(session, message, settings)
|
claim = await claim_job(session, message, settings)
|
||||||
acknowledge = claim.acknowledge
|
acknowledge = claim.acknowledge
|
||||||
if claim.work is not None:
|
if claim.work is not None:
|
||||||
work = claim.work
|
work = claim.work
|
||||||
try:
|
with telemetry.job_attempt() if telemetry else nullcontext({}) as result:
|
||||||
async with asyncio.timeout(settings.job_timeout_seconds):
|
try:
|
||||||
if before_processing is not None:
|
async with asyncio.timeout(settings.job_timeout_seconds):
|
||||||
before_processing(work.attachment_id)
|
if before_processing is not None:
|
||||||
acknowledge = await build_result(session, storage, work, after_object)
|
before_processing(work.attachment_id)
|
||||||
except (
|
acknowledge = await build_result(session, storage, work, after_object)
|
||||||
ProcessingError,
|
result["outcome"] = "success" if acknowledge else "deferred"
|
||||||
MinioException,
|
except (
|
||||||
StorageHTTPError,
|
ProcessingError,
|
||||||
OSError,
|
MinioException,
|
||||||
TimeoutError,
|
StorageHTTPError,
|
||||||
) as error:
|
OSError,
|
||||||
code, permanent = classify_failure(error)
|
TimeoutError,
|
||||||
await save_failure(session, work, settings, code, permanent=permanent)
|
) as error:
|
||||||
acknowledge = True
|
code, permanent = classify_failure(error)
|
||||||
|
await save_failure(session, work, settings, code, permanent=permanent)
|
||||||
|
result.update(outcome="error", error_code=code)
|
||||||
|
acknowledge = True
|
||||||
# Ошибка БД/неизвестная ошибка или отмена не подтверждают доставку.
|
# Ошибка БД/неизвестная ошибка или отмена не подтверждают доставку.
|
||||||
return acknowledge
|
return acknowledge
|
||||||
|
|
||||||
|
|||||||
@@ -167,6 +167,10 @@ async def dependency_unavailable_handler(
|
|||||||
request_id,
|
request_id,
|
||||||
type(exc).__name__,
|
type(exc).__name__,
|
||||||
)
|
)
|
||||||
|
telemetry = getattr(request.app.state, "telemetry", None)
|
||||||
|
if telemetry is not None:
|
||||||
|
telemetry.event("dependency.unavailable", error=True,
|
||||||
|
request_id=request_id, exception_type=type(exc).__name__)
|
||||||
|
|
||||||
error = unavailable()
|
error = unavailable()
|
||||||
return _build_response(
|
return _build_response(
|
||||||
@@ -206,9 +210,9 @@ async def unhandled_error_handler(
|
|||||||
request_id = _get_request_id(request)
|
request_id = _get_request_id(request)
|
||||||
|
|
||||||
logger.error(
|
logger.error(
|
||||||
"Unhandled error request_id=%s",
|
"Unhandled error request_id=%s type=%s",
|
||||||
request_id,
|
request_id,
|
||||||
exc_info=exc,
|
type(exc).__name__,
|
||||||
)
|
)
|
||||||
|
|
||||||
error = internal_error()
|
error = internal_error()
|
||||||
|
|||||||
+8
-1
@@ -1,3 +1,4 @@
|
|||||||
|
import asyncio
|
||||||
import logging
|
import logging
|
||||||
from collections.abc import AsyncGenerator
|
from collections.abc import AsyncGenerator
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
@@ -12,6 +13,7 @@ from app.core.lifecycle import GracefulServer, Lifecycle
|
|||||||
from app.core.redis import create_redis_client
|
from app.core.redis import create_redis_client
|
||||||
from app.core.request_capacity import acquire_request_slot, create_request_capacity
|
from app.core.request_capacity import acquire_request_slot, create_request_capacity
|
||||||
from app.core.request_id import RequestIdMiddleware
|
from app.core.request_id import RequestIdMiddleware
|
||||||
|
from app.core.telemetry import HttpTelemetryMiddleware, Telemetry
|
||||||
from app.endpoints.auth import router as auth_router
|
from app.endpoints.auth import router as auth_router
|
||||||
from app.endpoints.attachments import router as attachments_router
|
from app.endpoints.attachments import router as attachments_router
|
||||||
from app.endpoints.chats import router as chats_router
|
from app.endpoints.chats import router as chats_router
|
||||||
@@ -44,8 +46,9 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
|||||||
await s3.aclose()
|
await s3.aclose()
|
||||||
await redis.aclose()
|
await redis.aclose()
|
||||||
await engine.dispose()
|
await engine.dispose()
|
||||||
|
await asyncio.to_thread(telemetry.shutdown)
|
||||||
|
|
||||||
application = FastAPI(title="Messenger", version="1.5.0", lifespan=lifespan)
|
application = FastAPI(title="Messenger", version="1.6.0", lifespan=lifespan)
|
||||||
|
|
||||||
application.state.settings = settings
|
application.state.settings = settings
|
||||||
application.state.engine = engine
|
application.state.engine = engine
|
||||||
@@ -57,11 +60,14 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
|||||||
)
|
)
|
||||||
application.state.request_capacity = create_request_capacity(settings.max_in_flight)
|
application.state.request_capacity = create_request_capacity(settings.max_in_flight)
|
||||||
application.state.instance_id = resolve_instance_id(settings.instance_id)
|
application.state.instance_id = resolve_instance_id(settings.instance_id)
|
||||||
|
telemetry = Telemetry("messenger-api", application.state.instance_id)
|
||||||
|
application.state.telemetry = telemetry
|
||||||
application.state.lifecycle = Lifecycle()
|
application.state.lifecycle = Lifecycle()
|
||||||
application.add_middleware(RequestIdMiddleware)
|
application.add_middleware(RequestIdMiddleware)
|
||||||
application.add_middleware(
|
application.add_middleware(
|
||||||
InstanceIdMiddleware, instance_id=application.state.instance_id
|
InstanceIdMiddleware, instance_id=application.state.instance_id
|
||||||
)
|
)
|
||||||
|
application.add_middleware(HttpTelemetryMiddleware, telemetry=telemetry)
|
||||||
register_exception_handlers(application)
|
register_exception_handlers(application)
|
||||||
|
|
||||||
limited = [Depends(acquire_request_slot)]
|
limited = [Depends(acquire_request_slot)]
|
||||||
@@ -83,6 +89,7 @@ def main() -> None:
|
|||||||
host=settings.app_host,
|
host=settings.app_host,
|
||||||
port=settings.app_port,
|
port=settings.app_port,
|
||||||
log_level=settings.log_level.lower(),
|
log_level=settings.log_level.lower(),
|
||||||
|
access_log=False,
|
||||||
timeout_graceful_shutdown=settings.graceful_shutdown_timeout_seconds,
|
timeout_graceful_shutdown=settings.graceful_shutdown_timeout_seconds,
|
||||||
)
|
)
|
||||||
GracefulServer(
|
GracefulServer(
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ x-base-env: &base-env
|
|||||||
APP_HOST: ${APP_HOST:?Set APP_HOST in .env}
|
APP_HOST: ${APP_HOST:?Set APP_HOST in .env}
|
||||||
APP_PORT: ${APP_PORT:?Set APP_PORT in .env}
|
APP_PORT: ${APP_PORT:?Set APP_PORT in .env}
|
||||||
APP_ENV: ${APP_ENV:?Set APP_ENV in .env}
|
APP_ENV: ${APP_ENV:?Set APP_ENV in .env}
|
||||||
|
OTEL_ENABLED: ${OTEL_ENABLED:-true}
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||||
LOG_LEVEL: ${LOG_LEVEL:?Set LOG_LEVEL in .env}
|
LOG_LEVEL: ${LOG_LEVEL:?Set LOG_LEVEL in .env}
|
||||||
MAX_MESSAGES: ${MAX_MESSAGES:?Set MAX_MESSAGES in .env}
|
MAX_MESSAGES: ${MAX_MESSAGES:?Set MAX_MESSAGES in .env}
|
||||||
MAX_IN_FLIGHT: ${MAX_IN_FLIGHT:?Set MAX_IN_FLIGHT in .env}
|
MAX_IN_FLIGHT: ${MAX_IN_FLIGHT:?Set MAX_IN_FLIGHT in .env}
|
||||||
@@ -388,11 +390,105 @@ services:
|
|||||||
cpus: "0.5"
|
cpus: "0.5"
|
||||||
memory: 128M
|
memory: 128M
|
||||||
|
|
||||||
|
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.165.0
|
||||||
|
command: ["--config=/etc/otelcol/config.yaml"]
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.16.0
|
||||||
|
command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.retention.time=3d"]
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- prometheusdata:/prometheus
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.7.10
|
||||||
|
command: ["-config.file=/etc/loki/config.yaml"]
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/loki.yaml:/etc/loki/config.yaml:ro
|
||||||
|
- lokidata:/loki
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.9.0
|
||||||
|
user: "0:0"
|
||||||
|
command: ["-config.file=/etc/tempo/config.yaml"]
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/tempo.yaml:/etc/tempo/config.yaml:ro
|
||||||
|
- tempodata:/var/tempo
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:13.3.1
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
GF_AUTH_ANONYMOUS_ENABLED: "true"
|
||||||
|
GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||||
|
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||||
|
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||||
|
secrets:
|
||||||
|
- grafana_admin_password
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${GRAFANA_HOST_PORT:-13000}:3000"
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||||
|
- ./infra/otel/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
- grafanadata:/var/lib/grafana
|
||||||
|
healthcheck:
|
||||||
|
# Loki/Tempo/Collector не содержат shell/HTTP-клиент: проверяем их из Grafana.
|
||||||
|
test:
|
||||||
|
- CMD-SHELL
|
||||||
|
- wget -q -T 2 -O /dev/null http://127.0.0.1:3000/api/health && wget -q -T 2 -O /dev/null http://loki:3100/ready && wget -q -T 2 -O /dev/null http://tempo:3200/ready && wget -q -T 2 -O /dev/null http://otel-collector:13133/
|
||||||
|
interval: 5s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 36
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
redisdata:
|
redisdata:
|
||||||
miniodata:
|
miniodata:
|
||||||
rabbitmqdata:
|
rabbitmqdata:
|
||||||
|
prometheusdata:
|
||||||
|
lokidata:
|
||||||
|
tempodata:
|
||||||
|
grafanadata:
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
default:
|
default:
|
||||||
@@ -400,6 +496,8 @@ networks:
|
|||||||
internal: true
|
internal: true
|
||||||
|
|
||||||
secrets:
|
secrets:
|
||||||
|
grafana_admin_password:
|
||||||
|
file: ./secrets/grafana_admin_password
|
||||||
broker_password:
|
broker_password:
|
||||||
file: ./secrets/broker_password
|
file: ./secrets/broker_password
|
||||||
db_password:
|
db_password:
|
||||||
|
|||||||
+8
-3
@@ -1,5 +1,10 @@
|
|||||||
# Доказательства
|
# Результаты проверок
|
||||||
|
|
||||||
Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки.
|
`make verify` заново собирает два файла одного прогона:
|
||||||
|
|
||||||
Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно.
|
- `verification.json`: команды, время, результат регрессии, API/отказов и очистки.
|
||||||
|
- `observability.json`: нагрузка/CPU/RAM, метрики, корреляция логов и traces,
|
||||||
|
privacy, dashboard, инциденты и сохранность истории после restart.
|
||||||
|
|
||||||
|
Сохраняются только
|
||||||
|
синтетические технические данные; credentials, токены и тела сообщений исключены.
|
||||||
|
|||||||
@@ -0,0 +1,398 @@
|
|||||||
|
{
|
||||||
|
"date_utc": "2026-11-14T01:54:09.593067+00:00",
|
||||||
|
"project": "messenger-test",
|
||||||
|
"load": {
|
||||||
|
"date_utc": "2026-11-14T01:54:04.006033+00:00",
|
||||||
|
"workload": "synthetic POST messages; fixed arrival rate; no retries",
|
||||||
|
"duration_seconds": 10,
|
||||||
|
"elapsed_seconds": 9.929,
|
||||||
|
"arrival_rate": 10,
|
||||||
|
"concurrency_limit": 2,
|
||||||
|
"successful_requests": 100,
|
||||||
|
"failed_requests": 0,
|
||||||
|
"error_ratio": 0.0,
|
||||||
|
"successful_rps": 10.072,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 31.394,
|
||||||
|
"p95": 63.623,
|
||||||
|
"p99": 70.12
|
||||||
|
},
|
||||||
|
"dataset": {
|
||||||
|
"users": 3,
|
||||||
|
"chats": 1,
|
||||||
|
"messages": 100
|
||||||
|
},
|
||||||
|
"resource_samples": [
|
||||||
|
{
|
||||||
|
"elapsed_seconds": 2.166,
|
||||||
|
"containers": [
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-api-1",
|
||||||
|
"CPUPerc": "54.62%",
|
||||||
|
"MemUsage": "90.74MiB / 1.5GiB",
|
||||||
|
"MemPerc": "5.91%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-api-2",
|
||||||
|
"CPUPerc": "13.14%",
|
||||||
|
"MemUsage": "91.79MiB / 1.5GiB",
|
||||||
|
"MemPerc": "5.98%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-broker-1",
|
||||||
|
"CPUPerc": "0.16%",
|
||||||
|
"MemUsage": "112.5MiB / 768MiB",
|
||||||
|
"MemPerc": "14.64%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-cleanup-1",
|
||||||
|
"CPUPerc": "0.00%",
|
||||||
|
"MemUsage": "74.46MiB / 256MiB",
|
||||||
|
"MemPerc": "29.08%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-grafana-1",
|
||||||
|
"CPUPerc": "0.85%",
|
||||||
|
"MemUsage": "373.6MiB / 512MiB",
|
||||||
|
"MemPerc": "72.96%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-loki-1",
|
||||||
|
"CPUPerc": "0.82%",
|
||||||
|
"MemUsage": "62.73MiB / 512MiB",
|
||||||
|
"MemPerc": "12.25%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-minio-1",
|
||||||
|
"CPUPerc": "66.11%",
|
||||||
|
"MemUsage": "155.6MiB / 512MiB",
|
||||||
|
"MemPerc": "30.39%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-nginx-1",
|
||||||
|
"CPUPerc": "0.35%",
|
||||||
|
"MemUsage": "4.312MiB / 128MiB",
|
||||||
|
"MemPerc": "3.37%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-otel-collector-1",
|
||||||
|
"CPUPerc": "0.86%",
|
||||||
|
"MemUsage": "55.17MiB / 256MiB",
|
||||||
|
"MemPerc": "21.55%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-postgres-1",
|
||||||
|
"CPUPerc": "20.53%",
|
||||||
|
"MemUsage": "77.13MiB / 512MiB",
|
||||||
|
"MemPerc": "15.06%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-prometheus-1",
|
||||||
|
"CPUPerc": "0.16%",
|
||||||
|
"MemUsage": "34.8MiB / 512MiB",
|
||||||
|
"MemPerc": "6.80%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-publisher-1",
|
||||||
|
"CPUPerc": "0.92%",
|
||||||
|
"MemUsage": "62.27MiB / 256MiB",
|
||||||
|
"MemPerc": "24.32%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-redis-1",
|
||||||
|
"CPUPerc": "0.45%",
|
||||||
|
"MemUsage": "8.496MiB / 512MiB",
|
||||||
|
"MemPerc": "1.66%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-tempo-1",
|
||||||
|
"CPUPerc": "0.62%",
|
||||||
|
"MemUsage": "224.5MiB / 512MiB",
|
||||||
|
"MemPerc": "43.85%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-worker-1",
|
||||||
|
"CPUPerc": "0.01%",
|
||||||
|
"MemUsage": "68.05MiB / 2GiB",
|
||||||
|
"MemPerc": "3.32%"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"elapsed_seconds": 7.274,
|
||||||
|
"containers": [
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-api-1",
|
||||||
|
"CPUPerc": "11.38%",
|
||||||
|
"MemUsage": "90.96MiB / 1.5GiB",
|
||||||
|
"MemPerc": "5.92%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-api-2",
|
||||||
|
"CPUPerc": "81.50%",
|
||||||
|
"MemUsage": "98.59MiB / 1.5GiB",
|
||||||
|
"MemPerc": "6.42%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-broker-1",
|
||||||
|
"CPUPerc": "0.25%",
|
||||||
|
"MemUsage": "112.5MiB / 768MiB",
|
||||||
|
"MemPerc": "14.64%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-cleanup-1",
|
||||||
|
"CPUPerc": "0.00%",
|
||||||
|
"MemUsage": "74.46MiB / 256MiB",
|
||||||
|
"MemPerc": "29.08%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-grafana-1",
|
||||||
|
"CPUPerc": "0.91%",
|
||||||
|
"MemUsage": "373.6MiB / 512MiB",
|
||||||
|
"MemPerc": "72.96%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-loki-1",
|
||||||
|
"CPUPerc": "0.98%",
|
||||||
|
"MemUsage": "62.27MiB / 512MiB",
|
||||||
|
"MemPerc": "12.16%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-minio-1",
|
||||||
|
"CPUPerc": "0.18%",
|
||||||
|
"MemUsage": "155.6MiB / 512MiB",
|
||||||
|
"MemPerc": "30.39%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-nginx-1",
|
||||||
|
"CPUPerc": "0.75%",
|
||||||
|
"MemUsage": "3.852MiB / 128MiB",
|
||||||
|
"MemPerc": "3.01%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-otel-collector-1",
|
||||||
|
"CPUPerc": "1.71%",
|
||||||
|
"MemUsage": "54.97MiB / 256MiB",
|
||||||
|
"MemPerc": "21.47%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-postgres-1",
|
||||||
|
"CPUPerc": "21.91%",
|
||||||
|
"MemUsage": "77.45MiB / 512MiB",
|
||||||
|
"MemPerc": "15.13%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-prometheus-1",
|
||||||
|
"CPUPerc": "0.84%",
|
||||||
|
"MemUsage": "35.03MiB / 512MiB",
|
||||||
|
"MemPerc": "6.84%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-publisher-1",
|
||||||
|
"CPUPerc": "1.10%",
|
||||||
|
"MemUsage": "62.28MiB / 256MiB",
|
||||||
|
"MemPerc": "24.33%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-redis-1",
|
||||||
|
"CPUPerc": "9.35%",
|
||||||
|
"MemUsage": "8.848MiB / 512MiB",
|
||||||
|
"MemPerc": "1.73%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-tempo-1",
|
||||||
|
"CPUPerc": "0.63%",
|
||||||
|
"MemUsage": "224.7MiB / 512MiB",
|
||||||
|
"MemPerc": "43.89%"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "messenger-test-worker-1",
|
||||||
|
"CPUPerc": "0.49%",
|
||||||
|
"MemUsage": "68.05MiB / 2GiB",
|
||||||
|
"MemPerc": "3.32%"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"limits": "Latency covers successes from worker start; client scheduling is not included. Small controlled load, not a capacity benchmark."
|
||||||
|
},
|
||||||
|
"api_replicas": 2,
|
||||||
|
"dashboard_uid": "messenger-overview",
|
||||||
|
"api_correlation": {
|
||||||
|
"trace_id": "0a0e27eba5d266cf6cdc3eb9bfc7f5ef",
|
||||||
|
"span_id": "a7638b6d19f2e057",
|
||||||
|
"log": {
|
||||||
|
"timestamp": "2026-11-14T01:54:07.311535+00:00",
|
||||||
|
"severity": "INFO",
|
||||||
|
"service_name": "messenger-api",
|
||||||
|
"event": "http.request",
|
||||||
|
"trace_id": "0a0e27eba5d266cf6cdc3eb9bfc7f5ef",
|
||||||
|
"span_id": "a7638b6d19f2e057",
|
||||||
|
"method": "POST",
|
||||||
|
"route": "/api/v1/chats/{chat_id}/messages",
|
||||||
|
"status_code": 201,
|
||||||
|
"request_id": "e60a3114-3fa6-4aa5-a24b-e11f081f041b",
|
||||||
|
"duration_seconds": 0.015342902999691432
|
||||||
|
},
|
||||||
|
"spans": [
|
||||||
|
{
|
||||||
|
"name": "POST /api/v1/chats/{chat_id}/messages",
|
||||||
|
"kind": "SPAN_KIND_SERVER",
|
||||||
|
"spanId": "p2OLbRny4Fc=",
|
||||||
|
"startTimeUnixNano": "1794621247296110185",
|
||||||
|
"endTimeUnixNano": "1794621247311696146",
|
||||||
|
"status": {
|
||||||
|
"code": "STATUS_CODE_OK"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"worker_correlation": {
|
||||||
|
"trace_id": "e0b8ad546fdfe9dfd5d7391424b2fc18",
|
||||||
|
"span_id": "47ccae94dff8f378",
|
||||||
|
"log": {
|
||||||
|
"timestamp": "2026-11-14T01:54:07.762039+00:00",
|
||||||
|
"severity": "INFO",
|
||||||
|
"service_name": "messenger-worker",
|
||||||
|
"event": "job.received",
|
||||||
|
"trace_id": "e0b8ad546fdfe9dfd5d7391424b2fc18",
|
||||||
|
"span_id": "47ccae94dff8f378",
|
||||||
|
"job_id": "49ce2d69-4237-4836-b23b-e34c45fe9b15",
|
||||||
|
"attachment_id": "0358f440-2f03-49ae-992d-53447bba3baa"
|
||||||
|
},
|
||||||
|
"spans": [
|
||||||
|
{
|
||||||
|
"name": "attachment.process.v1",
|
||||||
|
"kind": "SPAN_KIND_CONSUMER",
|
||||||
|
"spanId": "R8yulN/483g=",
|
||||||
|
"startTimeUnixNano": "1794621247762005178",
|
||||||
|
"endTimeUnixNano": "1794621248800203658",
|
||||||
|
"status": {
|
||||||
|
"code": "STATUS_CODE_OK"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metrics": {
|
||||||
|
"http_requests": [
|
||||||
|
{
|
||||||
|
"metric": {},
|
||||||
|
"value": [
|
||||||
|
1794621249.18,
|
||||||
|
"229"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"http_duration": [
|
||||||
|
{
|
||||||
|
"metric": {},
|
||||||
|
"value": [
|
||||||
|
1794621249.198,
|
||||||
|
"229"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"job_success": [
|
||||||
|
{
|
||||||
|
"metric": {},
|
||||||
|
"value": [
|
||||||
|
1794621249.248,
|
||||||
|
"1"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"job_duration": [
|
||||||
|
{
|
||||||
|
"metric": {},
|
||||||
|
"value": [
|
||||||
|
1794621249.264,
|
||||||
|
"1"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"incidents": [
|
||||||
|
{
|
||||||
|
"scenario": "postgres_unavailable",
|
||||||
|
"http_status": 503,
|
||||||
|
"correlation": {
|
||||||
|
"trace_id": "46bd5c67c04ee46676631207f4cdaaef",
|
||||||
|
"span_id": "9da26006f1e46fec",
|
||||||
|
"log": {
|
||||||
|
"timestamp": "2026-11-14T01:54:11.699761+00:00",
|
||||||
|
"severity": "ERROR",
|
||||||
|
"service_name": "messenger-api",
|
||||||
|
"event": "http.request",
|
||||||
|
"trace_id": "46bd5c67c04ee46676631207f4cdaaef",
|
||||||
|
"span_id": "9da26006f1e46fec",
|
||||||
|
"method": "POST",
|
||||||
|
"route": "/api/v1/users",
|
||||||
|
"status_code": 503,
|
||||||
|
"request_id": "5b3b6549-a5b7-44d9-aaa4-883e7f7f82a6",
|
||||||
|
"duration_seconds": 0.31245764100094675
|
||||||
|
},
|
||||||
|
"spans": [
|
||||||
|
{
|
||||||
|
"name": "POST /api/v1/users",
|
||||||
|
"kind": "SPAN_KIND_SERVER",
|
||||||
|
"spanId": "naJgBvHkb+w=",
|
||||||
|
"startTimeUnixNano": "1794621251387164345",
|
||||||
|
"endTimeUnixNano": "1794621251699877506",
|
||||||
|
"status": {
|
||||||
|
"code": "STATUS_CODE_ERROR"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"diagnostic": {
|
||||||
|
"timestamp": "2026-11-14T01:54:11.698503+00:00",
|
||||||
|
"severity": "ERROR",
|
||||||
|
"service_name": "messenger-api",
|
||||||
|
"event": "dependency.unavailable",
|
||||||
|
"trace_id": "46bd5c67c04ee46676631207f4cdaaef",
|
||||||
|
"span_id": "9da26006f1e46fec",
|
||||||
|
"request_id": "5b3b6549-a5b7-44d9-aaa4-883e7f7f82a6",
|
||||||
|
"exception_type": "gaierror"
|
||||||
|
},
|
||||||
|
"observed_after_seconds": 4.194,
|
||||||
|
"recovery_seconds": 5.664
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"scenario": "permanent_processing_failure",
|
||||||
|
"recovered_status": "ready",
|
||||||
|
"log": {
|
||||||
|
"timestamp": "2026-11-14T01:54:18.958470+00:00",
|
||||||
|
"severity": "ERROR",
|
||||||
|
"service_name": "messenger-worker",
|
||||||
|
"event": "job.processed",
|
||||||
|
"trace_id": "c6bbd94e4fdbad5e5808a2655735b9ed",
|
||||||
|
"span_id": "40a757e89d4b1f76",
|
||||||
|
"job_type": "attachment.process.v1",
|
||||||
|
"duration_seconds": 0.009965533998183673,
|
||||||
|
"outcome": "error",
|
||||||
|
"error_code": "injected_permanent"
|
||||||
|
},
|
||||||
|
"failed_jobs_metric": [
|
||||||
|
{
|
||||||
|
"metric": {},
|
||||||
|
"value": [
|
||||||
|
1794621294.923,
|
||||||
|
"1"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metric_query": "sum(messenger_job_attempts_total{outcome=\"error\",service_instance_id=\"3b4f96f13e48\"})",
|
||||||
|
"failure_to_ready_seconds": 19.356
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"privacy_checked_logs": 72,
|
||||||
|
"checks": {
|
||||||
|
"three_backends": true,
|
||||||
|
"dashboard_queries": true,
|
||||||
|
"server_consumer_traces": true,
|
||||||
|
"log_trace_correlation": true,
|
||||||
|
"low_cardinality": true,
|
||||||
|
"privacy": true,
|
||||||
|
"history_survives_restart": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,472 @@
|
|||||||
|
{
|
||||||
|
"date_utc": "2026-11-14T01:50:28.592547+00:00",
|
||||||
|
"checks": [
|
||||||
|
{
|
||||||
|
"name": "contract",
|
||||||
|
"command": [
|
||||||
|
".venv/bin/python",
|
||||||
|
"scripts/check_contract.py"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 0.101,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "openapi",
|
||||||
|
"command": [
|
||||||
|
".venv/bin/python",
|
||||||
|
"scripts/validate_openapi.py"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 1.111,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "compose",
|
||||||
|
"command": [
|
||||||
|
"docker",
|
||||||
|
"compose",
|
||||||
|
"--env-file",
|
||||||
|
".env",
|
||||||
|
"config",
|
||||||
|
"--quiet"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 0.131,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "startup",
|
||||||
|
"command": [
|
||||||
|
"make",
|
||||||
|
"--no-print-directory",
|
||||||
|
"test-stand-up"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 77.116,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "regression",
|
||||||
|
"command": [
|
||||||
|
"make",
|
||||||
|
"--no-print-directory",
|
||||||
|
"test-unit"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 115.183,
|
||||||
|
"result": "PASS",
|
||||||
|
"summary": "206 passed in 112.44s (0:01:52)"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "api",
|
||||||
|
"command": [
|
||||||
|
".venv/bin/python",
|
||||||
|
"tests/smoke.py",
|
||||||
|
"--base-url",
|
||||||
|
"http://localhost:28080"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 8.349,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "observability",
|
||||||
|
"command": [
|
||||||
|
".venv/bin/python",
|
||||||
|
"-m",
|
||||||
|
"scripts.check_observability",
|
||||||
|
"--base-url",
|
||||||
|
"http://localhost:28080",
|
||||||
|
"--grafana-url",
|
||||||
|
"http://localhost:23000",
|
||||||
|
"--incidents",
|
||||||
|
"--restart-telemetry"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 79.231,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "persistence",
|
||||||
|
"command": [
|
||||||
|
".venv/bin/python",
|
||||||
|
"tests/resilience.py",
|
||||||
|
"--mode",
|
||||||
|
"persistence",
|
||||||
|
"--action-script",
|
||||||
|
"scripts/restart.sh",
|
||||||
|
"--base-url",
|
||||||
|
"http://localhost:28080"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 62.485,
|
||||||
|
"result": "PASS"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "failover",
|
||||||
|
"command": [
|
||||||
|
".venv/bin/python",
|
||||||
|
"tests/resilience.py",
|
||||||
|
"--mode",
|
||||||
|
"failover",
|
||||||
|
"--action-script",
|
||||||
|
"scripts/stop-one.sh",
|
||||||
|
"--base-url",
|
||||||
|
"http://localhost:28080"
|
||||||
|
],
|
||||||
|
"exit_code": 0,
|
||||||
|
"duration_seconds": 17.998,
|
||||||
|
"result": "PASS"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"profile": {
|
||||||
|
"single_stack": true,
|
||||||
|
"load_duration_seconds": 10,
|
||||||
|
"load_requests_per_second": 10,
|
||||||
|
"load_concurrency": 2
|
||||||
|
},
|
||||||
|
"result": "PASS",
|
||||||
|
"cleanup": {
|
||||||
|
"projects": [
|
||||||
|
"messenger",
|
||||||
|
"messenger-test"
|
||||||
|
],
|
||||||
|
"resources": {
|
||||||
|
"containers": [
|
||||||
|
"062d88c22d6c",
|
||||||
|
"5653c0121264",
|
||||||
|
"6e2b3ca3c86c",
|
||||||
|
"ac60f4044ea7",
|
||||||
|
"e633226993b5",
|
||||||
|
"1e21fe44a453",
|
||||||
|
"126c76cff388",
|
||||||
|
"76901c1e8b60",
|
||||||
|
"85731e19d4c6",
|
||||||
|
"79077e49c5ee",
|
||||||
|
"80a7e7e36fd1",
|
||||||
|
"69f42359b3e3",
|
||||||
|
"1a3d86fafd53",
|
||||||
|
"9f00acc93186",
|
||||||
|
"bd366e53bf42",
|
||||||
|
"b4f81e6b52c3",
|
||||||
|
"a9f375b0b17b"
|
||||||
|
],
|
||||||
|
"networks": [
|
||||||
|
"04eba990b02c",
|
||||||
|
"ff8d81906905"
|
||||||
|
],
|
||||||
|
"volumes": [
|
||||||
|
"messenger-test_grafanadata",
|
||||||
|
"messenger-test_lokidata",
|
||||||
|
"messenger-test_miniodata",
|
||||||
|
"messenger-test_pgdata",
|
||||||
|
"messenger-test_prometheusdata",
|
||||||
|
"messenger-test_rabbitmqdata",
|
||||||
|
"messenger-test_redisdata",
|
||||||
|
"messenger-test_tempodata"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"application_image_ids": [
|
||||||
|
"490c0e5b26df",
|
||||||
|
"669227412939",
|
||||||
|
"af2ab3c10330"
|
||||||
|
],
|
||||||
|
"local_settings_preserved": true,
|
||||||
|
"remaining": {
|
||||||
|
"containers": [],
|
||||||
|
"networks": [],
|
||||||
|
"volumes": []
|
||||||
|
},
|
||||||
|
"application_images_remaining": [],
|
||||||
|
"result": "PASS",
|
||||||
|
"verified": {
|
||||||
|
"containers_remaining": 0,
|
||||||
|
"volumes_remaining": 0,
|
||||||
|
"application_images_remaining": 0,
|
||||||
|
"local_settings_preserved": true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"finished_at_utc": "2026-11-14T01:56:33.228789+00:00",
|
||||||
|
"source": {
|
||||||
|
"base_commit": "498ce1e0d20c7ffc45ef71b81f5ce3cfa56208ec",
|
||||||
|
"working_tree_modified": true
|
||||||
|
},
|
||||||
|
"runtime": {
|
||||||
|
"python": "3.12.14",
|
||||||
|
"docker_engine": "29.9.3",
|
||||||
|
"compose": "5.7.0"
|
||||||
|
},
|
||||||
|
"container_lifecycle": [
|
||||||
|
{
|
||||||
|
"time_unix": 1794621212,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "redis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621212,
|
||||||
|
"action": "start",
|
||||||
|
"service": "redis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621251,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "postgres"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621251,
|
||||||
|
"action": "start",
|
||||||
|
"service": "publisher"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621254,
|
||||||
|
"action": "start",
|
||||||
|
"service": "postgres"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621255,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621256,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621267,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621269,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621271,
|
||||||
|
"action": "start",
|
||||||
|
"service": "minio-bootstrap"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621272,
|
||||||
|
"action": "start",
|
||||||
|
"service": "migrate"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621275,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621281,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621284,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621292,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621295,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "prometheus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621295,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "grafana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621295,
|
||||||
|
"action": "start",
|
||||||
|
"service": "prometheus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621295,
|
||||||
|
"action": "start",
|
||||||
|
"service": "grafana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621295,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "loki"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621296,
|
||||||
|
"action": "start",
|
||||||
|
"service": "loki"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621305,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "tempo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621305,
|
||||||
|
"action": "start",
|
||||||
|
"service": "tempo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621314,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621314,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "publisher"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621324,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "cleanup"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621324,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "otel-collector"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "minio"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "prometheus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "grafana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "broker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "redis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "postgres"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "loki"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "minio"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "otel-collector"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "prometheus"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "grafana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "broker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "redis"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "postgres"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621325,
|
||||||
|
"action": "start",
|
||||||
|
"service": "loki"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621334,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "tempo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621335,
|
||||||
|
"action": "start",
|
||||||
|
"service": "tempo"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621335,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "nginx"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621336,
|
||||||
|
"action": "start",
|
||||||
|
"service": "nginx"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621337,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "api"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621337,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "api"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621337,
|
||||||
|
"action": "start",
|
||||||
|
"service": "api"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621337,
|
||||||
|
"action": "start",
|
||||||
|
"service": "api"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621344,
|
||||||
|
"action": "start",
|
||||||
|
"service": "cleanup"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621344,
|
||||||
|
"action": "start",
|
||||||
|
"service": "publisher"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621345,
|
||||||
|
"action": "start",
|
||||||
|
"service": "worker"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"time_unix": 1794621377,
|
||||||
|
"action": "stop",
|
||||||
|
"service": "api"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
+17
-4
@@ -1,7 +1,20 @@
|
|||||||
# Конфигурация наблюдаемости — реализовать
|
# Наблюдаемость Messenger
|
||||||
|
|
||||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
API и worker экспортируют OTLP HTTP/protobuf в Collector (:4318).
|
||||||
|
Метрики выдаются Prometheus на :8889, логи отправляются в native OTLP Loki,
|
||||||
|
traces — в Tempo. Grafana читает три хранилища через provisioned datasources.
|
||||||
|
|
||||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
Конфиги backend, Collector, dashboard и provisioning находятся в этом каталоге.
|
||||||
|
Dashboard UID: `messenger-overview`. Метрики — в секундах и счётчиках попыток;
|
||||||
|
точные запросы/единицы находятся в JSON. Resource environment берётся из APP_ENV.
|
||||||
|
В Loki индексируются service.name и окружение; instance ID — structured metadata.
|
||||||
|
Строка лога содержит trace/span ID, ссылка TraceID открывает Tempo.
|
||||||
|
|
||||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
История хранится в prometheusdata/lokidata/tempodata, retention 3 дня;
|
||||||
|
grafanadata содержит настройки Grafana. Внешний порт имеет только Grafana,
|
||||||
|
по умолчанию 127.0.0.1:13000. Её healthcheck проверяет также Loki, Tempo и Collector.
|
||||||
|
Бизнес-readiness API от этих сервисов не зависит.
|
||||||
|
|
||||||
|
Проверка: `make test-observability`. Полный прогон с очисткой: `make verify`.
|
||||||
|
Инструкция запуска — в [RUNNING.md](../../RUNNING.md), ограничения и планы — в
|
||||||
|
[REPORT.md](../../REPORT.md).
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 192
|
||||||
|
spike_limit_mib: 32
|
||||||
|
batch:
|
||||||
|
timeout: 1s
|
||||||
|
send_batch_size: 128
|
||||||
|
send_batch_max_size: 256
|
||||||
|
exporters:
|
||||||
|
prometheus:
|
||||||
|
endpoint: 0.0.0.0:8889
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: http://loki:3100/otlp
|
||||||
|
timeout: 3s
|
||||||
|
sending_queue:
|
||||||
|
queue_size: 256
|
||||||
|
num_consumers: 2
|
||||||
|
retry_on_failure:
|
||||||
|
max_elapsed_time: 30s
|
||||||
|
otlphttp/tempo:
|
||||||
|
endpoint: http://tempo:4318
|
||||||
|
timeout: 3s
|
||||||
|
sending_queue:
|
||||||
|
queue_size: 256
|
||||||
|
num_consumers: 2
|
||||||
|
retry_on_failure:
|
||||||
|
max_elapsed_time: 30s
|
||||||
|
extensions:
|
||||||
|
health_check:
|
||||||
|
endpoint: 0.0.0.0:13133
|
||||||
|
service:
|
||||||
|
extensions: [health_check]
|
||||||
|
pipelines:
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [prometheus]
|
||||||
|
logs:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
|
traces:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/tempo]
|
||||||
@@ -0,0 +1,343 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-overview",
|
||||||
|
"title": "Messenger — наблюдаемость",
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"version": 1,
|
||||||
|
"tags": [
|
||||||
|
"messenger",
|
||||||
|
"observability"
|
||||||
|
],
|
||||||
|
"timezone": "browser",
|
||||||
|
"refresh": "5s",
|
||||||
|
"time": {
|
||||||
|
"from": "now-15m",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "API: запросы в секунду",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (http_request_method, http_route) (rate(messenger_http_requests_total{http_route!~\"/health/.*\"}[1m]))",
|
||||||
|
"legendFormat": "{{http_request_method}} {{http_route}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "API: доля 5xx",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "(sum(rate(messenger_http_requests_total{http_response_status_class=\"5xx\",http_route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{http_route!~\"/health/.*\"}[1m])), 0.000001)",
|
||||||
|
"legendFormat": "5xx / все бизнес-запросы"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Ошибки сервера: 5xx / все запросы, кроме health. 4xx не считаются отказом сервера.",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "API: время ответа p50/p95/p99",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 9,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[1m])))",
|
||||||
|
"legendFormat": "p50"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[1m])))",
|
||||||
|
"legendFormat": "p95"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[1m])))",
|
||||||
|
"legendFormat": "p99"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Histogram в секундах, buckets суммируются по репликам.",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Worker: попытки в секунду по исходу",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 9,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (outcome) (rate(messenger_job_attempts_total[1m]))",
|
||||||
|
"legendFormat": "{{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "success — результат записан; error — попытка не удалась; deferred — истёк lease. Дубли без обработки не считаются.",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "ops"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Worker: время обработки p95",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 18,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_duration_seconds_bucket[1m])))",
|
||||||
|
"legendFormat": "{{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Одна фактическая попытка, включая S3, преобразования и фиксацию metadata.",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Worker: обработанные попытки",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 18,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (outcome) (messenger_job_attempts_total)",
|
||||||
|
"legendFormat": "{{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "API: структурные логи",
|
||||||
|
"type": "logs",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 27,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "{service_name=\"messenger-api\"} | json",
|
||||||
|
"queryType": "range"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "Worker: структурные логи",
|
||||||
|
"type": "logs",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 27,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "{service_name=\"messenger-worker\"} | json",
|
||||||
|
"queryType": "range"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"title": "Реальные server/consumer traces",
|
||||||
|
"type": "table",
|
||||||
|
"datasource": {
|
||||||
|
"type": "tempo",
|
||||||
|
"uid": "tempo"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 36,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"queryType": "traceqlSearch",
|
||||||
|
"query": "{ resource.service.name =~ \"messenger-api|messenger-worker\" }",
|
||||||
|
"limit": 20
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"description": "Открыть trace в Explore; ссылка TraceID из строки Loki ведёт к той же трассе.",
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"title": "API: число 5xx бизнес-запросов",
|
||||||
|
"type": "stat",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 36,
|
||||||
|
"w": 12,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum(messenger_http_requests_total{http_response_status_class=\"5xx\",http_route!~\"/health/.*\"}) or vector(0)",
|
||||||
|
"instant": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"reduceOptions": {
|
||||||
|
"calcs": [
|
||||||
|
"lastNotNull"
|
||||||
|
],
|
||||||
|
"fields": "",
|
||||||
|
"values": false
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"description": "Накопленное число 5xx: показывает и первую ошибку нового ряда, когда rate ещё не имеет двух разных точек."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"annotations": {
|
||||||
|
"list": []
|
||||||
|
},
|
||||||
|
"templating": {
|
||||||
|
"list": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: Messenger
|
||||||
|
folder: Messenger
|
||||||
|
type: file
|
||||||
|
disableDeletion: true
|
||||||
|
editable: false
|
||||||
|
updateIntervalSeconds: 10
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: http://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: http://loki:3100
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
derivedFields:
|
||||||
|
- name: TraceID
|
||||||
|
matcherRegex: '"trace_id":\s*"([0-9a-f]{32})"'
|
||||||
|
datasourceUid: tempo
|
||||||
|
url: '$${__value.raw}'
|
||||||
|
urlDisplayLabel: Open trace
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: http://tempo:3200
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
spanStartTimeShift: '-1m'
|
||||||
|
spanEndTimeShift: '1m'
|
||||||
|
tags: [{key: service.name, value: service_name}]
|
||||||
|
filterByTraceID: true
|
||||||
|
filterBySpanID: false
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
replication_factor: 1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
storage:
|
||||||
|
filesystem:
|
||||||
|
chunks_directory: /loki/chunks
|
||||||
|
rules_directory: /loki/rules
|
||||||
|
schema_config:
|
||||||
|
configs:
|
||||||
|
- from: 2024-01-01
|
||||||
|
store: tsdb
|
||||||
|
object_store: filesystem
|
||||||
|
schema: v13
|
||||||
|
index:
|
||||||
|
prefix: index_
|
||||||
|
period: 24h
|
||||||
|
limits_config:
|
||||||
|
allow_structured_metadata: true
|
||||||
|
retention_period: 72h
|
||||||
|
otlp_config:
|
||||||
|
resource_attributes:
|
||||||
|
ignore_defaults: true
|
||||||
|
attributes_config:
|
||||||
|
- action: index_label
|
||||||
|
attributes: [service.name, deployment.environment.name]
|
||||||
|
- action: structured_metadata
|
||||||
|
attributes: [service.version, service.instance.id]
|
||||||
|
compactor:
|
||||||
|
working_directory: /loki/compactor
|
||||||
|
retention_enabled: true
|
||||||
|
delete_request_store: filesystem
|
||||||
|
analytics:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 5s
|
||||||
|
evaluation_interval: 5s
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: messenger
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:8889]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
ingester:
|
||||||
|
max_block_duration: 1m
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 72h
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/blocks
|
||||||
|
usage_report:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -21,6 +21,9 @@ MarkupSafe==3.0.4
|
|||||||
openapi-schema-validator==0.6.3
|
openapi-schema-validator==0.6.3
|
||||||
openapi-spec-validator==0.7.2
|
openapi-spec-validator==0.7.2
|
||||||
opentelemetry-api==1.45.1
|
opentelemetry-api==1.45.1
|
||||||
|
opentelemetry-sdk==1.45.1
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.45.1
|
||||||
|
opentelemetry-semantic-conventions==0.66b1
|
||||||
packaging==26.3
|
packaging==26.3
|
||||||
pathable==0.4.4
|
pathable==0.4.4
|
||||||
pluggy==1.7.0
|
pluggy==1.7.0
|
||||||
|
|||||||
@@ -179,7 +179,7 @@ def crash(client, actor, chat, mode):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def retry_replay(client, actor, chat, permanent):
|
def retry_replay(client, actor, chat, permanent, on_failed=None):
|
||||||
name = "messenger-retry-fault-" + uuid4().hex
|
name = "messenger-retry-fault-" + uuid4().hex
|
||||||
samples = []
|
samples = []
|
||||||
configuration = ComposeProject().config["services"]["worker"]["environment"]
|
configuration = ComposeProject().config["services"]["worker"]["environment"]
|
||||||
@@ -238,6 +238,8 @@ def retry_replay(client, actor, chat, permanent):
|
|||||||
actor=actor,
|
actor=actor,
|
||||||
expected=409,
|
expected=409,
|
||||||
)
|
)
|
||||||
|
if on_failed is not None:
|
||||||
|
on_failed(sample, name)
|
||||||
job_id = sample["job_id"]
|
job_id = sample["job_id"]
|
||||||
request_id = str(uuid4())
|
request_id = str(uuid4())
|
||||||
listing = admin("list-failed")
|
listing = admin("list-failed")
|
||||||
|
|||||||
@@ -0,0 +1,291 @@
|
|||||||
|
"""Проверка наблюдаемости через реальные запросы Grafana к трём backend.
|
||||||
|
|
||||||
|
--incidents явно разрешает два ограниченных отказа на выбранном Compose-проекте.
|
||||||
|
В evidence сохраняются только агрегаты и выбранные технические поля.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import math
|
||||||
|
import subprocess
|
||||||
|
import threading
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
from scripts.deployment import ComposeProject
|
||||||
|
from tests.client import Client, Failure, check
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
def eventually(operation, message, timeout=90):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
value = operation()
|
||||||
|
if value:
|
||||||
|
return value
|
||||||
|
except (OSError, ValueError, KeyError, AssertionError):
|
||||||
|
pass
|
||||||
|
time.sleep(1)
|
||||||
|
raise AssertionError(message)
|
||||||
|
|
||||||
|
|
||||||
|
class Grafana:
|
||||||
|
def __init__(self, base):
|
||||||
|
self.base = base.rstrip('/')
|
||||||
|
secret = (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
||||||
|
self.authorization = 'Basic ' + base64.b64encode(('admin:' + secret).encode()).decode()
|
||||||
|
|
||||||
|
def get(self, path, **params):
|
||||||
|
url = self.base + path
|
||||||
|
if params:
|
||||||
|
url += '?' + urllib.parse.urlencode(params)
|
||||||
|
request = urllib.request.Request(url, headers={'Authorization': self.authorization, 'Accept': 'application/json'})
|
||||||
|
with urllib.request.urlopen(request, timeout=10) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
def proxy(self, source, path, **params):
|
||||||
|
return self.get('/api/datasources/proxy/uid/' + source + path, **params)
|
||||||
|
|
||||||
|
def query(self, expression):
|
||||||
|
value = self.proxy('prometheus', '/api/v1/query', query=expression)
|
||||||
|
check(value['status'] == 'success', 'Prometheus query failed')
|
||||||
|
return value['data']['result']
|
||||||
|
|
||||||
|
def logs(self, selector, start):
|
||||||
|
value = self.proxy('loki', '/loki/api/v1/query_range', query=selector, start=start, end=time.time_ns(), limit=1000, direction='forward')
|
||||||
|
check(value['status'] == 'success', 'Loki query failed')
|
||||||
|
return [json.loads(line) for stream in value['data']['result'] for _, line, *_ in stream['values']]
|
||||||
|
|
||||||
|
def trace(self, trace_id):
|
||||||
|
return self.proxy('tempo', '/api/traces/' + trace_id)
|
||||||
|
|
||||||
|
|
||||||
|
def identifier_hex(value, byte_length):
|
||||||
|
if len(value) == byte_length * 2 and all(c in '0123456789abcdefABCDEF' for c in value):
|
||||||
|
return value.lower()
|
||||||
|
return base64.b64decode(value, validate=True).hex()
|
||||||
|
|
||||||
|
|
||||||
|
def spans_in(value):
|
||||||
|
found = []
|
||||||
|
if isinstance(value, dict):
|
||||||
|
for key, item in value.items():
|
||||||
|
if key == 'spans':
|
||||||
|
found.extend(item)
|
||||||
|
else:
|
||||||
|
found.extend(spans_in(item))
|
||||||
|
elif isinstance(value, list):
|
||||||
|
for item in value:
|
||||||
|
found.extend(spans_in(item))
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def correlation(grafana, service, start, *, trace_id=None, attachment_id=None, request_id=None):
|
||||||
|
selector = '{service_name="' + service + '"} | json'
|
||||||
|
if service == 'messenger-api':
|
||||||
|
selector += ' | event="http.request"'
|
||||||
|
if trace_id:
|
||||||
|
selector += ' | trace_id="' + trace_id + '"'
|
||||||
|
if attachment_id:
|
||||||
|
selector += ' | attachment_id="' + attachment_id + '"'
|
||||||
|
if request_id:
|
||||||
|
selector += ' | request_id="' + request_id + '"'
|
||||||
|
records = eventually(lambda: grafana.logs(selector, start), 'No correlated log for ' + service)
|
||||||
|
record = records[0]
|
||||||
|
trace_id = record['trace_id']
|
||||||
|
def matching_trace():
|
||||||
|
candidate = grafana.trace(trace_id)
|
||||||
|
return candidate if any(identifier_hex(span.get('spanId', ''), 8) == record['span_id'] for span in spans_in(candidate)) else None
|
||||||
|
trace = eventually(matching_trace, 'Matching span is missing in Tempo')
|
||||||
|
spans = [span for span in spans_in(trace) if identifier_hex(span.get('spanId', ''), 8) == record['span_id']]
|
||||||
|
# Tempo 2.9 JSON использует protobuf bytes (Base64); Loki хранит hex.
|
||||||
|
check(any(identifier_hex(span.get('spanId', ''), 8) == record['span_id'] for span in spans), 'Log span_id not found in real trace')
|
||||||
|
check(all(int(span['endTimeUnixNano']) > int(span['startTimeUnixNano']) for span in spans), 'Trace has no real duration')
|
||||||
|
return {'trace_id': trace_id, 'span_id': record['span_id'], 'log': record,
|
||||||
|
'spans': [{key: span.get(key) for key in ('name', 'kind', 'spanId', 'startTimeUnixNano', 'endTimeUnixNano', 'status')} for span in spans]}, trace
|
||||||
|
|
||||||
|
|
||||||
|
def run_load(args):
|
||||||
|
check(1 <= args.duration <= 300 and 1 <= args.rate <= 40 and 1 <= args.concurrency <= 16, 'Load profile outside bounds')
|
||||||
|
client = Client(args.base_url)
|
||||||
|
actor, _, _, chat = client.bootstrap()
|
||||||
|
project = ComposeProject()
|
||||||
|
container_ids = project.run('ps', '--quiet').splitlines()
|
||||||
|
samples = []
|
||||||
|
stop = threading.Event()
|
||||||
|
|
||||||
|
def sample():
|
||||||
|
while not stop.is_set():
|
||||||
|
result = subprocess.run(['docker','stats','--no-stream','--format','{{json .}}',*container_ids],capture_output=True,text=True,timeout=15)
|
||||||
|
if result.returncode == 0:
|
||||||
|
samples.append({'elapsed_seconds':round(time.monotonic()-started,3), 'containers':[
|
||||||
|
{k:row[k] for k in ('Name','CPUPerc','MemUsage','MemPerc')} for row in (json.loads(line) for line in result.stdout.splitlines())]})
|
||||||
|
stop.wait(3)
|
||||||
|
|
||||||
|
def write(index):
|
||||||
|
local = Client(args.base_url)
|
||||||
|
before = time.monotonic()
|
||||||
|
try:
|
||||||
|
local.message(actor,chat,'synthetic-observability-' + str(index))
|
||||||
|
return time.monotonic()-before
|
||||||
|
except Failure:
|
||||||
|
return None
|
||||||
|
|
||||||
|
started = time.monotonic()
|
||||||
|
sampler = threading.Thread(target=sample)
|
||||||
|
sampler.start()
|
||||||
|
try:
|
||||||
|
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||||
|
futures = []
|
||||||
|
for index in range(args.duration * args.rate):
|
||||||
|
time.sleep(max(0, started + index/args.rate - time.monotonic()))
|
||||||
|
futures.append(pool.submit(write,index))
|
||||||
|
results = [future.result() for future in futures]
|
||||||
|
elapsed = time.monotonic()-started
|
||||||
|
finally:
|
||||||
|
stop.set()
|
||||||
|
sampler.join()
|
||||||
|
latencies = sorted(value for value in results if value is not None)
|
||||||
|
failed = len(results)-len(latencies)
|
||||||
|
def percentile(q):
|
||||||
|
return round(latencies[max(0, math.ceil(q*len(latencies))-1)]*1000,3) if latencies else None
|
||||||
|
report = {'date_utc':datetime.now(timezone.utc).isoformat(), 'workload':'synthetic POST messages; fixed arrival rate; no retries',
|
||||||
|
'duration_seconds':args.duration,'elapsed_seconds':round(elapsed,3),'arrival_rate':args.rate,'concurrency_limit':args.concurrency,
|
||||||
|
'successful_requests':len(latencies),'failed_requests':failed,'error_ratio':failed/len(results),
|
||||||
|
'successful_rps':round(len(latencies)/elapsed,3), 'successful_latency_ms':{name:percentile(q) for name,q in [('p50',.5),('p95',.95),('p99',.99)]},
|
||||||
|
'dataset':{'users':3,'chats':1,'messages':len(latencies)},'resource_samples':samples,
|
||||||
|
'limits':'Latency covers successes from worker start; client scheduling is not included. Small controlled load, not a capacity benchmark.'}
|
||||||
|
check(bool(latencies) and failed == 0, 'Controlled load contains errors')
|
||||||
|
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument('--base-url', required=True)
|
||||||
|
parser.add_argument('--grafana-url', default='http://localhost:13000')
|
||||||
|
parser.add_argument('--incidents', action='store_true')
|
||||||
|
parser.add_argument('--restart-telemetry', action='store_true')
|
||||||
|
parser.add_argument('--output', default='evidence/observability.json')
|
||||||
|
parser.add_argument('--duration', type=int, default=10)
|
||||||
|
parser.add_argument('--rate', type=int, default=10)
|
||||||
|
parser.add_argument('--concurrency', type=int, default=2)
|
||||||
|
args = parser.parse_args()
|
||||||
|
load = run_load(args)
|
||||||
|
start = time.time_ns()
|
||||||
|
project = ComposeProject()
|
||||||
|
client = Client(args.base_url, timeout=40)
|
||||||
|
aliases = {r.instance_id for r in project.replicas() if r.running}
|
||||||
|
check(len(aliases) >= 2, 'Need two real API containers')
|
||||||
|
check(client.call('GET', '/health/live')['headers'].get('X-Instance-Id') in aliases, 'Wrong Compose project for BASE_URL')
|
||||||
|
grafana = Grafana(args.grafana_url)
|
||||||
|
eventually(lambda: grafana.get('/api/health').get('database') == 'ok', 'Grafana is not ready')
|
||||||
|
sources = grafana.get('/api/datasources')
|
||||||
|
check({'prometheus', 'loki', 'tempo'} <= {source['uid'] for source in sources}, 'Missing provisioned datasource')
|
||||||
|
dashboard = grafana.get('/api/dashboards/uid/messenger-overview')['dashboard']
|
||||||
|
check(len(dashboard['panels']) >= 8, 'Dashboard is missing panels')
|
||||||
|
actor, bob, eve, chat = client.bootstrap()
|
||||||
|
sentinel = 'private-content-' + uuid4().hex
|
||||||
|
response = client.message(actor, chat, sentinel)
|
||||||
|
controlled_trace = response['headers'].get('X-Trace-Id')
|
||||||
|
check(bool(controlled_trace), 'No API trace identifier')
|
||||||
|
attachment, _ = client.attachment(actor, chat)
|
||||||
|
client.wait_ready(actor, attachment)
|
||||||
|
api, api_trace = correlation(grafana, 'messenger-api', start, trace_id=controlled_trace, request_id=response['headers']['X-Request-Id'])
|
||||||
|
worker, worker_trace = correlation(grafana, 'messenger-worker', start, attachment_id=attachment['id'])
|
||||||
|
check(api['log']['request_id'] == response['headers']['X-Request-Id'], 'Request id correlation lost')
|
||||||
|
check(any(span['kind'] in ('SPAN_KIND_SERVER', 2) for span in api['spans']), 'No server span')
|
||||||
|
check(any(span['kind'] in ('SPAN_KIND_CONSUMER', 5) for span in worker['spans']), 'No consumer span')
|
||||||
|
processed = eventually(lambda: grafana.logs('{service_name="messenger-worker"} | json | event="job.processed" | trace_id="' + worker['trace_id'] + '"', start), 'No worker result log')
|
||||||
|
check(processed[0]['outcome'] == 'success', 'Controlled worker did not succeed')
|
||||||
|
metrics = {}
|
||||||
|
expressions = {
|
||||||
|
'http_requests': 'sum(messenger_http_requests_total)',
|
||||||
|
'http_duration': 'sum(messenger_http_duration_seconds_count)',
|
||||||
|
'job_success': 'sum(messenger_job_attempts_total{outcome="success"})',
|
||||||
|
'job_duration': 'sum(messenger_job_duration_seconds_count)',
|
||||||
|
}
|
||||||
|
for name, expression in expressions.items():
|
||||||
|
metrics[name] = eventually(lambda expression=expression: grafana.query(expression), 'Missing metric: ' + expression)
|
||||||
|
check(float(metrics[name][0]['value'][1]) > 0, 'Empty metric: ' + name)
|
||||||
|
# Все PromQL из dashboard должны давать численные данные после traffic.
|
||||||
|
for panel in dashboard['panels']:
|
||||||
|
if panel['datasource']['uid'] == 'prometheus':
|
||||||
|
eventually(lambda panel=panel: all(grafana.query(target['expr']) for target in panel['targets']), 'Empty dashboard panel: ' + panel['title'])
|
||||||
|
forbidden_labels = {'user_id','chat_id','message_id','attachment_id','request_id','filename','url','http_target','http_url'}
|
||||||
|
series = grafana.query('{__name__=~"messenger_.*"}')
|
||||||
|
check(not any(forbidden_labels & set(row['metric']) for row in series), 'High cardinality metric label')
|
||||||
|
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'project': project.name,
|
||||||
|
'load': load, 'api_replicas': len(aliases), 'dashboard_uid': dashboard['uid'],
|
||||||
|
'api_correlation': api, 'worker_correlation': worker, 'metrics': metrics, 'incidents': []}
|
||||||
|
if args.incidents:
|
||||||
|
# Восстановление выполняется даже при ошибке проверки.
|
||||||
|
try:
|
||||||
|
before = time.monotonic()
|
||||||
|
project.run('stop', 'postgres')
|
||||||
|
failed = client.call('POST', '/api/v1/users', expected=503,
|
||||||
|
body={'username':'fault_' + uuid4().hex[:12], 'display_name':'Synthetic', 'password':'not-exported-' + uuid4().hex})
|
||||||
|
error_trace = failed['headers'].get('X-Trace-Id')
|
||||||
|
error, _ = correlation(grafana, 'messenger-api', start, trace_id=error_trace, request_id=failed['headers']['X-Request-Id'])
|
||||||
|
diagnostics = eventually(lambda: grafana.logs('{service_name="messenger-api"} | json | event="dependency.unavailable" | trace_id="' + error_trace + '"', start), 'No dependency diagnostic log')
|
||||||
|
check(error['log'].get('status_code') == 503 or any(s['status'].get('code') in ('STATUS_CODE_ERROR', 2) for s in error['spans']), 'DB failure not reflected in trace')
|
||||||
|
report['incidents'].append({'scenario':'postgres_unavailable','http_status':503,'correlation':error,'diagnostic':diagnostics[0], 'observed_after_seconds':round(time.monotonic()-before,3)})
|
||||||
|
finally:
|
||||||
|
project.run('start', 'postgres')
|
||||||
|
eventually(lambda: _ready(client), 'API did not recover after PostgreSQL')
|
||||||
|
report['incidents'][-1]['recovery_seconds'] = round(time.monotonic() - before, 3)
|
||||||
|
# Явный fault hook обработки заданий: один permanent processing failure, затем replay.
|
||||||
|
from scripts.check_jobs import retry_replay
|
||||||
|
failed_instance = []
|
||||||
|
def wait_failed_metric(sample, container_name):
|
||||||
|
instance = project.docker('inspect', '--format', '{{.Config.Hostname}}', container_name)
|
||||||
|
failed_instance.append(instance)
|
||||||
|
expression = 'sum(messenger_job_attempts_total{outcome="error",service_instance_id="' + instance + '"})'
|
||||||
|
eventually(lambda: grafana.query(expression), 'Failed job metric not exported before recovery')
|
||||||
|
incident = retry_replay(client, actor, chat, permanent=True, on_failed=wait_failed_metric)
|
||||||
|
error_logs = eventually(lambda: grafana.logs('{service_name="messenger-worker"} | json | event="job.processed" | outcome="error" | error_code="injected_permanent"', start), 'No failed job telemetry')
|
||||||
|
error_trace = eventually(lambda: grafana.trace(error_logs[-1]['trace_id']), 'No failed job trace')
|
||||||
|
check(any(span.get('status', {}).get('code') in ('STATUS_CODE_ERROR', 2) for span in spans_in(error_trace)), 'Worker error trace status lost')
|
||||||
|
expression = 'sum(messenger_job_attempts_total{outcome="error",service_instance_id="' + failed_instance[0] + '"})'
|
||||||
|
errors = eventually(lambda: grafana.query(expression), 'No failed jobs counter')
|
||||||
|
recovery = (datetime.fromisoformat(incident['after']['updated_at']) - datetime.fromisoformat(incident['samples'][-1]['updated_at'])).total_seconds()
|
||||||
|
report['incidents'].append({'scenario':'permanent_processing_failure','recovered_status':incident['after']['status'], 'log':error_logs[-1], 'failed_jobs_metric':errors, 'metric_query':expression, 'failure_to_ready_seconds':round(recovery,3)})
|
||||||
|
# Не сохраняем API bodies или SDK exceptions; проверяем реальные выбранные сигналы.
|
||||||
|
logs = grafana.logs('{service_name=~"messenger-api|messenger-worker"}', start)
|
||||||
|
exported = json.dumps([logs, api_trace, worker_trace])
|
||||||
|
private = [sentinel, *(person['token'] for person in (actor,bob,eve)), *(person['registration']['password'] for person in (actor,bob,eve))]
|
||||||
|
private.extend(path.read_text().strip() for path in (ROOT / 'secrets').iterdir() if path.is_file())
|
||||||
|
check(not any(secret and secret in exported for secret in private), 'Private value found in telemetry')
|
||||||
|
check(all(record.get('trace_id') and record.get('span_id') and record.get('timestamp') and record.get('severity') for record in logs), 'Incomplete structured logs')
|
||||||
|
report['privacy_checked_logs'] = len(logs)
|
||||||
|
report['checks'] = {'three_backends':True, 'dashboard_queries':True,'server_consumer_traces':True,'log_trace_correlation':True,'low_cardinality':True,'privacy':True}
|
||||||
|
if args.restart_telemetry:
|
||||||
|
historical_time = time.time()
|
||||||
|
expression = 'sum(messenger_http_requests_total)'
|
||||||
|
before = grafana.proxy('prometheus', '/api/v1/query', query=expression, time=historical_time)['data']['result']
|
||||||
|
project.run('restart', 'prometheus', 'loki', 'tempo', 'grafana')
|
||||||
|
after = eventually(lambda: grafana.proxy('prometheus', '/api/v1/query', query=expression, time=historical_time)['data']['result'], 'Prometheus history lost')
|
||||||
|
check(before == after, 'Historical metric changed after storage restart')
|
||||||
|
correlation(grafana, 'messenger-api', start, trace_id=api['trace_id'])
|
||||||
|
correlation(grafana, 'messenger-worker', start, trace_id=worker['trace_id'])
|
||||||
|
report['checks']['history_survives_restart'] = True
|
||||||
|
destination = ROOT / args.output
|
||||||
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
destination.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||||
|
print('PASS: telemetry, dashboard, privacy, correlations' + ('; two incidents recovered' if args.incidents else ''))
|
||||||
|
|
||||||
|
|
||||||
|
def _ready(client):
|
||||||
|
return client.call('GET', '/health/ready', expected=[200,503])['status'] == 200
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
@@ -71,3 +71,145 @@ class ComposeProject:
|
|||||||
)
|
)
|
||||||
for row in map(json.loads, rows)
|
for row in map(json.loads, rows)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def cleanup_docker(*args, allow_failure=False):
|
||||||
|
result = subprocess.run(['docker',*args],cwd=ROOT,text=True,capture_output=True,timeout=120)
|
||||||
|
if result.returncode and not allow_failure:
|
||||||
|
raise RuntimeError('Docker cleanup failed: ' + ' '.join(args[:2]))
|
||||||
|
return result.stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
|
def inventory(projects):
|
||||||
|
resources = {'containers':[], 'networks':[], 'volumes':[]}
|
||||||
|
for project in projects:
|
||||||
|
label = 'label=com.docker.compose.project=' + project
|
||||||
|
resources['containers'].extend(cleanup_docker('ps','-aq','--filter',label).splitlines())
|
||||||
|
resources['networks'].extend(cleanup_docker('network','ls','-q','--filter',label).splitlines())
|
||||||
|
resources['volumes'].extend(cleanup_docker('volume','ls','-q','--filter',label).splitlines())
|
||||||
|
return resources
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def clean_stands(*, apply=False):
|
||||||
|
config = json.loads(cleanup_docker('compose','--env-file','.env','config','--format','json'))
|
||||||
|
projects = sorted({config['name'], os.getenv('MAIN_PROJECT', 'messenger'), os.getenv('TEST_PROJECT', 'messenger-test')})
|
||||||
|
resources = inventory(projects)
|
||||||
|
names = {service['image'] for service in config['services'].values() if 'build' in service}
|
||||||
|
image_ids = set()
|
||||||
|
for name in names:
|
||||||
|
image_ids.update(cleanup_docker('image','ls','-q',name).splitlines())
|
||||||
|
# У старых сборок API может уже не быть тега. Сверяем также команду и WORKDIR,
|
||||||
|
# чтобы не затронуть сторонние образы с обычным OCI revision label.
|
||||||
|
candidates = cleanup_docker('image','ls','-q','--filter','label=org.opencontainers.image.revision').splitlines()
|
||||||
|
for candidate in candidates:
|
||||||
|
image = json.loads(cleanup_docker('image','inspect',candidate))[0]
|
||||||
|
settings = image['Config']
|
||||||
|
if settings.get('Cmd') == ['python','-m','app'] and settings.get('WorkingDir') == '/app':
|
||||||
|
image_ids.add(candidate)
|
||||||
|
plan = {'projects':projects, 'resources':resources, 'application_image_ids':sorted(image_ids), 'local_settings_preserved':True}
|
||||||
|
if not apply:
|
||||||
|
return plan
|
||||||
|
if resources['containers']:
|
||||||
|
cleanup_docker('rm','-f','-v',*resources['containers'])
|
||||||
|
if resources['networks']:
|
||||||
|
cleanup_docker('network','rm',*resources['networks'])
|
||||||
|
if resources['volumes']:
|
||||||
|
cleanup_docker('volume','rm',*resources['volumes'])
|
||||||
|
if image_ids:
|
||||||
|
cleanup_docker('image','rm',*sorted(image_ids))
|
||||||
|
remaining = inventory(projects)
|
||||||
|
if any(remaining.values()):
|
||||||
|
raise RuntimeError('Cleanup incomplete')
|
||||||
|
plan['remaining'] = remaining
|
||||||
|
plan['application_images_remaining'] = [name for name in sorted(names) if cleanup_docker('image','ls','-q',name)]
|
||||||
|
if plan['application_images_remaining']:
|
||||||
|
raise RuntimeError('Application images remain')
|
||||||
|
plan['result'] = 'PASS'
|
||||||
|
return plan
|
||||||
|
|
||||||
|
|
||||||
|
def verify():
|
||||||
|
"""Один последовательный прогон на одном стенде с обязательной очисткой."""
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
project_name = os.getenv('TEST_PROJECT', 'messenger-test')
|
||||||
|
os.environ.update(COMPOSE_PROJECT_NAME=project_name,
|
||||||
|
COMPOSE_FILE='compose.yaml:compose.test.yaml',
|
||||||
|
GRAFANA_HOST_PORT='23000', LB_HOST_PORT='28080',
|
||||||
|
DOCKER_TESTS='1')
|
||||||
|
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'checks': [],
|
||||||
|
'profile': {'single_stack': True, 'load_duration_seconds': 10,
|
||||||
|
'load_requests_per_second': 10, 'load_concurrency': 2}}
|
||||||
|
destination = ROOT / 'evidence/verification.json'
|
||||||
|
destination.parent.mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
def run(name, command, timeout=600):
|
||||||
|
print('RUN: ' + name, flush=True)
|
||||||
|
started = time.monotonic()
|
||||||
|
result = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=timeout)
|
||||||
|
executable = Path(command[0])
|
||||||
|
display_command = [str(executable.relative_to(ROOT)) if executable.is_relative_to(ROOT)
|
||||||
|
else command[0], *command[1:]]
|
||||||
|
entry = {'name': name, 'command': display_command, 'exit_code': result.returncode,
|
||||||
|
'duration_seconds': round(time.monotonic()-started, 3),
|
||||||
|
'result': 'PASS' if result.returncode == 0 else 'FAIL'}
|
||||||
|
if name == 'regression':
|
||||||
|
summary = re.search(r'\d+ passed[^\n]*', result.stdout)
|
||||||
|
if summary:
|
||||||
|
entry['summary'] = summary.group(0)
|
||||||
|
if result.returncode:
|
||||||
|
# Полные диагностические логи локальны; в evidence нет путей/credentials.
|
||||||
|
(ROOT / '.verification-error.log').write_text(result.stdout + result.stderr)
|
||||||
|
entry['diagnostics'] = '.verification-error.log (local, not committed)'
|
||||||
|
report['checks'].append(entry)
|
||||||
|
print(entry['result'] + ': ' + name, flush=True)
|
||||||
|
if result.returncode:
|
||||||
|
raise RuntimeError(name + ' failed; inspect local diagnostic log')
|
||||||
|
|
||||||
|
try:
|
||||||
|
run('contract', [sys.executable, 'scripts/check_contract.py'])
|
||||||
|
run('openapi', [sys.executable, 'scripts/validate_openapi.py'])
|
||||||
|
run('compose', ['docker', 'compose', '--env-file', '.env', 'config', '--quiet'])
|
||||||
|
run('startup', ['make', '--no-print-directory', 'test-stand-up'], timeout=600)
|
||||||
|
run('regression', ['make', '--no-print-directory', 'test-unit'])
|
||||||
|
run('api', [sys.executable, 'tests/smoke.py', '--base-url', 'http://localhost:28080'])
|
||||||
|
run('observability', [sys.executable, '-m', 'scripts.check_observability',
|
||||||
|
'--base-url', 'http://localhost:28080',
|
||||||
|
'--grafana-url', 'http://localhost:23000',
|
||||||
|
'--incidents', '--restart-telemetry'])
|
||||||
|
run('persistence', [sys.executable, 'tests/resilience.py', '--mode', 'persistence',
|
||||||
|
'--action-script', 'scripts/restart.sh', '--base-url', 'http://localhost:28080'])
|
||||||
|
run('failover', [sys.executable, 'tests/resilience.py', '--mode', 'failover',
|
||||||
|
'--action-script', 'scripts/stop-one.sh', '--base-url', 'http://localhost:28080'])
|
||||||
|
report['result'] = 'PASS'
|
||||||
|
except BaseException:
|
||||||
|
report['result'] = 'FAIL'
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
print('RUN: cleanup', flush=True)
|
||||||
|
report['cleanup'] = clean_stands(apply=True)
|
||||||
|
print('PASS: cleanup', flush=True)
|
||||||
|
finally:
|
||||||
|
report['finished_at_utc'] = datetime.now(timezone.utc).isoformat()
|
||||||
|
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n')
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
import argparse
|
||||||
|
parser = argparse.ArgumentParser(description='Проверка и очистка Compose-стендов')
|
||||||
|
parser.add_argument('command', choices=['verify', 'clean'])
|
||||||
|
parser.add_argument('--apply', action='store_true', help='Подтвердить удаление ресурсов')
|
||||||
|
args = parser.parse_args()
|
||||||
|
if args.command == 'verify':
|
||||||
|
verify()
|
||||||
|
else:
|
||||||
|
print(json.dumps(clean_stands(apply=args.apply), indent=2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ def main() -> None:
|
|||||||
directory = root / "secrets"
|
directory = root / "secrets"
|
||||||
directory.mkdir(mode=0o700, exist_ok=True)
|
directory.mkdir(mode=0o700, exist_ok=True)
|
||||||
for name in (
|
for name in (
|
||||||
|
"grafana_admin_password",
|
||||||
"db_password",
|
"db_password",
|
||||||
"redis_password",
|
"redis_password",
|
||||||
"broker_password",
|
"broker_password",
|
||||||
|
|||||||
+12
-7
@@ -24,14 +24,19 @@ wait_healthy() {
|
|||||||
|
|
||||||
worker_running=$(compose ps --status running --quiet worker)
|
worker_running=$(compose ps --status running --quiet worker)
|
||||||
compose stop worker publisher cleanup
|
compose stop worker publisher cleanup
|
||||||
compose restart postgres redis minio broker
|
compose restart postgres redis minio broker prometheus loki tempo grafana otel-collector
|
||||||
wait_healthy postgres redis minio broker
|
wait_healthy postgres redis minio broker
|
||||||
compose restart api
|
compose restart api nginx
|
||||||
wait_healthy api
|
wait_healthy api nginx
|
||||||
compose restart nginx
|
# Compose start также запускает завершённые migrate/bootstrap dependencies.
|
||||||
wait_healthy nginx
|
# Здесь нужны только ранее созданные фоновые контейнеры, без повторного bootstrap.
|
||||||
compose start publisher cleanup
|
background_ids=$(compose ps --all --quiet publisher cleanup)
|
||||||
|
docker start $background_ids
|
||||||
# Сценарий с заранее остановленным worker сохраняет его остановленным.
|
# Сценарий с заранее остановленным worker сохраняет его остановленным.
|
||||||
if [ -n "$worker_running" ]; then
|
if [ -n "$worker_running" ]; then
|
||||||
compose start worker
|
worker_ids=$(compose ps --all --quiet worker)
|
||||||
|
docker start $worker_ids
|
||||||
fi
|
fi
|
||||||
|
# Пока восстанавливался бизнес-путь, telemetry backend тоже успели запуститься.
|
||||||
|
# Grafana healthcheck проверяет также готовность Loki, Tempo и Collector.
|
||||||
|
wait_healthy prometheus grafana
|
||||||
|
|||||||
@@ -65,7 +65,8 @@ async def test_unhandled_exception_is_hidden_from_client(
|
|||||||
assert "test-secret" not in json.dumps(payload, ensure_ascii=False)
|
assert "test-secret" not in json.dumps(payload, ensure_ascii=False)
|
||||||
assert "Traceback" not in json.dumps(payload, ensure_ascii=False)
|
assert "Traceback" not in json.dumps(payload, ensure_ascii=False)
|
||||||
assert "Unhandled error request_id=" in caplog.text
|
assert "Unhandled error request_id=" in caplog.text
|
||||||
assert "test-secret" in caplog.text
|
assert "test-secret" not in caplog.text
|
||||||
|
assert "RuntimeError" in caplog.text
|
||||||
assert_request_id(response)
|
assert_request_id(response)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""Проверки приватности и исходов на реальных SDK exporters в памяти."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
import httpx
|
||||||
|
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter
|
||||||
|
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
|
||||||
|
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||||
|
from opentelemetry.trace import SpanKind
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core import telemetry as module
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
async def clean_db():
|
||||||
|
# Этот набор не использует БД, Redis и фикстуры приложения.
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def telemetry(monkeypatch):
|
||||||
|
spans = InMemorySpanExporter()
|
||||||
|
logs = InMemoryLogRecordExporter()
|
||||||
|
metrics = InMemoryMetricReader()
|
||||||
|
monkeypatch.setattr(module, "OTLPSpanExporter", lambda **_: spans)
|
||||||
|
monkeypatch.setattr(module, "OTLPLogExporter", lambda **_: logs)
|
||||||
|
monkeypatch.setattr(module, "PeriodicExportingMetricReader", lambda *_, **__: metrics)
|
||||||
|
runtime = module.Telemetry("messenger-api", "unit", enabled=True)
|
||||||
|
yield runtime, spans, logs, metrics
|
||||||
|
runtime.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_http_template_correlation_and_private_data(telemetry):
|
||||||
|
runtime, spans, logs, metrics = telemetry
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
@app.post("/items/{item_id}")
|
||||||
|
async def item(item_id: str):
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
|
app.add_middleware(module.HttpTelemetryMiddleware, telemetry=runtime)
|
||||||
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app), base_url="http://test") as client:
|
||||||
|
# ASGI caller может иметь свой активный span, не относящийся к входящему HTTP.
|
||||||
|
with runtime.tracer.start_as_current_span("unrelated-task"):
|
||||||
|
response = await client.post("/items/private-id?token=private-query", json={"text":"private-body"}, headers={"Authorization":"Bearer private-token"})
|
||||||
|
await client.get("/arbitrary-private-path")
|
||||||
|
runtime.traces.force_flush()
|
||||||
|
runtime.logs.force_flush()
|
||||||
|
finished = spans.get_finished_spans()
|
||||||
|
assert finished[0].kind == SpanKind.SERVER
|
||||||
|
assert finished[0].name == "POST /items/{item_id}"
|
||||||
|
assert finished[1].attributes["http.route"] == "unmatched"
|
||||||
|
assert finished[0].context.trace_id != finished[1].context.trace_id
|
||||||
|
assert all(span.parent is None for span in finished[:2])
|
||||||
|
body = json.loads(logs.get_finished_logs()[0].log_record.body)
|
||||||
|
assert body["trace_id"] == response.headers["X-Trace-Id"]
|
||||||
|
assert int(body["span_id"], 16) == finished[0].context.span_id
|
||||||
|
data = metrics.get_metrics_data()
|
||||||
|
all_attributes = [dict(point.attributes) for resource in data.resource_metrics for scope in resource.scope_metrics for metric in scope.metrics for point in metric.data.data_points]
|
||||||
|
assert {"http.request.method":"POST", "http.route":"/items/{item_id}", "http.response.status_class":"2xx"} in all_attributes
|
||||||
|
exported = repr([(s.name, dict(s.attributes)) for s in finished]) + repr(all_attributes) + repr([str(log.log_record.body) for log in logs.get_finished_logs()])
|
||||||
|
for private in ("private-id", "private-query", "private-body", "private-token", "arbitrary-private-path"):
|
||||||
|
assert private not in exported
|
||||||
|
|
||||||
|
|
||||||
|
async def test_unhandled_error_preserves_correlation_without_exception_payload(telemetry):
|
||||||
|
from app.core.request_id import RequestIdMiddleware
|
||||||
|
from app.errors.handlers import register_exception_handlers
|
||||||
|
runtime, spans, logs, _ = telemetry
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
@app.get("/explode")
|
||||||
|
async def explode():
|
||||||
|
raise RuntimeError("private-error-with-credentials")
|
||||||
|
|
||||||
|
app.add_middleware(RequestIdMiddleware)
|
||||||
|
app.add_middleware(module.HttpTelemetryMiddleware, telemetry=runtime)
|
||||||
|
register_exception_handlers(app)
|
||||||
|
async with httpx.AsyncClient(transport=httpx.ASGITransport(app, raise_app_exceptions=False), base_url="http://test") as client:
|
||||||
|
response = await client.get("/explode")
|
||||||
|
runtime.traces.force_flush()
|
||||||
|
runtime.logs.force_flush()
|
||||||
|
record = json.loads(logs.get_finished_logs()[0].log_record.body)
|
||||||
|
assert response.status_code == record["status_code"] == 500
|
||||||
|
assert response.headers["X-Request-Id"] == record["request_id"]
|
||||||
|
assert spans.get_finished_spans()[0].status.status_code.name == "ERROR"
|
||||||
|
assert "private-error-with-credentials" not in repr(record)
|
||||||
|
|
||||||
|
|
||||||
|
def test_job_success_and_error_record_real_outcomes(telemetry):
|
||||||
|
runtime, spans, logs, metrics = telemetry
|
||||||
|
for fail in (False, True):
|
||||||
|
try:
|
||||||
|
with runtime.tracer.start_as_current_span("attachment.process.v1", kind=SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False):
|
||||||
|
with runtime.job_attempt():
|
||||||
|
if fail:
|
||||||
|
raise RuntimeError("private-exception-payload")
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
runtime.traces.force_flush()
|
||||||
|
runtime.logs.force_flush()
|
||||||
|
finished = spans.get_finished_spans()
|
||||||
|
assert [s.attributes["outcome"] for s in finished] == ["success", "error"]
|
||||||
|
assert finished[1].status.status_code.name == "ERROR"
|
||||||
|
assert not finished[1].events
|
||||||
|
records = [json.loads(item.log_record.body) for item in logs.get_finished_logs()]
|
||||||
|
assert [record["outcome"] for record in records] == ["success", "error"]
|
||||||
|
assert "private-exception-payload" not in repr(records)
|
||||||
|
data = metrics.get_metrics_data()
|
||||||
|
counters = [point for resource in data.resource_metrics for scope in resource.scope_metrics for metric in scope.metrics if metric.name == "messenger.job.attempts" for point in metric.data.data_points]
|
||||||
|
assert {p.attributes["outcome"]:p.value for p in counters} == {"success":1,"error":1}
|
||||||
|
|
||||||
|
|
||||||
|
def test_disabled_telemetry_has_no_exporters():
|
||||||
|
runtime = module.Telemetry("messenger-api", enabled=False)
|
||||||
|
runtime.event("ignored")
|
||||||
|
runtime.shutdown()
|
||||||
|
assert not hasattr(runtime, "metrics")
|
||||||
|
|
||||||
|
|
||||||
|
def test_tempo_base64_and_hex_identifiers_match():
|
||||||
|
from scripts.check_observability import identifier_hex
|
||||||
|
assert identifier_hex("3X/51BqmrXA=", 8) == "dd7ff9d41aa6ad70"
|
||||||
|
assert identifier_hex("dd7ff9d41aa6ad70", 8) == "dd7ff9d41aa6ad70"
|
||||||
Reference in New Issue
Block a user