forked from mtusi2026/mtusi2026lab6
Добавить наблюдаемость и проверки отказов для ЛР 6
This commit is contained in:
+17
-27
@@ -1,30 +1,20 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Local Compose settings. ./scripts/bootstrap.sh generates ignored secrets separately.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
POSTGRES_USER=messenger
|
||||||
APP_HOST=0.0.0.0
|
POSTGRES_DB=messenger
|
||||||
APP_PORT=8080
|
PORT=8080
|
||||||
APP_ENV=lab
|
CACHE_URL=redis://redis:6379/0
|
||||||
SESSION_TTL_SECONDS=3600
|
SESSION_TTL_SECONDS=3600
|
||||||
# Choose credentials locally. File paths contain no secret values.
|
MAX_CONCURRENT_REQUESTS=50
|
||||||
DATABASE_URL_FILE=/run/secrets/database_url
|
DB_MAX_CONNS=10
|
||||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
DB_MIN_CONNS=2
|
||||||
SESSION_STORE=postgres
|
DB_CONN_TIMEOUT_SECONDS=5
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
WORKER_CONCURRENCY=1
|
||||||
API_REPLICAS=2
|
|
||||||
IDEMPOTENCY_TTL_SECONDS=86400
|
|
||||||
S3_ENDPOINT=http://s3:9000
|
|
||||||
S3_REGION=us-east-1
|
|
||||||
S3_BUCKET=messenger-attachments
|
|
||||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
|
||||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
|
||||||
MAX_UPLOAD_BYTES=10485760
|
|
||||||
MAX_IMAGE_PIXELS=40000000
|
|
||||||
BROKER_URL_FILE=/run/secrets/broker_url
|
|
||||||
WORKER_CONCURRENCY=2
|
|
||||||
JOB_MAX_ATTEMPTS=5
|
JOB_MAX_ATTEMPTS=5
|
||||||
JOB_TIMEOUT_SECONDS=60
|
JOB_TIMEOUT_SECONDS=30
|
||||||
STAGING_RETENTION_SECONDS=86400
|
STAGING_RETENTION_SECONDS=86400
|
||||||
OTEL_SERVICE_NAME=messenger-api
|
APP_VERSION=lab6
|
||||||
# Worker must set a distinct service.name.
|
GRAFANA_PORT=3000
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
|
||||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
# Fixed Compose wiring: OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318,
|
||||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
# OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf, deployment.environment.name=lab.
|
||||||
|
# OTEL_SERVICE_NAME differs between api, outbox and worker in compose.yml.
|
||||||
|
|||||||
@@ -12,5 +12,22 @@ jobs:
|
|||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
- run: python -m pip install -r requirements-dev.txt
|
- run: python -m pip install -r requirements-dev.txt
|
||||||
- run: make check validate PYTHON=python
|
- run: make check validate PYTHON=python
|
||||||
# This job validates the skeleton, not a student solution.
|
application-smoke:
|
||||||
# Add build, readiness and make test in a separate application job.
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 15
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Build and start the lab
|
||||||
|
run: |
|
||||||
|
./scripts/bootstrap.sh
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d --build
|
||||||
|
./scripts/wait_ready.sh 180
|
||||||
|
- name: Check the application with telemetry enabled
|
||||||
|
run: |
|
||||||
|
curl --fail --retry 15 --retry-delay 2 --retry-connrefused http://localhost:3000/api/health
|
||||||
|
make test
|
||||||
|
- if: failure()
|
||||||
|
run: docker compose ps --all
|
||||||
|
- if: always()
|
||||||
|
run: docker compose down
|
||||||
|
|||||||
+3
-3
@@ -1,12 +1,12 @@
|
|||||||
FROM golang:1.27-alpine AS builder
|
FROM golang:1.27.1-alpine AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
COPY go.mod go.sum ./
|
COPY go.mod go.sum ./
|
||||||
RUN go mod download
|
|
||||||
|
|
||||||
COPY cmd ./cmd
|
COPY cmd ./cmd
|
||||||
COPY internal ./internal
|
COPY internal ./internal
|
||||||
RUN --mount=type=cache,target=/root/.cache/go-build CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/api ./cmd/api \
|
RUN --mount=type=cache,target=/root/.cache/go-build --mount=type=cache,target=/go/pkg/mod \
|
||||||
|
CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/api ./cmd/api \
|
||||||
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/reconcile ./cmd/reconcile \
|
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/reconcile ./cmd/reconcile \
|
||||||
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/worker ./cmd/worker
|
&& CGO_ENABLED=0 GOOS=linux go build -trimpath -o /out/worker ./cmd/worker
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,16 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://localhost:8080
|
||||||
|
GRAFANA_URL ?= http://localhost:3000
|
||||||
|
PIPELINE_OUTPUT ?= evidence/lab6-pipeline.json
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence test-failover test-pipeline verify-level4
|
.PHONY: help check validate test load test-persistence test-failover test-pipeline verify-level4 verify-observability
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||||
|
@echo "verify-observability: lab6 alerts, traces and telemetry outage (local Compose)"
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -19,11 +22,14 @@ test:
|
|||||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
test-pipeline:
|
test-pipeline:
|
||||||
$(PYTHON) scripts/check_pipeline.py --base-url "$(BASE_URL)"
|
$(PYTHON) scripts/check_pipeline.py --base-url "$(BASE_URL)" --output "$(PIPELINE_OUTPUT)"
|
||||||
|
|
||||||
verify-level4:
|
verify-level4:
|
||||||
./scripts/verify_level4.sh
|
./scripts/verify_level4.sh
|
||||||
|
|
||||||
|
verify-observability:
|
||||||
|
$(PYTHON) scripts/verify_observability.py --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)"
|
||||||
|
|
||||||
load:
|
load:
|
||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
|||||||
@@ -1,37 +1,126 @@
|
|||||||
# Отчёт — лабораторная 6
|
# Лабораторная 6. Наблюдаемость мессенджера
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- **Автор и группа** — Морозов, БВТ2304
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- **Целевая оценка** — 4
|
||||||
- Commit/PR: TODO после публикации
|
- **Ветка** — `Morozov/bvt2304-solution`
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Для стенда нужны Docker с Compose V2, Python 3.9+, OpenSSL и make. Для тестов Go нужен Go 1.27.1. На машине с Docker Desktop для экспериментов использовалось 4 ГБ памяти виртуальной машины.
|
||||||
|
|
||||||
## Архитектура и решения
|
```sh
|
||||||
|
./scripts/bootstrap.sh
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d --build
|
||||||
|
./scripts/wait_ready.sh
|
||||||
|
make check
|
||||||
|
make test
|
||||||
|
make test-pipeline
|
||||||
|
make verify-observability
|
||||||
|
```
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
Bootstrap создаёт `.env` из [.env.example](.env.example) и локальные credentials в `secrets/`. Повторный запуск сохраняет существующие ключи. Compose ждёт готовности PostgreSQL, применяет миграции через `migrate` и создаёт приватный бакет `attachments` через `s3-init`. Миграция 000005 добавляет nullable-поля W3C и индекс ожидающих заданий. Задания, сохранённые до этой миграции, обрабатываются и получают трассу с отдельным корнем.
|
||||||
|
|
||||||
## Доказательства критериев
|
API доступен на `http://localhost:8080`. Grafana открывается с правами Viewer на [дашборде мессенджера](http://localhost:3000/d/messenger-lab6). Секрет для администратора Grafana лежит в `secrets/grafana_admin_password.txt`. Порт Grafana задаётся `GRAFANA_PORT`, при изменении передайте тот же адрес в `make verify-observability GRAFANA_URL=...`.
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
Остановка с сохранением данных выполняется командой `docker compose down`. Команда `docker compose down --volumes` предназначена для намеренного сброса всех данных выбранного учебного проекта.
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## Архитектура
|
||||||
|
|
||||||
## Эксперименты и отказы
|
```mermaid
|
||||||
|
flowchart LR
|
||||||
|
Client --> HAProxy --> API["API × 2"]
|
||||||
|
API --> PG[("PostgreSQL")]
|
||||||
|
API --> Sessions[("Redis сессий")]
|
||||||
|
API --> S3[("SeaweedFS через S3 proxy")]
|
||||||
|
PG --> Outbox["Outbox relay"]
|
||||||
|
Outbox --> Broker[("Redis Streams")]
|
||||||
|
Broker --> Worker
|
||||||
|
Worker --> PG
|
||||||
|
Worker --> S3
|
||||||
|
API -->|OTLP HTTP| Collector
|
||||||
|
Outbox -->|OTLP HTTP| Collector
|
||||||
|
Worker -->|OTLP HTTP| Collector
|
||||||
|
Collector -->|scrape /metrics| Prometheus
|
||||||
|
Collector -->|OTLP logs| Loki
|
||||||
|
Collector -->|OTLP traces| Tempo
|
||||||
|
Prometheus --> Grafana
|
||||||
|
Loki --> Grafana
|
||||||
|
Tempo --> Grafana
|
||||||
|
```
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Из ЛР5 перенесены бизнес-API, две реплики за балансировщиком, Redis сессий, PostgreSQL, приватный S3, долговечный брокер Redis Streams и отдельные процессы relay и worker. PostgreSQL хранит сообщения и статусы заданий. Redis Streams доставляет задания как минимум один раз. Worker подтверждает брокеру обработку после сохранения результата или состояния повтора в БД. S3 хранит оригиналы и варианты изображений.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Роль и сервисы Compose | Версия | Готовность, хранение и доступ |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| `api` × 2, `worker`, `outbox`, `reconciler` | Go 1.27.1, Alpine 3.20 | HAProxy проверяет `/health/ready` API. Постоянное состояние вынесено в БД, Redis и S3. DSN и S3-ключи монтируются через secrets. |
|
||||||
|
| `postgres`, `migrate` | PostgreSQL 16.4 Alpine, migrate v4.17.1 | `pg_isready`, том `postgres-data`, сеть `data`. |
|
||||||
|
| `redis` и `broker` | Redis 7.4 Alpine | `redis-cli ping`, тома `redis-data` и `broker-data`. Брокер пишет AOF с `appendfsync always`. |
|
||||||
|
| `seaweedfs`, `s3-init`, `s3-proxy` | SeaweedFS 4.50, AWS CLI 2.39.1, HAProxy 3.0 Alpine | `/cluster/status` и пробная запись объекта, том `s3-data`, учётные записи приложения и bootstrap имеют отдельные ключи. |
|
||||||
|
| `lb` | HAProxy 3.0 Alpine | `127.0.0.1:8080`, проверка готовности каждой реплики. |
|
||||||
|
| `otel-collector` | Collector Contrib 0.128.0 | Приём OTLP HTTP на 4318, экспорт метрик на 9464, собственные метрики на 8888. Сеть `telemetry`. |
|
||||||
|
| `prometheus` | Prometheus 3.5.0 | `/-/ready`, том `prometheus-data`, история до 7 дней или 512 МБ, правила алертов. |
|
||||||
|
| `loki` | Loki 3.5.5 | `/ready`, TSDB v13 и WAL в томе `loki-data`, история до 7 дней. |
|
||||||
|
| `tempo` | Tempo 2.8.2 | `/ready`, локальные блоки и WAL в томе `tempo-data`, история до 7 дней. |
|
||||||
|
| `grafana` | Grafana 12.1.1 | `/api/health`, том `grafana-data`, provisioning из Git, доступ с хоста через loopback. |
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
`POSTGRES_*`, `PORT`, `SESSION_TTL_SECONDS`, `CACHE_URL`, `MAX_CONCURRENT_REQUESTS` и `DB_*` из `.env` настраивают рабочие сервисы. `WORKER_CONCURRENCY`, `JOB_*` и `STAGING_RETENTION_SECONDS` управляют конвейером. Compose задаёт `OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318`, протокол `http/protobuf` и `deployment.environment.name=lab`. SDK использует имена `messenger-api`, `messenger-outbox`, `messenger-worker`, версию из `APP_VERSION` и ID экземпляра из hostname или `INSTANCE_ID` у API.
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
## Сигналы и SLO
|
||||||
|
|
||||||
|
API записывает W3C `traceparent` и `tracestate` в одной транзакции с метаданными, job и outbox. Relay строит producer span под `db.attachment.accept` и помещает его контекст в отдельные поля сообщения Redis. Worker строит consumer span под producer. При повторе появляются новые producer и consumer spans в исходной трассе. По `job.attempt` видны попытки, по `s3.*` и `db.job.complete` — запись объектов и коммит результата.
|
||||||
|
|
||||||
|
Логи OTLP содержат timestamp, severity, event и ресурс сервиса. Loki хранит trace/span ID и `request_id` в структурных метаданных. Для HTTP лог содержит имя метода, шаблон маршрута, код, длительность и `X-Request-Id`. Логи worker привязаны к consumer span. Значения SQL-параметров, URL, названия файлов, тело сообщений, содержимое изображений, Authorization и credentials не включаются в инструментацию. Список HTTP-методов ограничен, неизвестные пути получают значение `<unmatched>`. Метрики используют шаблоны маршрутов и технические атрибуты сервиса без идентификаторов HTTP-запросов, пользователей, сообщений или вложений.
|
||||||
|
|
||||||
|
| Сигнал | PromQL или имя серии | Единица |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Частота бизнес-запросов | `sum(rate(messenger_http_requests_total{route!="<unmatched>"}[1m]))` | запросы/с |
|
||||||
|
| Ошибки API | `messenger:api_errors:ratio1m` | доля 0–1 |
|
||||||
|
| p50/p95/p99 API | `histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!="<unmatched>"}[1m])))` с 0.50, 0.95 или 0.99 | секунды |
|
||||||
|
| Попытки worker | `sum by (outcome) (rate(messenger_job_attempts_total[1m]))` | попытки/с, `success` или `error` |
|
||||||
|
| Время обработки | `histogram_quantile(0.95, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket{outcome="success"}[1m])))` | секунды |
|
||||||
|
| До ready | `messenger_attachment_time_to_ready_seconds_bucket` от записи задания в транзакции принятия до коммита ready, включая ожидание повторов | секунды |
|
||||||
|
| Глубина и возраст | `messenger_queue_depth`, `messenger_queue_oldest_age_seconds`. Relay измеряет durable backlog `queued`, включая ожидающие retry. | задания, секунды |
|
||||||
|
| DB pool | `messenger_db_pool_used`, `messenger_db_pool_waiting`, `messenger_db_pool_capacity`. Waiting считает вызовы Acquire в процессе выполнения. | соединения, вызовы |
|
||||||
|
| Блокировка записей | `messenger_db_messages_lock_waiters` из `pg_locks` | ожидающие транзакции |
|
||||||
|
| Загрузка worker | `sum(messenger_worker_busy) / sum(messenger_worker_capacity)` | доля занятых слотов |
|
||||||
|
| CPU и RAM | `rate(messenger_process_cpu_time_seconds_total[1m])`, `messenger_process_memory_rss_bytes` | ядра CPU, байты RSS |
|
||||||
|
|
||||||
|
SLI доступности — число ответов без 5xx, делённое на все ответы зарегистрированных бизнес-маршрутов API за последние 30 минут. Health и неизвестные маршруты исключены. 4xx относятся к ответам без серверной ошибки. При отсутствии трафика значение не вычисляется. Прокси-ошибки без ответа экземпляра API находятся вне области этого SLI. SLO для учебного стенда — **не менее 99% за 30 минут**. Текущее значение записывает правило `messenger:api_availability:ratio30m`. Квантили строятся по сумме bucket rates всех реплик. Пороги, окна, параметры `for` и подсказки оператора доступны в [правилах Prometheus](infra/otel/alerts.yaml) и [инструкции диагностики](infra/otel/README.md).
|
||||||
|
|
||||||
|
## Ограничение нагрузки от телеметрии
|
||||||
|
|
||||||
|
OTLP отправляется вне бизнес-запросов. SDK Go 1.44.0 и SDK логов 0.20.0 используют неблокирующие очереди по 1024 записей для логов и spans, партии до 128, тайм-аут передачи 1 секунду и отключённые повторы HTTP-экспортёров. Метрики собираются раз в 2 секунды. Collector применяет memory limiter с мягким порогом 128 МиБ и жёстким 160 МиБ, партии до 256 и контейнерный предел 256 МиБ. Для Loki и Tempo выделено по 8 пакетов и одному потребителю, задержки повторов ограничены 12 секундами на пакет. Prometheus опрашивает последний снимок метрик каждого процесса, устаревшие серии выводятся из экспортёра через 25 секунд.
|
||||||
|
|
||||||
|
При длительном отказе экспортёр отбрасывает часть сигналов. При опустевшей очереди потери логов оцениваются как разность приростов счётчиков принятых Collector и доставленных в Loki записей. Бизнес-операции продолжают работать со своими хранилищами.
|
||||||
|
|
||||||
|
## Проверка критериев на «4»
|
||||||
|
|
||||||
|
Публичные `make check` и `make test` выполнены при поднятом стенде. Результаты сохранены в [проверке структуры](evidence/lab6-check.txt) и [smoke-тесте](evidence/lab6-smoke.txt). Отдельно проверены [Go-тесты](evidence/lab6-go-test.txt), [go vet](evidence/lab6-go-vet.txt) и [конфигурация Prometheus](evidence/lab6-prometheus-config.txt).
|
||||||
|
|
||||||
|
`make verify-observability` последовательно воспроизводит три сценария. Скрипт применяет воздействия к локальному стенду и восстанавливает сервисы по окончании каждого сценария.
|
||||||
|
|
||||||
|
1. **Worker остановлен.** Подтверждаем принятие двух загрузок, рост возраста заданий и переход `MessengerQueueLag` в `firing`. Перед первой попыткой worker временно отключаем S3-прокси. Сопоставляем обе попытки с исходным HTTP span в Tempo и их событиями в Loki. После восстановления проверяем `ready`, совпадение оригинала с тестовым файлом и переход алерта в `inactive`.
|
||||||
|
2. **Запись в PostgreSQL заблокирована.** На 40 секунд удерживаем блокировку `SHARE` на таблице `messages` и запускаем запись через API. Диагноз опирается на три наблюдения: рост числа ожидающих блокировку в `pg_locks`, 5xx в Prometheus и длительный `INSERT` в трассе. После снятия блокировки проверяем успешную запись и переход `MessengerHighErrorRate` в `inactive`.
|
||||||
|
3. **Loki остановлен.** Записываем сообщения через API около 30 секунд и снимаем размер очереди логов и RSS Collector. После старта Loki проверяем чтение ранее записанного сообщения, приём нового лога и судьбу контрольного лога, созданного во время отказа. Сверяем счётчики логов после опустошения очереди.
|
||||||
|
|
||||||
|
В конце скрипт сверяет серии и квантили дашборда с Prometheus и проверяет историю в трёх хранилищах после перезапусков.
|
||||||
|
|
||||||
|
| Сценарий | Результат прогона 26 ноября 2026 |
|
||||||
|
| --- | --- |
|
||||||
|
| Остановка worker и повтор после отказа S3-прокси | В очереди накопились два задания, возраст старейшего достиг 49,9 с. Алерт увидели через 36,9 с после остановки. После запуска сервисов оба вложения перешли в `ready`, а алерт вернулся в `inactive` за 14,6 с. Контрольная трасса `ed0ba6d57d8b41c5a65d9c5a724ae0d4` содержит исходный upload, попытку с ошибкой и успешный повтор. |
|
||||||
|
| Блокировка записи в PostgreSQL | Максимум три запроса ожидали блокировку. Контрольный POST вернул 500 через 4,02 с. Минутная доля 5xx достигла 88,3%. Алерт увидели через 29,7 с, после снятия блокировки он вернулся в `inactive` за 47,0 с. |
|
||||||
|
| Остановка Loki | За 30,5 с API вернул 215 ответов 201. Контрольное сообщение прочитано после восстановления. Очередь достигла предела в восемь пакетов, пиковый RSS Collector составил 108,7 МиБ, Collector работал без перезапуска. Потеря оценена в 170 логов по разнице счётчиков. Трасса контрольного запроса сохранилась в Tempo, а новый запрос после восстановления снова появился в Loki. |
|
||||||
|
| История после перезапусков | Контрольная трасса сохранилась в Tempo с 90 spans, в Loki сохранилось девять связанных логов. В Prometheus сохранились временные ряды обоих алертов. |
|
||||||
|
|
||||||
|
Тайминги алертов получены периодическим опросом. Снимок SLI за 30 минут составил 96,0%, в это окно попал эксперимент с блокировкой PostgreSQL. Синтетические идентификаторы, график состояний и исходные счётчики есть в [JSON сквозной проверки](evidence/lab6-observability.json).
|
||||||
|
|
||||||
|
### Нагрузка после восстановления
|
||||||
|
|
||||||
|
`python3 scripts/collect_runtime.py --load` запускает четырёх параллельных клиентов, отправляющих POST сообщений в течение 30 секунд. На Docker VM с 8 vCPU и 4,1 ГБ RAM было 4984 успешных ответа и 8 ошибок среди 4992 запросов. Общая длительность с ожиданием последних ответов составила 36,9 с, успешная пропускная способность — 135 запросов/с. Для успешных запросов p50/p95/p99 составили 6,7/34,7/73,8 мс. [Агрегаты нагрузки](evidence/lab6-load.json)
|
||||||
|
|
||||||
|
В 13 снимках `docker stats` пиковое потребление памяти двух API-реплик составило 219 и 205,3 МиБ, пиковый CPU — 35,6% и 37,1%. Collector достиг 208,2 МиБ из 256 МиБ по учёту Docker. Размер таблицы сообщений вырос с 1129 до 6113 строк. [Снимки ресурсов и счётчики БД](evidence/lab6-runtime.json)
|
||||||
|
|
||||||
|
## Источники и использование ИИ
|
||||||
|
|
||||||
|
Для инструментации, provisioning, скрипта проверок и отчёта использовался OpenAI Codex. В приложение добавлены OpenTelemetry SDK, официальный OTLP HTTP exporter и обёртка ResponseWriter httpsnoop. Исходники и тесты бизнес-API перенесены из своей ЛР5. В работе использованы [OpenTelemetry Go](https://opentelemetry.io/docs/languages/go/instrumentation/), [W3C Trace Context](https://www.w3.org/TR/trace-context/), [Prometheus histograms](https://prometheus.io/docs/practices/histograms/), [Prometheus alerting rules](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/), [Loki OTLP ingestion](https://grafana.com/docs/loki/latest/send-data/otel/) и [Grafana provisioning](https://grafana.com/docs/grafana/latest/administration/provisioning/).
|
||||||
|
|||||||
+10
-4
@@ -17,12 +17,22 @@ import (
|
|||||||
"mtusi2026/internal/httpapi"
|
"mtusi2026/internal/httpapi"
|
||||||
"mtusi2026/internal/sessionstore"
|
"mtusi2026/internal/sessionstore"
|
||||||
"mtusi2026/internal/store"
|
"mtusi2026/internal/store"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
|
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
instanceID := config.GetEnv("INSTANCE_ID", "")
|
||||||
|
if instanceID == "" {
|
||||||
|
instanceID, _ = os.Hostname()
|
||||||
|
}
|
||||||
|
stopTelemetry, err := telemetry.Start(ctx, "messenger-api", instanceID)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("could not initialize OpenTelemetry SDK")
|
||||||
|
}
|
||||||
|
defer stopTelemetry()
|
||||||
|
|
||||||
dbCfg := db.Config{
|
dbCfg := db.Config{
|
||||||
DSN: config.GetEnv("DATABASE_URL", ""),
|
DSN: config.GetEnv("DATABASE_URL", ""),
|
||||||
@@ -70,10 +80,6 @@ func main() {
|
|||||||
|
|
||||||
s := store.New(pool, limiter)
|
s := store.New(pool, limiter)
|
||||||
|
|
||||||
instanceID := config.GetEnv("INSTANCE_ID", "")
|
|
||||||
if instanceID == "" {
|
|
||||||
instanceID, _ = os.Hostname()
|
|
||||||
}
|
|
||||||
var draining atomic.Bool
|
var draining atomic.Bool
|
||||||
|
|
||||||
var blobs blobstore.Store
|
var blobs blobstore.Store
|
||||||
|
|||||||
+25
-1
@@ -15,7 +15,9 @@ import (
|
|||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
"mtusi2026/internal/blobstore"
|
"mtusi2026/internal/blobstore"
|
||||||
"mtusi2026/internal/config"
|
"mtusi2026/internal/config"
|
||||||
|
"mtusi2026/internal/db"
|
||||||
"mtusi2026/internal/jobs"
|
"mtusi2026/internal/jobs"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -25,7 +27,23 @@ func main() {
|
|||||||
flag.Parse()
|
flag.Parse()
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||||
defer stop()
|
defer stop()
|
||||||
pool, err := pgxpool.New(ctx, config.GetEnv("DATABASE_URL", ""))
|
if *mode == "worker" || *mode == "relay" {
|
||||||
|
service := "messenger-worker"
|
||||||
|
if *mode == "relay" {
|
||||||
|
service = "messenger-outbox"
|
||||||
|
}
|
||||||
|
instance, _ := os.Hostname()
|
||||||
|
stopTelemetry, err := telemetry.Start(ctx, service, instance)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("could not initialize OpenTelemetry SDK")
|
||||||
|
}
|
||||||
|
defer stopTelemetry()
|
||||||
|
}
|
||||||
|
poolCfg, err := pgxpool.ParseConfig(config.GetEnv("DATABASE_URL", ""))
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
pool, err := db.NewPool(ctx, poolCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -69,10 +87,16 @@ func main() {
|
|||||||
log.Printf("pipeline mode=%s concurrency=%d prefetch=1 timeout=%s lease=%s attempts=%d", *mode, concurrency, timeout, repo.Lease, attempts)
|
log.Printf("pipeline mode=%s concurrency=%d prefetch=1 timeout=%s lease=%s attempts=%d", *mode, concurrency, timeout, repo.Lease, attempts)
|
||||||
switch *mode {
|
switch *mode {
|
||||||
case "worker":
|
case "worker":
|
||||||
|
if err := rt.ObserveWorker(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
if err := rt.Workers(ctx); err != nil {
|
if err := rt.Workers(ctx); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
case "relay":
|
case "relay":
|
||||||
|
if err := rt.ObserveQueue(); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
rt.Relay(ctx)
|
rt.Relay(ctx)
|
||||||
default:
|
default:
|
||||||
log.Fatal("unknown mode")
|
log.Fatal("unknown mode")
|
||||||
|
|||||||
+103
-8
@@ -1,3 +1,9 @@
|
|||||||
|
x-telemetry-env: &telemetry-env
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||||
|
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
|
||||||
|
APP_VERSION: ${APP_VERSION:-lab6}
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:16.4-alpine
|
image: postgres:16.4-alpine
|
||||||
@@ -41,12 +47,12 @@ services:
|
|||||||
depends_on:
|
depends_on:
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
secrets: [database_url]
|
||||||
volumes:
|
volumes:
|
||||||
- ./migrations:/migrations
|
- ./migrations:/migrations:ro
|
||||||
|
entrypoint: ["/bin/sh", "-ec"]
|
||||||
command:
|
command:
|
||||||
- "-path=/migrations"
|
- exec migrate -path=/migrations -database="$$(cat /run/secrets/database_url)" up
|
||||||
- "-database=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable"
|
|
||||||
- "up"
|
|
||||||
restart: "no"
|
restart: "no"
|
||||||
networks: [data]
|
networks: [data]
|
||||||
deploy:
|
deploy:
|
||||||
@@ -69,6 +75,8 @@ services:
|
|||||||
s3-proxy:
|
s3-proxy:
|
||||||
condition: service_started
|
condition: service_started
|
||||||
environment:
|
environment:
|
||||||
|
<<: *telemetry-env
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
PORT: ${PORT}
|
PORT: ${PORT}
|
||||||
DATABASE_URL_FILE: /run/secrets/database_url
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS}
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS}
|
||||||
@@ -80,7 +88,6 @@ services:
|
|||||||
CHAT_CACHE_TTL_SECONDS: 30
|
CHAT_CACHE_TTL_SECONDS: 30
|
||||||
DRAIN_SECONDS: 4
|
DRAIN_SECONDS: 4
|
||||||
GOMEMLIMIT: 200MiB
|
GOMEMLIMIT: 200MiB
|
||||||
APP_VERSION: ${APP_VERSION:-dev}
|
|
||||||
S3_ENDPOINT: http://s3-proxy:8333
|
S3_ENDPOINT: http://s3-proxy:8333
|
||||||
S3_BUCKET: attachments
|
S3_BUCKET: attachments
|
||||||
S3_REGION: us-east-1
|
S3_REGION: us-east-1
|
||||||
@@ -99,7 +106,7 @@ services:
|
|||||||
timeout: 2s
|
timeout: 2s
|
||||||
retries: 3
|
retries: 3
|
||||||
start_period: 5s
|
start_period: 5s
|
||||||
networks: [edge, data, s3access]
|
networks: [edge, data, s3access, telemetry]
|
||||||
deploy:
|
deploy:
|
||||||
replicas: 2
|
replicas: 2
|
||||||
resources:
|
resources:
|
||||||
@@ -228,7 +235,9 @@ services:
|
|||||||
migrate: { condition: service_completed_successfully }
|
migrate: { condition: service_completed_successfully }
|
||||||
s3-init: { condition: service_completed_successfully }
|
s3-init: { condition: service_completed_successfully }
|
||||||
broker: { condition: service_healthy }
|
broker: { condition: service_healthy }
|
||||||
environment:
|
environment: &pipeline-env
|
||||||
|
<<: *telemetry-env
|
||||||
|
OTEL_SERVICE_NAME: messenger-worker
|
||||||
DATABASE_URL_FILE: /run/secrets/database_url
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
BROKER_URL: redis://broker:6379/0
|
BROKER_URL: redis://broker:6379/0
|
||||||
S3_ENDPOINT: http://s3-proxy:8333
|
S3_ENDPOINT: http://s3-proxy:8333
|
||||||
@@ -243,7 +252,7 @@ services:
|
|||||||
IMAGE_MEMORY_MB: 384
|
IMAGE_MEMORY_MB: 384
|
||||||
GOMEMLIMIT: 128MiB
|
GOMEMLIMIT: 128MiB
|
||||||
secrets: [database_url, s3_api_access_key, s3_api_secret_key]
|
secrets: [database_url, s3_api_access_key, s3_api_secret_key]
|
||||||
networks: [data, s3access]
|
networks: [data, s3access, telemetry]
|
||||||
stop_grace_period: 40s
|
stop_grace_period: 40s
|
||||||
healthcheck: { disable: true }
|
healthcheck: { disable: true }
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
@@ -254,10 +263,89 @@ services:
|
|||||||
outbox:
|
outbox:
|
||||||
<<: *pipeline
|
<<: *pipeline
|
||||||
command: ["./worker", "-mode=relay"]
|
command: ["./worker", "-mode=relay"]
|
||||||
|
environment:
|
||||||
|
<<: *pipeline-env
|
||||||
|
OTEL_SERVICE_NAME: messenger-outbox
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
limits: { cpus: "0.25", memory: 192M }
|
limits: { cpus: "0.25", memory: 192M }
|
||||||
|
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.128.0
|
||||||
|
command: ["--config=/etc/otelcol/config.yaml"]
|
||||||
|
environment:
|
||||||
|
GOMEMLIMIT: 150MiB
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||||
|
networks: [telemetry]
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.5", memory: 256M }
|
||||||
|
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.5.0
|
||||||
|
command:
|
||||||
|
- --config.file=/etc/prometheus/prometheus.yaml
|
||||||
|
- --storage.tsdb.path=/prometheus
|
||||||
|
- --storage.tsdb.retention.time=7d
|
||||||
|
- --storage.tsdb.retention.size=512MB
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||||
|
- ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro
|
||||||
|
- prometheus-data:/prometheus
|
||||||
|
networks: [telemetry]
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.5", memory: 384M }
|
||||||
|
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.5.5
|
||||||
|
command: ["-config.file=/etc/loki/lab.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/loki.yaml:/etc/loki/lab.yaml:ro
|
||||||
|
- loki-data:/loki
|
||||||
|
networks: [telemetry]
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.5", memory: 384M }
|
||||||
|
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.8.2
|
||||||
|
command: ["-config.file=/etc/tempo/lab.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/tempo.yaml:/etc/tempo/lab.yaml:ro
|
||||||
|
- tempo-data:/var/tempo
|
||||||
|
networks: [telemetry]
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.5", memory: 384M }
|
||||||
|
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:12.1.1
|
||||||
|
environment:
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||||
|
GF_AUTH_ANONYMOUS_ENABLED: "true"
|
||||||
|
GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer
|
||||||
|
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||||
|
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||||
|
secrets: [grafana_admin_password]
|
||||||
|
volumes:
|
||||||
|
- grafana-data:/var/lib/grafana
|
||||||
|
- ./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||||
|
- ./infra/otel/grafana/dashboards:/etc/grafana/dashboards:ro
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000"
|
||||||
|
networks: [edge, telemetry]
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits: { cpus: "0.5", memory: 384M }
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
edge:
|
edge:
|
||||||
data:
|
data:
|
||||||
@@ -265,6 +353,8 @@ networks:
|
|||||||
internal: true
|
internal: true
|
||||||
s3access:
|
s3access:
|
||||||
internal: true
|
internal: true
|
||||||
|
telemetry:
|
||||||
|
internal: true
|
||||||
|
|
||||||
secrets:
|
secrets:
|
||||||
database_url:
|
database_url:
|
||||||
@@ -276,9 +366,14 @@ secrets:
|
|||||||
s3_api_secret_key: { file: ./secrets/s3_api_secret_key.txt }
|
s3_api_secret_key: { file: ./secrets/s3_api_secret_key.txt }
|
||||||
s3_admin_access_key: { file: ./secrets/s3_admin_access_key.txt }
|
s3_admin_access_key: { file: ./secrets/s3_admin_access_key.txt }
|
||||||
s3_admin_secret_key: { file: ./secrets/s3_admin_secret_key.txt }
|
s3_admin_secret_key: { file: ./secrets/s3_admin_secret_key.txt }
|
||||||
|
grafana_admin_password: { file: ./secrets/grafana_admin_password.txt }
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
redis-data:
|
redis-data:
|
||||||
s3-data:
|
s3-data:
|
||||||
broker-data:
|
broker-data:
|
||||||
|
prometheus-data:
|
||||||
|
loki-data:
|
||||||
|
tempo-data:
|
||||||
|
grafana-data:
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
? mtusi2026/cmd/api [no test files]
|
||||||
|
? mtusi2026/cmd/reconcile [no test files]
|
||||||
|
? mtusi2026/cmd/worker [no test files]
|
||||||
|
? mtusi2026/internal/auth [no test files]
|
||||||
|
? mtusi2026/internal/blobstore [no test files]
|
||||||
|
? mtusi2026/internal/cache [no test files]
|
||||||
|
? mtusi2026/internal/config [no test files]
|
||||||
|
? mtusi2026/internal/cursor [no test files]
|
||||||
|
? mtusi2026/internal/db [no test files]
|
||||||
|
ok mtusi2026/internal/httpapi 10.560s
|
||||||
|
? mtusi2026/internal/idgen [no test files]
|
||||||
|
ok mtusi2026/internal/images 2.141s
|
||||||
|
ok mtusi2026/internal/jobs 0.969s
|
||||||
|
? mtusi2026/internal/model [no test files]
|
||||||
|
? mtusi2026/internal/reconcile [no test files]
|
||||||
|
? mtusi2026/internal/sessionstore [no test files]
|
||||||
|
? mtusi2026/internal/store [no test files]
|
||||||
|
? mtusi2026/internal/telemetry [no test files]
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
go vet ./...
|
||||||
|
PASS: no diagnostics
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 6,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 30.0,
|
||||||
|
"elapsed_seconds": 36.914,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 4984,
|
||||||
|
"failed_requests": 8,
|
||||||
|
"error_ratio": 0.001603,
|
||||||
|
"successful_rps": 135.015,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 6.716,
|
||||||
|
"p95": 34.651,
|
||||||
|
"p99": 73.798
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"lab": 6,
|
||||||
|
"workload": "closed-loop POST messages; no automatic retries",
|
||||||
|
"requested_duration_seconds": 30.0,
|
||||||
|
"elapsed_seconds": 36.914,
|
||||||
|
"concurrency": 4,
|
||||||
|
"successful_requests": 4984,
|
||||||
|
"failed_requests": 8,
|
||||||
|
"error_ratio": 0.001603,
|
||||||
|
"successful_rps": 135.015,
|
||||||
|
"successful_latency_ms": {
|
||||||
|
"p50": 6.716,
|
||||||
|
"p95": 34.651,
|
||||||
|
"p99": 73.798
|
||||||
|
},
|
||||||
|
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,6 @@
|
|||||||
|
Checking /etc/prometheus/prometheus.yaml
|
||||||
|
SUCCESS: 1 rule files found
|
||||||
|
SUCCESS: /etc/prometheus/prometheus.yaml is valid prometheus config file syntax
|
||||||
|
|
||||||
|
Checking /etc/prometheus/alerts.yaml
|
||||||
|
SUCCESS: 5 rules found
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,2 @@
|
|||||||
|
python3 tests/smoke.py --base-url "http://localhost:8080"
|
||||||
|
PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -8,12 +8,23 @@ require (
|
|||||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.12
|
github.com/aws/aws-sdk-go-v2/credentials v1.20.12
|
||||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6
|
||||||
github.com/aws/smithy-go v1.28.7
|
github.com/aws/smithy-go v1.28.7
|
||||||
|
github.com/felixge/httpsnoop v1.1.0
|
||||||
github.com/golang-migrate/migrate/v4 v4.20.1
|
github.com/golang-migrate/migrate/v4 v4.20.1
|
||||||
github.com/jackc/pgx/v5 v5.11.0
|
github.com/jackc/pgx/v5 v5.11.0
|
||||||
github.com/redis/go-redis/v9 v9.23.0
|
github.com/redis/go-redis/v9 v9.23.0
|
||||||
github.com/testcontainers/testcontainers-go v0.44.0
|
github.com/testcontainers/testcontainers-go v0.44.0
|
||||||
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0
|
||||||
github.com/testcontainers/testcontainers-go/modules/redis v0.44.0
|
github.com/testcontainers/testcontainers-go/modules/redis v0.44.0
|
||||||
|
go.opentelemetry.io/otel v1.44.0
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.20.0
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0
|
||||||
|
go.opentelemetry.io/otel/log v0.20.0
|
||||||
|
go.opentelemetry.io/otel/metric v1.44.0
|
||||||
|
go.opentelemetry.io/otel/sdk v1.44.0
|
||||||
|
go.opentelemetry.io/otel/sdk/log v0.20.0
|
||||||
|
go.opentelemetry.io/otel/sdk/metric v1.44.0
|
||||||
|
go.opentelemetry.io/otel/trace v1.44.0
|
||||||
golang.org/x/crypto v0.54.0
|
golang.org/x/crypto v0.54.0
|
||||||
golang.org/x/sync v0.22.0
|
golang.org/x/sync v0.22.0
|
||||||
)
|
)
|
||||||
@@ -66,6 +77,7 @@ require (
|
|||||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0 // indirect
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.44.0 // indirect
|
||||||
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect
|
github.com/aws/aws-sdk-go-v2/service/sts v1.51.6 // indirect
|
||||||
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
|
||||||
|
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 // indirect
|
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 // indirect
|
||||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect
|
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect
|
||||||
@@ -85,7 +97,6 @@ require (
|
|||||||
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712 // indirect
|
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712 // indirect
|
||||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect
|
github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect
|
||||||
github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect
|
github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect
|
||||||
github.com/felixge/httpsnoop v1.1.0 // indirect
|
|
||||||
github.com/form3tech-oss/jwt-go v3.2.5+incompatible // indirect
|
github.com/form3tech-oss/jwt-go v3.2.5+incompatible // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.1 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.1 // indirect
|
||||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||||
@@ -107,6 +118,7 @@ require (
|
|||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/googleapis/enterprise-certificate-proxy v0.3.17 // indirect
|
github.com/googleapis/enterprise-certificate-proxy v0.3.17 // indirect
|
||||||
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
|
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
|
||||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
|
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
|
||||||
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect
|
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect
|
||||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||||
@@ -183,11 +195,8 @@ require (
|
|||||||
go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect
|
go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect
|
||||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0 // indirect
|
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.69.0 // indirect
|
||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect
|
||||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||||
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
|
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect
|
|
||||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
|
||||||
go.uber.org/atomic v1.12.0 // indirect
|
go.uber.org/atomic v1.12.0 // indirect
|
||||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||||
golang.org/x/mod v0.37.0 // indirect
|
golang.org/x/mod v0.37.0 // indirect
|
||||||
|
|||||||
@@ -135,6 +135,8 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
|||||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
|
||||||
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
|
||||||
|
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||||
|
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
@@ -311,6 +313,8 @@ github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
|
|||||||
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
||||||
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
|
||||||
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
|
||||||
|
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
|
||||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU=
|
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU=
|
||||||
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0=
|
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0=
|
||||||
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed h1:5upAirOpQc1Q53c0bnx2ufif5kANL7bfZWcc6VJWJd8=
|
github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed h1:5upAirOpQc1Q53c0bnx2ufif5kANL7bfZWcc6VJWJd8=
|
||||||
@@ -624,18 +628,32 @@ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4
|
|||||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.20.0 h1:owlhcJ3QO3X0YTDTCcDZ4V+6aVDkWbNmBoQ5NUp7Oww=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.20.0/go.mod h1:MP4eemTiI9zC8fgg+DYynhYDYf3ba72S376TvP+Ye0Q=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0 h1:RuynHbfU8JUEw7DyONgkVYg2SVtsoF28y0LGIr69jgA=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.44.0/go.mod h1:qZF+/lBs71APw8mlnEZcqZHMzqrYrsFiJOv83lX1OGo=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
|
||||||
|
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
|
||||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY=
|
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0 h1:rixTyDGXFxRy1xzhKrotaHy3/KXdPhlWARrCgK+eqUY=
|
||||||
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw=
|
go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.36.0/go.mod h1:dowW6UsM9MKbJq5JTz2AMVp3/5iW5I/TStsk8S+CfHw=
|
||||||
|
go.opentelemetry.io/otel/log v0.20.0 h1:/5i0vuHxCLWUfChWG41K9wkM0jafruPw9NU1/RCJirs=
|
||||||
|
go.opentelemetry.io/otel/log v0.20.0/go.mod h1:wOcMcjsZpG8x7Bak7IhSi/lg8wscV2C1VdrKCLPlt0E=
|
||||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||||
go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=
|
go.opentelemetry.io/otel/metric/x v0.66.0 h1:YkCrx1zLOChi9ZcZ6euupOcsgzbVlec7D/xoEU1+cTA=
|
||||||
go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=
|
go.opentelemetry.io/otel/metric/x v0.66.0/go.mod h1:d1+BDj9t96do0/1LoU1ayfCv79ZgNE41qbhBvnMOBZk=
|
||||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||||
|
go.opentelemetry.io/otel/sdk/log v0.20.0 h1:vM3xI7TQgKPiSghe6urZtAkyFY7SodrSpC83CffDFuY=
|
||||||
|
go.opentelemetry.io/otel/sdk/log v0.20.0/go.mod h1:Knej2nmsTUzN79T2eeXdRsjjPcoxoq2pUyUHz9TFyyU=
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||||
|
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||||
|
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||||
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||||
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
|
||||||
|
|||||||
+17
-4
@@ -1,7 +1,20 @@
|
|||||||
# Конфигурация наблюдаемости — реализовать
|
# Диагностика в Grafana
|
||||||
|
|
||||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
Откройте [дашборд мессенджера](http://localhost:3000/d/messenger-lab6) за последние 15 минут. Для свежих данных запустите `make test`. Grafana подключает Prometheus, Loki и Tempo через provisioning. Для ручного импорта используйте [JSON дашборда](grafana/dashboards/messenger.json) и [UID источников](grafana/provisioning/datasources/observability.yaml).
|
||||||
|
|
||||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
## MessengerQueueLag
|
||||||
|
|
||||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
1. Сравните глубину очереди, возраст старейшего задания и занятость worker. Алерт срабатывает, если есть ожидающие задания и возраст старейшего превышает 20 секунд в течение 9 секунд.
|
||||||
|
2. В Loki найдите `attachment.published` сервиса `messenger-outbox` и скопируйте `trace_id` в Tempo. Если consumer span `attachment.consume` долго отсутствует, проверьте worker командой `docker compose ps worker`.
|
||||||
|
3. После восстановления проверьте `attachment.ready` в Loki, `db.job.complete` в Tempo и возврат глубины очереди к нулю. В Prometheus правило перейдёт в `inactive`.
|
||||||
|
|
||||||
|
## MessengerHighErrorRate
|
||||||
|
|
||||||
|
1. Проверьте `messenger:api_errors:ratio1m` и `messenger:api_requests:count1m`. Алерт срабатывает после 12 секунд при доле 5xx выше 5% и как минимум пяти запросах за минуту.
|
||||||
|
2. Найдите маршрут через `sum by (route) (rate(messenger_http_requests_total{status_class="5xx"}[1m]))`. По `request_id` из `X-Request-Id` найдите лог в Loki. Скопируйте его `trace_id` в Tempo.
|
||||||
|
3. Сравните `db.pool.acquire` и `db.query`. Долгий `INSERT` при быстром получении соединения указывает на ожидание внутри PostgreSQL. Проверьте панель «Ожидание блокировки сообщений».
|
||||||
|
4. После восстановления выполните POST сообщения и дождитесь, пока 5xx выйдут из минутного окна. Состояние правила можно прочитать в Prometheus через `/api/v1/rules?type=alert`.
|
||||||
|
|
||||||
|
## Отказ Loki
|
||||||
|
|
||||||
|
Через Prometheus проверьте `otelcol_exporter_queue_size` и `otelcol_exporter_queue_capacity` для `exporter="otlphttp/loki"`, а также `otelcol_process_memory_rss_bytes`. После восстановления Loki убедитесь, что очередь опустела и новый лог появился. Историю сообщений проверьте через API. Пример измерений и оценка потерь приведены в [отчёте](../../REPORT.md).
|
||||||
|
|||||||
@@ -0,0 +1,35 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger
|
||||||
|
rules:
|
||||||
|
- record: messenger:api_requests:count1m
|
||||||
|
expr: sum(increase(messenger_http_requests_total{route!="<unmatched>"}[1m]))
|
||||||
|
- record: messenger:api_errors:ratio1m
|
||||||
|
expr: |
|
||||||
|
(sum(increase(messenger_http_requests_total{route!="<unmatched>",status_class="5xx"}[1m]))
|
||||||
|
or 0 * messenger:api_requests:count1m)
|
||||||
|
/ (messenger:api_requests:count1m > 0)
|
||||||
|
- record: messenger:api_availability:ratio30m
|
||||||
|
expr: |
|
||||||
|
1 - (
|
||||||
|
(sum(increase(messenger_http_requests_total{route!="<unmatched>",status_class="5xx"}[30m]))
|
||||||
|
or 0 * sum(increase(messenger_http_requests_total{route!="<unmatched>"}[30m])))
|
||||||
|
/ (sum(increase(messenger_http_requests_total{route!="<unmatched>"}[30m])) > 0)
|
||||||
|
)
|
||||||
|
- alert: MessengerHighErrorRate
|
||||||
|
expr: messenger:api_errors:ratio1m > 0.05 and messenger:api_requests:count1m >= 5
|
||||||
|
for: 12s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: "Более 5% бизнес-запросов API вернули 5xx за минуту"
|
||||||
|
runbook: infra/otel/README.md#messengerhigherrorrate
|
||||||
|
- alert: MessengerQueueLag
|
||||||
|
expr: |
|
||||||
|
max by (queue) (messenger_queue_oldest_age_seconds) > 20
|
||||||
|
and max by (queue) (messenger_queue_depth) > 0
|
||||||
|
for: 9s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: "В очереди есть задание, которое ждёт более 20 секунд"
|
||||||
|
runbook: infra/otel/README.md#messengerqueuelag
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 160
|
||||||
|
spike_limit_mib: 32
|
||||||
|
batch:
|
||||||
|
timeout: 1s
|
||||||
|
send_batch_size: 128
|
||||||
|
send_batch_max_size: 256
|
||||||
|
|
||||||
|
exporters:
|
||||||
|
prometheus:
|
||||||
|
endpoint: 0.0.0.0:9464
|
||||||
|
metric_expiration: 25s
|
||||||
|
enable_open_metrics: true
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
otlphttp/tempo:
|
||||||
|
endpoint: http://tempo:4318
|
||||||
|
timeout: 2s
|
||||||
|
sending_queue:
|
||||||
|
enabled: true
|
||||||
|
num_consumers: 1
|
||||||
|
queue_size: 8
|
||||||
|
retry_on_failure:
|
||||||
|
enabled: true
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 3s
|
||||||
|
max_elapsed_time: 12s
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: http://loki:3100/otlp
|
||||||
|
timeout: 2s
|
||||||
|
sending_queue:
|
||||||
|
enabled: true
|
||||||
|
num_consumers: 1
|
||||||
|
queue_size: 8
|
||||||
|
retry_on_failure:
|
||||||
|
enabled: true
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 3s
|
||||||
|
max_elapsed_time: 12s
|
||||||
|
|
||||||
|
service:
|
||||||
|
telemetry:
|
||||||
|
metrics:
|
||||||
|
readers:
|
||||||
|
- pull:
|
||||||
|
exporter:
|
||||||
|
prometheus:
|
||||||
|
host: 0.0.0.0
|
||||||
|
port: 8888
|
||||||
|
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,890 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-lab6",
|
||||||
|
"title": "Мессенджер · наблюдаемость",
|
||||||
|
"description": "Метрики бизнес-API и обработки вложений",
|
||||||
|
"tags": [
|
||||||
|
"lab6",
|
||||||
|
"messenger"
|
||||||
|
],
|
||||||
|
"schemaVersion": 40,
|
||||||
|
"version": 1,
|
||||||
|
"timezone": "browser",
|
||||||
|
"editable": true,
|
||||||
|
"time": {
|
||||||
|
"from": "now-15m",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"refresh": "5s",
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Запросы API",
|
||||||
|
"description": "Бизнес-запросы в секунду. Health и неизвестные маршруты исключены.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum(rate(messenger_http_requests_total{route!=\"<unmatched>\"}[$__rate_interval]))",
|
||||||
|
"legendFormat": "все запросы",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Доля ответов 5xx",
|
||||||
|
"description": "Доля 5xx от всех бизнес-запросов за 1 минуту. Порог алерта 5%.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 0,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "messenger:api_errors:ratio1m",
|
||||||
|
"legendFormat": "5xx / все",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit",
|
||||||
|
"min": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "orange",
|
||||||
|
"value": 0.05
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"custom": {
|
||||||
|
"thresholdsStyle": {
|
||||||
|
"mode": "line"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Доступность API за 30 минут",
|
||||||
|
"description": "SLI равен доле ответов без серверной ошибки. Цель 99%.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 0,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "messenger:api_availability:ratio30m",
|
||||||
|
"legendFormat": "доступность",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "vector(0.99)",
|
||||||
|
"legendFormat": "цель",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Длительность запросов API",
|
||||||
|
"description": "Квантили в секундах по всем API-репликам, включая ошибки.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 8,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!=\"<unmatched>\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p50",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!=\"<unmatched>\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p95",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!=\"<unmatched>\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p99",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Попытки обработки",
|
||||||
|
"description": "Успешные и ошибочные попытки в секунду. Повтор после сбоя считается новой попыткой.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 8,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (outcome) (rate(messenger_job_attempts_total[$__rate_interval]))",
|
||||||
|
"legendFormat": "{{outcome}}",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "suffix: попыток/с",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Длительность обработки",
|
||||||
|
"description": "Квантили длительности успешных попыток. Ошибочные попытки показаны отдельным p95.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 8,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket{outcome=\"success\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p50",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket{outcome=\"success\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p95",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket{outcome=\"success\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p99",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "D",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket{outcome=\"error\"}[$__rate_interval])))",
|
||||||
|
"legendFormat": "p95 ошибок",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Глубина очереди",
|
||||||
|
"description": "Количество заданий в состоянии queued, включая запланированные повторы.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 16,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max by (queue) (messenger_queue_depth)",
|
||||||
|
"legendFormat": "{{queue}}",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Возраст старейшего задания",
|
||||||
|
"description": "Секунды с принятия старейшего queued-задания. Порог алерта 20 с.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 16,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max by (queue) (messenger_queue_oldest_age_seconds)",
|
||||||
|
"legendFormat": "{{queue}}",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s",
|
||||||
|
"min": 0,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "orange",
|
||||||
|
"value": 20
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"custom": {
|
||||||
|
"thresholdsStyle": {
|
||||||
|
"mode": "line"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "От принятия до ready",
|
||||||
|
"description": "Очередь, ожидание повтора и обработка до коммита результата в БД.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 16,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[$__rate_interval])))",
|
||||||
|
"legendFormat": "p50",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[$__rate_interval])))",
|
||||||
|
"legendFormat": "p95",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[$__rate_interval])))",
|
||||||
|
"legendFormat": "p99",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Пулы PostgreSQL",
|
||||||
|
"description": "Занятые соединения, лимит пула и незавершённые вызовы Acquire.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 24,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "messenger_db_pool_used",
|
||||||
|
"legendFormat": "занято · {{service_name}} {{service_instance_id}}",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "messenger_db_pool_waiting",
|
||||||
|
"legendFormat": "запросы к пулу · {{service_name}} {{service_instance_id}}",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "messenger_db_pool_capacity",
|
||||||
|
"legendFormat": "ёмкость · {{service_name}} {{service_instance_id}}",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Загрузка слотов worker",
|
||||||
|
"description": "Отношение выполняемых задач к числу слотов. Снимок каждые 2 с.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 24,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum(messenger_worker_busy) / sum(messenger_worker_capacity)",
|
||||||
|
"legendFormat": "занято / всего",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 12,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Ожидание блокировки сообщений",
|
||||||
|
"description": "Число ожидающих блокировку таблицы messages по данным PostgreSQL.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 24,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max(messenger_db_messages_lock_waiters)",
|
||||||
|
"legendFormat": "ожидают",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 13,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "CPU процессов",
|
||||||
|
"description": "Потребление CPU API, relay и worker в эквиваленте ядер.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 32,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "rate(messenger_process_cpu_time_seconds_total[$__rate_interval])",
|
||||||
|
"legendFormat": "{{service_name}} {{service_instance_id}}",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "suffix: ядра",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 14,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Память процессов",
|
||||||
|
"description": "Текущий RSS процессов приложения и Collector, в байтах.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 32,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "messenger_process_memory_rss_bytes",
|
||||||
|
"legendFormat": "{{service_name}} {{service_instance_id}}",
|
||||||
|
"range": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "otelcol_process_memory_rss_bytes{job=\"otel-collector\"}",
|
||||||
|
"legendFormat": "Collector",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Алерты Prometheus",
|
||||||
|
"description": "В активные периоды значение 1. Статус inactive после восстановления виден в /api/v1/rules.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 32,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "ALERTS{alertname=~\"MessengerHighErrorRate|MessengerQueueLag\"}",
|
||||||
|
"legendFormat": "{{alertname}} · {{alertstate}}",
|
||||||
|
"range": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"showLegend": true,
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
},
|
||||||
|
"tooltip": {
|
||||||
|
"mode": "multi",
|
||||||
|
"sort": "desc"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 16,
|
||||||
|
"type": "logs",
|
||||||
|
"title": "События API, outbox и worker",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 40,
|
||||||
|
"w": 24,
|
||||||
|
"h": 9
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"showLabels": false,
|
||||||
|
"showTime": true,
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"dedupStrategy": "none",
|
||||||
|
"sortOrder": "Descending"
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"expr": "{service_name=~\"messenger-(api|outbox|worker)\"}",
|
||||||
|
"queryType": "range",
|
||||||
|
"maxLines": 100
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
providers:
|
||||||
|
- name: lab6
|
||||||
|
orgId: 1
|
||||||
|
folder: Мессенджер
|
||||||
|
type: file
|
||||||
|
updateIntervalSeconds: 10
|
||||||
|
options:
|
||||||
|
path: /etc/grafana/dashboards
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: http://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
jsonData:
|
||||||
|
timeInterval: 3s
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: http://loki:3100
|
||||||
|
jsonData:
|
||||||
|
derivedFields:
|
||||||
|
- name: Trace
|
||||||
|
matcherType: label
|
||||||
|
matcherRegex: "^trace_id$"
|
||||||
|
datasourceUid: tempo
|
||||||
|
url: '$${__value.raw}'
|
||||||
|
urlDisplayLabel: "Открыть трассу"
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: http://tempo:3200
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
spanStartTimeShift: '-1m'
|
||||||
|
spanEndTimeShift: '1m'
|
||||||
|
tags:
|
||||||
|
- key: service.name
|
||||||
|
value: service_name
|
||||||
|
customQuery: true
|
||||||
|
query: '{$$__tags} | trace_id="$${__span.traceId}"'
|
||||||
|
nodeGraph:
|
||||||
|
enabled: true
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
|
||||||
|
analytics:
|
||||||
|
reporting_enabled: false
|
||||||
|
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
instance_addr: 127.0.0.1
|
||||||
|
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
|
||||||
|
discover_log_levels: true
|
||||||
|
retention_period: 168h
|
||||||
|
|
||||||
|
distributor:
|
||||||
|
otlp_config:
|
||||||
|
default_resource_attributes_as_index_labels: [service.name]
|
||||||
|
|
||||||
|
compactor:
|
||||||
|
working_directory: /loki/compactor
|
||||||
|
retention_enabled: true
|
||||||
|
delete_request_store: filesystem
|
||||||
|
|
||||||
|
ingester:
|
||||||
|
wal:
|
||||||
|
dir: /loki/wal
|
||||||
|
flush_on_shutdown: true
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 3s
|
||||||
|
scrape_timeout: 2s
|
||||||
|
evaluation_interval: 3s
|
||||||
|
|
||||||
|
rule_files: [/etc/prometheus/alerts.yaml]
|
||||||
|
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: messenger
|
||||||
|
honor_labels: true
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:9464]
|
||||||
|
- job_name: otel-collector
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:8888]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
|
||||||
|
ingester:
|
||||||
|
trace_idle_period: 5s
|
||||||
|
max_block_duration: 1m
|
||||||
|
flush_all_on_shutdown: true
|
||||||
|
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 168h
|
||||||
|
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/blocks
|
||||||
@@ -14,6 +14,10 @@ import (
|
|||||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||||
"github.com/aws/smithy-go"
|
"github.com/aws/smithy-go"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrNotFound = errors.New("object not found")
|
var ErrNotFound = errors.New("object not found")
|
||||||
@@ -57,8 +61,10 @@ func NewS3(ctx context.Context, c S3Config) (*S3, error) {
|
|||||||
return &S3{client: client, bucket: c.Bucket}, nil
|
return &S3{client: client, bucket: c.Bucket}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
|
func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) (err error) {
|
||||||
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
ctx, span := startS3(ctx, "s3.put_object", key)
|
||||||
|
defer func() { telemetry.Finish(span, err) }()
|
||||||
|
_, err = s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||||
Bucket: aws.String(s.bucket),
|
Bucket: aws.String(s.bucket),
|
||||||
Key: aws.String(key),
|
Key: aws.String(key),
|
||||||
Body: body,
|
Body: body,
|
||||||
@@ -68,7 +74,9 @@ func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
func (s *S3) Get(ctx context.Context, key string) (_ io.ReadCloser, err error) {
|
||||||
|
ctx, span := startS3(ctx, "s3.get_object", key)
|
||||||
|
defer func() { telemetry.Finish(span, err) }()
|
||||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||||
Bucket: aws.String(s.bucket),
|
Bucket: aws.String(s.bucket),
|
||||||
Key: aws.String(key),
|
Key: aws.String(key),
|
||||||
@@ -82,14 +90,28 @@ func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
|||||||
return out.Body, nil
|
return out.Body, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
func (s *S3) Delete(ctx context.Context, key string) (err error) {
|
||||||
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
ctx, span := startS3(ctx, "s3.delete_object", key)
|
||||||
|
defer func() { telemetry.Finish(span, err) }()
|
||||||
|
_, err = s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||||
Bucket: aws.String(s.bucket),
|
Bucket: aws.String(s.bucket),
|
||||||
Key: aws.String(key),
|
Key: aws.String(key),
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func startS3(ctx context.Context, operation, key string) (context.Context, trace.Span) {
|
||||||
|
role := "original"
|
||||||
|
switch {
|
||||||
|
case strings.HasPrefix(key, "staging/"):
|
||||||
|
role = "staging"
|
||||||
|
case strings.Contains(key, "/v1/"):
|
||||||
|
role = "variant"
|
||||||
|
}
|
||||||
|
return telemetry.Tracer.Start(ctx, operation, trace.WithSpanKind(trace.SpanKindClient),
|
||||||
|
trace.WithAttributes(attribute.String("rpc.system", "aws-api"), attribute.String("s3.object.role", role)))
|
||||||
|
}
|
||||||
|
|
||||||
func (s *S3) Ping(ctx context.Context) error {
|
func (s *S3) Ping(ctx context.Context) error {
|
||||||
body := []byte("ok")
|
body := []byte("ok")
|
||||||
if _, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
if _, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||||
|
|||||||
+1
-1
@@ -27,7 +27,7 @@ func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
|||||||
|
|
||||||
connCtx, cancel := context.WithTimeout(ctx, cfg.ConnTimeout)
|
connCtx, cancel := context.WithTimeout(ctx, cfg.ConnTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
pool, err := pgxpool.NewWithConfig(connCtx, poolCfg)
|
pool, err := NewPool(connCtx, poolCfg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("create pool: %w", err)
|
return nil, fmt.Errorf("create pool: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package db
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
|
)
|
||||||
|
|
||||||
|
type postgresTracer struct{ waiting atomic.Int64 }
|
||||||
|
|
||||||
|
func NewPool(ctx context.Context, cfg *pgxpool.Config) (*pgxpool.Pool, error) {
|
||||||
|
tracer := &postgresTracer{}
|
||||||
|
cfg.ConnConfig.Tracer = tracer
|
||||||
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = tracer.observe(pool)
|
||||||
|
if err != nil {
|
||||||
|
pool.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *postgresTracer) observe(pool *pgxpool.Pool) error {
|
||||||
|
used, err := telemetry.Meter.Int64ObservableGauge("messenger.db.pool.used")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
waiting, err := telemetry.Meter.Int64ObservableGauge("messenger.db.pool.waiting")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
capacity, err := telemetry.Meter.Int64ObservableGauge("messenger.db.pool.capacity")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = telemetry.Meter.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
|
||||||
|
stats := pool.Stat()
|
||||||
|
observer.ObserveInt64(used, int64(stats.AcquiredConns()))
|
||||||
|
observer.ObserveInt64(waiting, t.waiting.Load())
|
||||||
|
observer.ObserveInt64(capacity, int64(stats.MaxConns()))
|
||||||
|
return nil
|
||||||
|
}, used, waiting, capacity)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *postgresTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||||
|
if !trace.SpanFromContext(ctx).IsRecording() {
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
sql := strings.TrimSpace(data.SQL)
|
||||||
|
first := strings.IndexAny(sql, " \t\r\n;")
|
||||||
|
if first >= 0 {
|
||||||
|
sql = sql[:first]
|
||||||
|
}
|
||||||
|
operation := strings.ToUpper(sql)
|
||||||
|
switch operation {
|
||||||
|
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
||||||
|
default:
|
||||||
|
operation = "OTHER"
|
||||||
|
}
|
||||||
|
ctx, _ = telemetry.Tracer.Start(ctx, "db.query", trace.WithSpanKind(trace.SpanKindClient),
|
||||||
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", operation)))
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *postgresTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||||
|
if span := trace.SpanFromContext(ctx); span.IsRecording() {
|
||||||
|
err := data.Err
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
err = nil
|
||||||
|
}
|
||||||
|
telemetry.Finish(span, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *postgresTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||||
|
t.waiting.Add(1)
|
||||||
|
if !trace.SpanFromContext(ctx).IsRecording() {
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
ctx, _ = telemetry.Tracer.Start(ctx, "db.pool.acquire", trace.WithSpanKind(trace.SpanKindClient),
|
||||||
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||||
|
return ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
func (t *postgresTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
||||||
|
t.waiting.Add(-1)
|
||||||
|
if span := trace.SpanFromContext(ctx); span.IsRecording() {
|
||||||
|
telemetry.Finish(span, data.Err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
_ "image/jpeg"
|
_ "image/jpeg"
|
||||||
_ "image/png"
|
_ "image/png"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
|
||||||
"mime"
|
"mime"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
@@ -25,6 +24,7 @@ import (
|
|||||||
"mtusi2026/internal/jobs"
|
"mtusi2026/internal/jobs"
|
||||||
"mtusi2026/internal/model"
|
"mtusi2026/internal/model"
|
||||||
"mtusi2026/internal/store"
|
"mtusi2026/internal/store"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -162,7 +162,7 @@ func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u m
|
|||||||
err = a.blobs.Put(putCtx, stagingKey, io.NewSectionReader(tmp, 0, n), n, mt)
|
err = a.blobs.Put(putCtx, stagingKey, io.NewSectionReader(tmp, 0, n), n, mt)
|
||||||
cancel()
|
cancel()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("s3 put failed: %v", err)
|
telemetry.Error(r.Context(), "attachment.staging.write_failed")
|
||||||
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
|
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
|
||||||
_ = a.blobs.Delete(delCtx, stagingKey)
|
_ = a.blobs.Delete(delCtx, stagingKey)
|
||||||
delCancel()
|
delCancel()
|
||||||
@@ -177,7 +177,7 @@ func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u m
|
|||||||
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, StagingKey: stagingKey,
|
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, StagingKey: stagingKey,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("attachment metadata commit uncertain, staging retained: %v", err)
|
telemetry.Error(r.Context(), "attachment.accept_failed")
|
||||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -252,10 +252,10 @@ func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u
|
|||||||
t.Stop()
|
t.Stop()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, blobstore.ErrNotFound) {
|
if errors.Is(err, blobstore.ErrNotFound) {
|
||||||
log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey)
|
telemetry.Error(r.Context(), "attachment.object_missing")
|
||||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||||
} else {
|
} else {
|
||||||
log.Printf("s3 get failed: %v", err)
|
telemetry.Error(r.Context(), "attachment.object_read_failed")
|
||||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"regexp"
|
"regexp"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"mtusi2026/internal/idgen"
|
"mtusi2026/internal/idgen"
|
||||||
"mtusi2026/internal/model"
|
"mtusi2026/internal/model"
|
||||||
@@ -46,7 +48,9 @@ func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u mode
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text, ids)
|
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
m, err := a.store.CreateMessage(ctx, chatID, u.ID, key, req.Text, ids)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
|
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
|
||||||
|
|||||||
@@ -1,30 +1,66 @@
|
|||||||
package httpapi
|
package httpapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/felixge/httpsnoop"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
otellog "go.opentelemetry.io/otel/log"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
"go.opentelemetry.io/otel/propagation"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
"mtusi2026/internal/store"
|
"mtusi2026/internal/store"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
)
|
)
|
||||||
|
|
||||||
type statusRecorder struct {
|
var (
|
||||||
http.ResponseWriter
|
httpRequests, _ = telemetry.Meter.Int64Counter("messenger.http.requests")
|
||||||
status int
|
httpDuration, _ = telemetry.Meter.Float64Histogram("messenger.http.request.duration",
|
||||||
}
|
metric.WithUnit("s"),
|
||||||
|
metric.WithExplicitBucketBoundaries(.001, .0025, .005, .01, .025, .05, .1, .25, .5, 1, 2, 4, 8, 15, 30, 60))
|
||||||
|
)
|
||||||
|
|
||||||
func (r *statusRecorder) WriteHeader(status int) {
|
func observeRequests(root, apiMux *http.ServeMux) http.Handler {
|
||||||
r.status = status
|
|
||||||
r.ResponseWriter.WriteHeader(status)
|
|
||||||
}
|
|
||||||
|
|
||||||
func loggingMiddleware(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
start := time.Now()
|
_, pattern := root.Handler(r)
|
||||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
if pattern == "GET /health/live" || pattern == "GET /health/ready" {
|
||||||
next.ServeHTTP(rec, r)
|
root.ServeHTTP(w, r)
|
||||||
log.Printf("method=%s path=%s status=%d duration=%s",
|
return
|
||||||
r.Method, r.URL.Path, rec.status, time.Since(start))
|
}
|
||||||
|
_, pattern = apiMux.Handler(r)
|
||||||
|
registeredMethod, route, matched := strings.Cut(pattern, " ")
|
||||||
|
if !matched || (registeredMethod != r.Method && !(r.Method == http.MethodHead && registeredMethod == http.MethodGet)) {
|
||||||
|
route = "<unmatched>"
|
||||||
|
}
|
||||||
|
method := r.Method
|
||||||
|
switch method {
|
||||||
|
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
|
||||||
|
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace:
|
||||||
|
default:
|
||||||
|
method = "_OTHER"
|
||||||
|
}
|
||||||
|
ctx := telemetry.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||||
|
ctx, span := telemetry.Tracer.Start(ctx, method+" "+route, trace.WithSpanKind(trace.SpanKindServer),
|
||||||
|
trace.WithAttributes(attribute.String("http.request.method", method), attribute.String("http.route", route)))
|
||||||
|
defer span.End()
|
||||||
|
result := httpsnoop.CaptureMetrics(root, w, r.WithContext(ctx))
|
||||||
|
statusClass := strconv.Itoa(result.Code/100) + "xx"
|
||||||
|
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
|
||||||
|
attribute.String("status_class", statusClass))
|
||||||
|
httpRequests.Add(ctx, 1, attrs)
|
||||||
|
httpDuration.Record(ctx, result.Duration.Seconds(), attrs)
|
||||||
|
span.SetAttributes(attribute.Int("http.response.status_code", result.Code))
|
||||||
|
severity := otellog.SeverityInfo
|
||||||
|
if result.Code >= 500 {
|
||||||
|
severity = otellog.SeverityError
|
||||||
|
telemetry.SetError(span, statusClass)
|
||||||
|
}
|
||||||
|
telemetry.Event(ctx, severity, "http.request",
|
||||||
|
otellog.String("method", method), otellog.String("route", route), otellog.Int("http.status_code", result.Code),
|
||||||
|
otellog.Float64("duration_s", result.Duration.Seconds()), otellog.String("request_id", w.Header().Get("X-Request-Id")))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -82,10 +82,7 @@ func NewRouterWithCache(
|
|||||||
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
|
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
|
||||||
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
|
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
|
||||||
|
|
||||||
var h http.Handler = root
|
return instanceMiddleware(o.InstanceID, observeRequests(root, apiMux))
|
||||||
h = loggingMiddleware(h)
|
|
||||||
h = instanceMiddleware(o.InstanceID, h)
|
|
||||||
return h
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func instanceMiddleware(id string, next http.Handler) http.Handler {
|
func instanceMiddleware(id string, next http.Handler) http.Handler {
|
||||||
|
|||||||
@@ -10,11 +10,16 @@ import (
|
|||||||
|
|
||||||
"mtusi2026/internal/idgen"
|
"mtusi2026/internal/idgen"
|
||||||
"mtusi2026/internal/model"
|
"mtusi2026/internal/model"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const JobType = "attachment.process.v1"
|
||||||
|
|
||||||
type Job struct {
|
type Job struct {
|
||||||
SchemaVersion int `json:"schema_version"`
|
SchemaVersion int `json:"schema_version"`
|
||||||
ID string `json:"job_id"`
|
ID string `json:"job_id"`
|
||||||
@@ -38,7 +43,9 @@ type Work struct {
|
|||||||
|
|
||||||
func Enqueue(ctx context.Context, tx pgx.Tx, attachmentID string) error {
|
func Enqueue(ctx context.Context, tx pgx.Tx, attachmentID string) error {
|
||||||
id := idgen.GenerateUUIDv4()
|
id := idgen.GenerateUUIDv4()
|
||||||
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id) VALUES($1,$2)`, id, attachmentID)
|
carrier := telemetry.Inject(ctx)
|
||||||
|
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,created_at,traceparent,tracestate)
|
||||||
|
VALUES($1,$2,clock_timestamp(),NULLIF($3,''),NULLIF($4,''))`, id, attachmentID, carrier.Get("traceparent"), carrier.Get("tracestate"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -57,7 +64,7 @@ func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
|
|||||||
lease_token=$3,lease_until=now()+$4::interval,updated_at=now()
|
lease_token=$3,lease_until=now()+$4::interval,updated_at=now()
|
||||||
WHERE id=$1 AND attachment_id=$2 AND pipeline_version=$5 AND status='queued'
|
WHERE id=$1 AND attachment_id=$2 AND pipeline_version=$5 AND status='queued'
|
||||||
AND next_attempt_at<=now() AND attempt=$6-1
|
AND next_attempt_at<=now() AND attempt=$6-1
|
||||||
RETURNING attempt`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt)
|
RETURNING attempt,created_at`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt, &w.CreatedAt)
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
@@ -76,7 +83,10 @@ func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
|
|||||||
return w, nil
|
return w, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (bool, error) {
|
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (_ bool, err error) {
|
||||||
|
ctx, span := telemetry.Tracer.Start(ctx, "db.job.complete",
|
||||||
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||||
|
defer func() { telemetry.Finish(span, err) }()
|
||||||
tx, err := r.Pool.Begin(ctx)
|
tx, err := r.Pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
@@ -247,7 +257,7 @@ func (r Repo) Failed(ctx context.Context) ([]map[string]any, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (j Job) Validate() error {
|
func (j Job) Validate() error {
|
||||||
if j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
|
if j.SchemaVersion != 1 || j.Type != JobType || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
|
||||||
return fmt.Errorf("invalid job envelope")
|
return fmt.Errorf("invalid job envelope")
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
+78
-27
@@ -13,14 +13,21 @@ import (
|
|||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"mtusi2026/internal/blobstore"
|
"mtusi2026/internal/blobstore"
|
||||||
"mtusi2026/internal/images"
|
"mtusi2026/internal/images"
|
||||||
"mtusi2026/internal/model"
|
"mtusi2026/internal/model"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
otellog "go.opentelemetry.io/otel/log"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
"go.opentelemetry.io/otel/propagation"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
)
|
)
|
||||||
|
|
||||||
const Stream = "attachment-jobs-v1"
|
const Stream = "attachment-jobs-v1"
|
||||||
@@ -34,20 +41,24 @@ type Runtime struct {
|
|||||||
Concurrency int
|
Concurrency int
|
||||||
Fault string
|
Fault string
|
||||||
Retention time.Duration
|
Retention time.Duration
|
||||||
|
busy atomic.Int64
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
func (r *Runtime) PublishOne(ctx context.Context) (_ bool, err error) {
|
||||||
tx, err := r.Repo.Pool.Begin(ctx)
|
tx, err := r.Repo.Pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
defer tx.Rollback(ctx)
|
defer tx.Rollback(ctx)
|
||||||
var oid int64
|
var oid int64
|
||||||
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
|
var parent, state string
|
||||||
err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at
|
j := Job{SchemaVersion: 1, Type: JobType}
|
||||||
|
err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at,
|
||||||
|
COALESCE(j.traceparent,''),COALESCE(j.tracestate,'')
|
||||||
FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id
|
FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id
|
||||||
WHERE o.published_at IS NULL AND o.available_at<=now()
|
WHERE o.published_at IS NULL AND o.available_at<=now()
|
||||||
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED`).Scan(&oid, &j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt)
|
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED`).
|
||||||
|
Scan(&oid, &j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt, &parent, &state)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
return false, nil
|
return false, nil
|
||||||
@@ -62,12 +73,21 @@ func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
ctx = telemetry.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
||||||
|
ctx, span := telemetry.Tracer.Start(ctx, "attachment.publish", trace.WithSpanKind(trace.SpanKindProducer), messagingAttributes("send", j))
|
||||||
|
defer func() { telemetry.Finish(span, err) }()
|
||||||
|
values := map[string]any{"payload": string(payload)}
|
||||||
|
for key, value := range telemetry.Inject(ctx) {
|
||||||
|
values[key] = value
|
||||||
|
}
|
||||||
pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||||
_, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"payload": string(payload)}}).Result()
|
_, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: values}).Result()
|
||||||
cancel()
|
cancel()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
telemetry.Warn(ctx, "attachment.publish_failed", otellog.Int("job.attempt", j.Attempt))
|
||||||
return false, err
|
return false, err
|
||||||
}
|
}
|
||||||
|
telemetry.Info(ctx, "attachment.published", otellog.Int("job.attempt", j.Attempt))
|
||||||
if r.Fault == "after_publish" {
|
if r.Fault == "after_publish" {
|
||||||
log.Print("FAULT after_publish: duplicate publication expected")
|
log.Print("FAULT after_publish: duplicate publication expected")
|
||||||
os.Exit(86)
|
os.Exit(86)
|
||||||
@@ -79,6 +99,16 @@ func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
|||||||
return true, tx.Commit(ctx)
|
return true, tx.Commit(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func messagingAttributes(operation string, j Job) trace.SpanStartOption {
|
||||||
|
return trace.WithAttributes(
|
||||||
|
attribute.String("messaging.system", "redis"),
|
||||||
|
attribute.String("messaging.destination.name", Stream),
|
||||||
|
attribute.String("messaging.operation.type", operation),
|
||||||
|
attribute.String("job.type", j.Type),
|
||||||
|
attribute.Int("job.attempt", j.Attempt),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Runtime) Relay(ctx context.Context) {
|
func (r *Runtime) Relay(ctx context.Context) {
|
||||||
tick := time.NewTicker(300 * time.Millisecond)
|
tick := time.NewTicker(300 * time.Millisecond)
|
||||||
defer tick.Stop()
|
defer tick.Stop()
|
||||||
@@ -163,28 +193,52 @@ func (r *Runtime) deliver(ctx context.Context, m redis.XMessage) {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
parent, _ := m.Values["traceparent"].(string)
|
||||||
|
state, _ := m.Values["tracestate"].(string)
|
||||||
|
ctx = telemetry.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
||||||
|
ctx, span := telemetry.Tracer.Start(ctx, "attachment.consume", trace.WithSpanKind(trace.SpanKindConsumer), messagingAttributes("process", j))
|
||||||
|
defer span.End()
|
||||||
w, err := r.Repo.Claim(ctx, j)
|
w, err := r.Repo.Claim(ctx, j)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("claim job=%s: %v", j.ID, err)
|
telemetry.SetError(span, "claim_failed")
|
||||||
|
telemetry.Error(ctx, "attachment.claim_failed", otellog.Int("job.attempt", j.Attempt))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if w != nil {
|
if w != nil {
|
||||||
err = r.process(ctx, w)
|
started := time.Now()
|
||||||
|
r.busy.Add(1)
|
||||||
|
code, err := r.process(ctx, w)
|
||||||
|
r.busy.Add(-1)
|
||||||
|
outcome := "success"
|
||||||
|
logFields := []otellog.KeyValue{otellog.String("job.type", j.Type), otellog.Int("job.attempt", j.Attempt)}
|
||||||
|
if code != "" {
|
||||||
|
outcome = "error"
|
||||||
|
telemetry.SetError(span, code)
|
||||||
|
telemetry.Error(ctx, "attachment.attempt_failed", append(logFields, otellog.String("error.type", code))...)
|
||||||
|
} else {
|
||||||
|
telemetry.Info(ctx, "attachment.ready", logFields...)
|
||||||
|
}
|
||||||
|
span.SetAttributes(attribute.String("job.outcome", outcome))
|
||||||
|
attrs := metric.WithAttributes(attribute.String("job_type", j.Type), attribute.String("outcome", outcome))
|
||||||
|
jobAttempts.Add(ctx, 1, attrs)
|
||||||
|
jobDuration.Record(ctx, time.Since(started).Seconds(), attrs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("process job=%s attempt=%d: %v", j.ID, w.Attempt, err)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
span.SetAttributes(attribute.String("job.outcome", "duplicate"))
|
||||||
}
|
}
|
||||||
if r.Fault == "before_ack" {
|
if r.Fault == "before_ack" {
|
||||||
log.Print("FAULT before_ack: durable DB result, pending broker delivery")
|
log.Print("FAULT before_ack: durable DB result, pending broker delivery")
|
||||||
os.Exit(86)
|
os.Exit(86)
|
||||||
}
|
}
|
||||||
if err = r.Broker.XAck(ctx, Stream, Group, m.ID).Err(); err != nil {
|
if err = r.Broker.XAck(ctx, Stream, Group, m.ID).Err(); err != nil {
|
||||||
log.Printf("ack job=%s: %v", j.ID, err)
|
telemetry.SetError(span, "ack_failed")
|
||||||
|
telemetry.Warn(ctx, "attachment.ack_failed", otellog.Int("job.attempt", j.Attempt))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Runtime) process(ctx context.Context, w *Work) error {
|
func (r *Runtime) process(ctx context.Context, w *Work) (string, error) {
|
||||||
workCtx, cancel := context.WithTimeout(ctx, r.Timeout)
|
workCtx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
variants, err := r.effects(workCtx, w)
|
variants, err := r.effects(workCtx, w)
|
||||||
@@ -202,30 +256,27 @@ func (r *Runtime) process(ctx context.Context, w *Work) error {
|
|||||||
case errors.Is(err, blobstore.ErrNotFound):
|
case errors.Is(err, blobstore.ErrNotFound):
|
||||||
code, permanent = "staging_missing", true
|
code, permanent = "staging_missing", true
|
||||||
}
|
}
|
||||||
log.Printf("job=%s attempt=%d error_code=%s", w.ID, w.Attempt, code)
|
return code, r.Repo.Fail(dbCtx, w, code, permanent)
|
||||||
return r.Repo.Fail(dbCtx, w, code, permanent)
|
|
||||||
}
|
}
|
||||||
ok, err := r.Repo.Complete(dbCtx, w, variants)
|
ok, err := r.Repo.Complete(dbCtx, w, variants)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return "complete_failed", err
|
||||||
}
|
}
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("completion lease expired or replaced; delivery left pending")
|
return "lease_lost", errors.New("completion lease expired or replaced; delivery left pending")
|
||||||
}
|
}
|
||||||
if ok {
|
timeToReady.Record(ctx, max(0, time.Since(w.CreatedAt).Seconds()), metric.WithAttributes(attribute.String("job_type", w.Type)))
|
||||||
log.Printf("job=%s attempt=%d ready variants=%d", w.ID, w.Attempt, len(variants))
|
if r.Fault == "after_commit" {
|
||||||
if r.Fault == "after_commit" {
|
log.Print("FAULT after_commit")
|
||||||
log.Print("FAULT after_commit")
|
os.Exit(86)
|
||||||
os.Exit(86)
|
|
||||||
}
|
|
||||||
if err = r.Blobs.Delete(dbCtx, w.StagingKey); err == nil {
|
|
||||||
_, err = r.Repo.Pool.Exec(dbCtx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, w.AttachmentID)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("defer staging cleanup job=%s", w.ID)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return nil
|
if err = r.Blobs.Delete(dbCtx, w.StagingKey); err == nil {
|
||||||
|
_, err = r.Repo.Pool.Exec(dbCtx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, w.AttachmentID)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
telemetry.Warn(ctx, "attachment.staging.cleanup_deferred")
|
||||||
|
}
|
||||||
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Runtime) effects(ctx context.Context, w *Work) ([]model.Variant, error) {
|
func (r *Runtime) effects(ctx context.Context, w *Work) ([]model.Variant, error) {
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package jobs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
jobAttempts, _ = telemetry.Meter.Int64Counter("messenger.job.attempts")
|
||||||
|
jobDuration, _ = telemetry.Meter.Float64Histogram("messenger.job.processing.duration", metric.WithUnit("s"),
|
||||||
|
metric.WithExplicitBucketBoundaries(.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120, 300))
|
||||||
|
timeToReady, _ = telemetry.Meter.Float64Histogram("messenger.attachment.time_to_ready", metric.WithUnit("s"),
|
||||||
|
metric.WithExplicitBucketBoundaries(.05, .1, .25, .5, 1, 2, 3, 5, 10, 15, 20, 30, 45, 60, 120, 300))
|
||||||
|
)
|
||||||
|
|
||||||
|
func (r *Runtime) ObserveWorker() error {
|
||||||
|
busy, err := telemetry.Meter.Int64ObservableGauge("messenger.worker.busy")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
capacity, err := telemetry.Meter.Int64ObservableGauge("messenger.worker.capacity")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = telemetry.Meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||||
|
o.ObserveInt64(busy, r.busy.Load())
|
||||||
|
o.ObserveInt64(capacity, int64(r.Concurrency))
|
||||||
|
return nil
|
||||||
|
}, busy, capacity)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Runtime) ObserveQueue() error {
|
||||||
|
depth, err := telemetry.Meter.Int64ObservableGauge("messenger.queue.depth")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
oldest, err := telemetry.Meter.Float64ObservableGauge("messenger.queue.oldest.age", metric.WithUnit("s"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
lockWaiters, err := telemetry.Meter.Int64ObservableGauge("messenger.db.messages.lock.waiters")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
attrs := metric.WithAttributes(attribute.String("queue", Stream))
|
||||||
|
_, err = telemetry.Meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||||
|
ctx, cancel := context.WithTimeout(ctx, 750*time.Millisecond)
|
||||||
|
defer cancel()
|
||||||
|
var size, waiters int64
|
||||||
|
var age float64
|
||||||
|
err := r.Repo.Pool.QueryRow(ctx, `
|
||||||
|
SELECT count(*), COALESCE(EXTRACT(EPOCH FROM (now() - min(created_at))), 0)::double precision,
|
||||||
|
(SELECT count(*) FROM pg_catalog.pg_locks WHERE relation = 'messages'::regclass AND NOT granted)
|
||||||
|
FROM attachment_jobs WHERE status = 'queued'`).Scan(&size, &age, &waiters)
|
||||||
|
if err == nil {
|
||||||
|
o.ObserveInt64(depth, size, attrs)
|
||||||
|
o.ObserveFloat64(oldest, max(0, age), attrs)
|
||||||
|
o.ObserveInt64(lockWaiters, waiters)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}, depth, oldest, lockWaiters)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -15,11 +15,14 @@ import (
|
|||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
"github.com/jackc/pgx/v5/pgconn"
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
"github.com/jackc/pgx/v5/pgxpool"
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
"mtusi2026/internal/cursor"
|
"mtusi2026/internal/cursor"
|
||||||
"mtusi2026/internal/idgen"
|
"mtusi2026/internal/idgen"
|
||||||
"mtusi2026/internal/jobs"
|
"mtusi2026/internal/jobs"
|
||||||
"mtusi2026/internal/model"
|
"mtusi2026/internal/model"
|
||||||
|
"mtusi2026/internal/telemetry"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -55,7 +58,10 @@ func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool,
|
|||||||
return ok, err
|
return ok, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
|
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (_ model.Attachment, err error) {
|
||||||
|
ctx, span := telemetry.Tracer.Start(ctx, "db.attachment.accept",
|
||||||
|
trace.WithAttributes(attribute.String("db.system.name", "postgresql")))
|
||||||
|
defer func() { telemetry.Finish(span, err) }()
|
||||||
tx, err := s.pool.Begin(ctx)
|
tx, err := s.pool.Begin(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return a, err
|
return a, err
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package telemetry
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.opentelemetry.io/otel/metric"
|
||||||
|
)
|
||||||
|
|
||||||
|
func observeProcess() error {
|
||||||
|
_, err := Meter.Float64ObservableCounter("messenger.process.cpu.time",
|
||||||
|
metric.WithUnit("s"),
|
||||||
|
metric.WithFloat64Callback(func(_ context.Context, observer metric.Float64Observer) error {
|
||||||
|
var usage syscall.Rusage
|
||||||
|
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
|
||||||
|
observer.Observe(time.Duration(usage.Utime.Nano() + usage.Stime.Nano()).Seconds())
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_, err = Meter.Int64ObservableGauge("messenger.process.memory.rss",
|
||||||
|
metric.WithUnit("By"),
|
||||||
|
metric.WithInt64Callback(func(_ context.Context, observer metric.Int64Observer) error {
|
||||||
|
raw, err := os.ReadFile("/proc/self/statm")
|
||||||
|
if err == nil {
|
||||||
|
fields := strings.Fields(string(raw))
|
||||||
|
if len(fields) > 1 {
|
||||||
|
if pages, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
|
||||||
|
observer.Observe(pages * int64(os.Getpagesize()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
return err
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
package telemetry
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"go.opentelemetry.io/otel"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
"go.opentelemetry.io/otel/codes"
|
||||||
|
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||||
|
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||||
|
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||||
|
otellog "go.opentelemetry.io/otel/log"
|
||||||
|
logglobal "go.opentelemetry.io/otel/log/global"
|
||||||
|
"go.opentelemetry.io/otel/propagation"
|
||||||
|
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||||
|
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||||
|
"go.opentelemetry.io/otel/sdk/resource"
|
||||||
|
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||||
|
"go.opentelemetry.io/otel/trace"
|
||||||
|
|
||||||
|
"mtusi2026/internal/config"
|
||||||
|
)
|
||||||
|
|
||||||
|
const scope = "mtusi2026/messenger"
|
||||||
|
const exportTimeout = time.Second
|
||||||
|
|
||||||
|
var (
|
||||||
|
Tracer = otel.Tracer(scope)
|
||||||
|
Meter = otel.Meter(scope)
|
||||||
|
logger = logglobal.Logger(scope)
|
||||||
|
)
|
||||||
|
|
||||||
|
func Start(ctx context.Context, service, instance string) (func(), error) {
|
||||||
|
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == "" {
|
||||||
|
return func() {}, nil
|
||||||
|
}
|
||||||
|
res, err := resource.New(ctx, resource.WithFromEnv(), resource.WithAttributes(
|
||||||
|
attribute.String("service.name", config.GetEnv("OTEL_SERVICE_NAME", service)),
|
||||||
|
attribute.String("service.version", config.GetEnv("APP_VERSION", "dev")),
|
||||||
|
attribute.String("service.instance.id", instance),
|
||||||
|
))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
traces, err := otlptracehttp.New(ctx,
|
||||||
|
otlptracehttp.WithTimeout(exportTimeout),
|
||||||
|
otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
metrics, err := otlpmetrichttp.New(ctx,
|
||||||
|
otlpmetrichttp.WithTimeout(exportTimeout),
|
||||||
|
otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
logs, err := otlploghttp.New(ctx,
|
||||||
|
otlploghttp.WithTimeout(exportTimeout),
|
||||||
|
otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res),
|
||||||
|
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
|
||||||
|
sdktrace.WithBatcher(traces,
|
||||||
|
sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128),
|
||||||
|
sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(exportTimeout),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res),
|
||||||
|
sdkmetric.WithCardinalityLimit(500),
|
||||||
|
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metrics,
|
||||||
|
sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(2*time.Second),
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res),
|
||||||
|
sdklog.WithProcessor(sdklog.NewBatchProcessor(logs,
|
||||||
|
sdklog.WithMaxQueueSize(1024), sdklog.WithExportMaxBatchSize(128),
|
||||||
|
sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(exportTimeout),
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
otel.SetTracerProvider(tp)
|
||||||
|
otel.SetMeterProvider(mp)
|
||||||
|
logglobal.SetLoggerProvider(lp)
|
||||||
|
if err := observeProcess(); err != nil {
|
||||||
|
log.Print("telemetry: process metrics unavailable")
|
||||||
|
}
|
||||||
|
return func() {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||||
|
defer cancel()
|
||||||
|
if err := errors.Join(tp.Shutdown(ctx), lp.Shutdown(ctx), mp.Shutdown(ctx)); err != nil {
|
||||||
|
log.Print("telemetry: shutdown did not flush all signals")
|
||||||
|
}
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
|
||||||
|
return (propagation.TraceContext{}).Extract(ctx, carrier)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Inject(ctx context.Context) propagation.MapCarrier {
|
||||||
|
carrier := make(propagation.MapCarrier, 2)
|
||||||
|
(propagation.TraceContext{}).Inject(ctx, carrier)
|
||||||
|
return carrier
|
||||||
|
}
|
||||||
|
|
||||||
|
func Finish(span trace.Span, err error) {
|
||||||
|
if err != nil {
|
||||||
|
code := "operation_failed"
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, context.DeadlineExceeded):
|
||||||
|
code = "deadline_exceeded"
|
||||||
|
case errors.Is(err, context.Canceled):
|
||||||
|
code = "canceled"
|
||||||
|
}
|
||||||
|
SetError(span, code)
|
||||||
|
}
|
||||||
|
span.End()
|
||||||
|
}
|
||||||
|
|
||||||
|
func SetError(span trace.Span, code string) {
|
||||||
|
span.SetAttributes(attribute.String("error.type", code))
|
||||||
|
span.SetStatus(codes.Error, code)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Event(ctx context.Context, severity otellog.Severity, event string, attrs ...otellog.KeyValue) {
|
||||||
|
var record otellog.Record
|
||||||
|
record.SetTimestamp(time.Now())
|
||||||
|
record.SetSeverity(severity)
|
||||||
|
record.SetSeverityText(severity.String())
|
||||||
|
record.SetBody(otellog.StringValue(event))
|
||||||
|
record.AddAttributes(otellog.String("event", event))
|
||||||
|
record.AddAttributes(attrs...)
|
||||||
|
logger.Emit(ctx, record)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Warn(ctx context.Context, event string, attrs ...otellog.KeyValue) {
|
||||||
|
Event(ctx, otellog.SeverityWarn, event, attrs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Error(ctx context.Context, event string, attrs ...otellog.KeyValue) {
|
||||||
|
Event(ctx, otellog.SeverityError, event, attrs...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func Info(ctx context.Context, event string, attrs ...otellog.KeyValue) {
|
||||||
|
Event(ctx, otellog.SeverityInfo, event, attrs...)
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
DROP INDEX attachment_jobs_queued_created_at;
|
||||||
|
ALTER TABLE attachment_jobs DROP COLUMN tracestate;
|
||||||
|
ALTER TABLE attachment_jobs DROP COLUMN traceparent;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
ALTER TABLE attachment_jobs ADD COLUMN traceparent TEXT;
|
||||||
|
ALTER TABLE attachment_jobs ADD COLUMN tracestate TEXT;
|
||||||
|
CREATE INDEX attachment_jobs_queued_created_at ON attachment_jobs(created_at) WHERE status = 'queued';
|
||||||
+20
-14
@@ -3,25 +3,31 @@ set -eu
|
|||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
[ -f .env ] || { cp .env.example .env; echo ".env создан из .env.example"; }
|
[ -f .env ] || { cp .env.example .env; echo ".env создан из .env.example"; }
|
||||||
mkdir -p secrets
|
mkdir -p secrets
|
||||||
|
chmod 700 secrets
|
||||||
python3 - <<'PY'
|
python3 - <<'PY'
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
import secrets
|
import secrets
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
env = Path('.env')
|
env = Path('.env')
|
||||||
lines = env.read_text().splitlines()
|
values = dict(line.split('=', 1) for line in env.read_text().splitlines() if '=' in line and not line.lstrip().startswith('#'))
|
||||||
values = dict(line.split('=', 1) for line in lines if '=' in line and not line.startswith('#'))
|
|
||||||
password_file = Path('secrets/postgres_password.txt')
|
def local_secret(filename, default):
|
||||||
values['POSTGRES_PASSWORD'] = values.get('POSTGRES_PASSWORD') or (password_file.read_text().strip() if password_file.exists() else secrets.token_hex(24))
|
path = Path('secrets') / filename
|
||||||
values['DATABASE_URL'] = values.get('DATABASE_URL') or f"postgres://{values.get('POSTGRES_USER', 'messenger')}:{values['POSTGRES_PASSWORD']}@postgres:5432/{values.get('POSTGRES_DB', 'messenger')}?sslmode=disable"
|
if not path.exists():
|
||||||
for key in ('POSTGRES_PASSWORD', 'DATABASE_URL'):
|
path.write_text(default + '\n')
|
||||||
lines = [line for line in lines if not line.startswith(key + '=')]
|
return path.read_text().strip()
|
||||||
lines.append(key + '=' + values[key])
|
|
||||||
for filename, key in [('postgres_password.txt', 'POSTGRES_PASSWORD'), ('database_url.txt', 'DATABASE_URL')]:
|
password = local_secret('postgres_password.txt', values.get('POSTGRES_PASSWORD') or secrets.token_hex(24))
|
||||||
p = Path('secrets') / filename
|
user = quote(values.get('POSTGRES_USER', 'messenger'), safe='')
|
||||||
if not p.exists():
|
database = quote(values.get('POSTGRES_DB', 'messenger'), safe='')
|
||||||
p.write_text(values[key])
|
dsn = f"postgres://{user}:{quote(password, safe='')}@postgres:5432/{database}?sslmode=disable"
|
||||||
env.write_text('\n'.join(lines) + '\n')
|
local_secret('database_url.txt', values.get('DATABASE_URL') or dsn)
|
||||||
|
local_secret('grafana_admin_password.txt', secrets.token_urlsafe(24))
|
||||||
env.chmod(0o600)
|
env.chmod(0o600)
|
||||||
PY
|
PY
|
||||||
./scripts/gen-s3-secrets.sh
|
./scripts/gen-s3-secrets.sh
|
||||||
chmod 644 secrets/*
|
chmod 644 secrets/postgres_password.txt secrets/database_url.txt secrets/grafana_admin_password.txt \
|
||||||
|
secrets/s3_config.json secrets/s3_api_access_key.txt secrets/s3_api_secret_key.txt \
|
||||||
|
secrets/s3_admin_access_key.txt secrets/s3_admin_secret_key.txt
|
||||||
echo "секреты готовы"
|
echo "секреты готовы"
|
||||||
|
|||||||
+21
-14
@@ -8,22 +8,26 @@ import sys
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
EVIDENCE = ROOT / "evidence"
|
||||||
|
LAB = json.loads((ROOT / "lab.json").read_text())["number"]
|
||||||
|
|
||||||
|
|
||||||
def run(*args):
|
def run(*args):
|
||||||
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
|
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
|
||||||
|
|
||||||
|
|
||||||
info = json.loads(run('docker', 'info', '--format', '{{json .}}'))
|
version, cpus, memory = run('docker', 'info', '--format', '{{.ServerVersion}} {{.NCPU}} {{.MemTotal}}').split()
|
||||||
ids = run('docker', 'compose', 'ps', '-q').splitlines()
|
ids = run('docker', 'compose', 'ps', '-q').splitlines()
|
||||||
|
inspected = json.loads(run('docker', 'inspect', *ids))
|
||||||
|
project = inspected[0]['Config']['Labels']['com.docker.compose.project']
|
||||||
containers = []
|
containers = []
|
||||||
for item in json.loads(run('docker', 'inspect', *ids)):
|
for item in inspected:
|
||||||
containers.append(dict(name=item['Name'], image=item['Config']['Image'],
|
containers.append(dict(name=item['Name'], image=item['Config']['Image'],
|
||||||
started_at=item['State']['StartedAt'], cpus=item['HostConfig']['NanoCpus']/1e9,
|
started_at=item['State']['StartedAt'], cpus=item['HostConfig']['NanoCpus']/1e9,
|
||||||
memory_bytes=item['HostConfig']['Memory'], volumes=[m['Name'] for m in item['Mounts'] if m['Type']=='volume']))
|
memory_bytes=item['HostConfig']['Memory'], volumes=[m['Name'] for m in item['Mounts'] if m['Type']=='volume']))
|
||||||
report = dict(date=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
report = dict(date=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||||
host_machine=platform.machine(), host_os=platform.platform(),
|
host_machine=platform.machine(), host_os=platform.platform(),
|
||||||
docker=dict(version=info['ServerVersion'], cpus=info['NCPU'], memory_bytes=info['MemTotal']),
|
docker=dict(version=version, cpus=int(cpus), memory_bytes=int(memory)),
|
||||||
go=run('go','version'), compose=run('docker','compose','version'),
|
go=run('go','version'), compose=run('docker','compose','version'),
|
||||||
image_runtime=run('docker','compose','exec','-T','worker','python3','-c',"import sys,PIL; print(sys.version.split()[0], 'Pillow', PIL.__version__)"),
|
image_runtime=run('docker','compose','exec','-T','worker','python3','-c',"import sys,PIL; print(sys.version.split()[0], 'Pillow', PIL.__version__)"),
|
||||||
containers=containers)
|
containers=containers)
|
||||||
@@ -34,21 +38,24 @@ def dataset():
|
|||||||
return json.loads(raw)
|
return json.loads(raw)
|
||||||
report['dataset_before']=dataset()
|
report['dataset_before']=dataset()
|
||||||
if '--load' in sys.argv:
|
if '--load' in sys.argv:
|
||||||
log=(ROOT/'evidence/lab5-load.txt').open('w')
|
log_path = EVIDENCE / f"lab{LAB}-load.txt"
|
||||||
load=subprocess.Popen([sys.executable,'tests/load.py','--duration','30','--concurrency','4','--output','evidence/lab5-load.json'],cwd=ROOT,stdout=log,stderr=subprocess.STDOUT)
|
load_path = EVIDENCE / f"lab{LAB}-load.json"
|
||||||
samples=[]
|
samples = []
|
||||||
while load.poll() is None:
|
with log_path.open('w') as log:
|
||||||
samples.append(dict(at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
load = subprocess.Popen([sys.executable, 'tests/load.py', '--duration', '30', '--concurrency', '4',
|
||||||
containers=[json.loads(line) for line in run('docker','stats','--no-stream','--format','{{json .}}',*ids).splitlines()]))
|
'--output', str(load_path)], cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
|
||||||
time.sleep(1)
|
while load.poll() is None:
|
||||||
log.close()
|
stats = run('docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids)
|
||||||
|
samples.append(dict(at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||||
|
containers=[json.loads(line) for line in stats.splitlines()]))
|
||||||
|
time.sleep(1)
|
||||||
if load.returncode:
|
if load.returncode:
|
||||||
raise SystemExit('load failed; see evidence/lab5-load.txt')
|
raise SystemExit(f'load failed; see {log_path}')
|
||||||
report['load_samples']=samples
|
report['load_samples']=samples
|
||||||
report['dataset_after']=dataset()
|
report['dataset_after']=dataset()
|
||||||
events=run('docker','events','--since','1h','--until','0s','--filter','type=container',
|
events=run('docker','events','--since','1h','--until','0s','--filter','type=container',
|
||||||
'--filter','label=com.docker.compose.project=mtusi2026lab5','--format','{{json .}}')
|
'--filter',f'label=com.docker.compose.project={project}','--format','{{json .}}')
|
||||||
report['lifecycle_events']=[dict(time=e['time'],action=e['Action'],name=e['Actor']['Attributes'].get('name'))
|
report['lifecycle_events']=[dict(time=e['time'],action=e['Action'],name=e['Actor']['Attributes'].get('name'))
|
||||||
for e in (json.loads(line) for line in events.splitlines()) if e['Action'] in ('start','stop','die','kill','restart')]
|
for e in (json.loads(line) for line in events.splitlines()) if e['Action'] in ('start','stop','die','kill','restart')]
|
||||||
(ROOT/'evidence/lab5-runtime.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
(EVIDENCE / f"lab{LAB}-runtime.json").write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||||
print('PASS sanitized runtime evidence saved')
|
print('PASS sanitized runtime evidence saved')
|
||||||
|
|||||||
@@ -0,0 +1,457 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Run the level 4 exercises on the local Compose project and save telemetry evidence."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import select
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from threading import Event
|
||||||
|
import time
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.parse import urlencode
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
from client import Client, check, run
|
||||||
|
|
||||||
|
|
||||||
|
def now():
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for(probe, description, timeout=60, interval=2):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
last_error = None
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
value = probe()
|
||||||
|
if value:
|
||||||
|
return value
|
||||||
|
except HTTPError as error:
|
||||||
|
if error.code not in (502, 503, 504):
|
||||||
|
raise
|
||||||
|
last_error = f"HTTP {error.code}"
|
||||||
|
except (URLError, TimeoutError) as error:
|
||||||
|
last_error = type(error).__name__
|
||||||
|
time.sleep(interval)
|
||||||
|
suffix = f" (last transport error: {last_error})" if last_error else ""
|
||||||
|
check(False, "timed out waiting for " + description + suffix)
|
||||||
|
|
||||||
|
|
||||||
|
def compose(*args):
|
||||||
|
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, timeout=60).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def start_only(service):
|
||||||
|
ids = compose("ps", "--all", "--quiet", service).splitlines()
|
||||||
|
check(bool(ids), "missing Compose container for " + service)
|
||||||
|
subprocess.run(["docker", "start", *ids], cwd=ROOT, check=True, capture_output=True, timeout=30)
|
||||||
|
|
||||||
|
|
||||||
|
def collector_started_at():
|
||||||
|
container = compose("ps", "-q", "otel-collector")
|
||||||
|
return subprocess.check_output(["docker", "inspect", "--format", "{{.State.StartedAt}}", container],
|
||||||
|
cwd=ROOT, text=True, timeout=10).strip()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def stopped(service):
|
||||||
|
compose("stop", "-t", "5", service)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
start_only(service)
|
||||||
|
|
||||||
|
|
||||||
|
def trace_headers():
|
||||||
|
trace_id, parent = uuid4().hex, uuid4().hex[:16]
|
||||||
|
return trace_id, parent, {"traceparent": f"00-{trace_id}-{parent}-01", "tracestate": "lab=probe"}
|
||||||
|
|
||||||
|
|
||||||
|
def attrs(items):
|
||||||
|
result = {}
|
||||||
|
for item in items:
|
||||||
|
kind, value = next(iter(item["value"].items()))
|
||||||
|
result[item["key"]] = int(value) if kind == "intValue" else value
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def span_id(value):
|
||||||
|
if not value or re.fullmatch(r"[0-9a-f]{16}", value):
|
||||||
|
return value
|
||||||
|
return base64.b64decode(value).hex()
|
||||||
|
|
||||||
|
|
||||||
|
class Grafana:
|
||||||
|
def __init__(self, base):
|
||||||
|
self.base = base.rstrip("/")
|
||||||
|
|
||||||
|
def get(self, path, **params):
|
||||||
|
url = self.base + path + ("?" + urlencode(params) if params else "")
|
||||||
|
with urlopen(Request(url, headers={"Accept": "application/json"}), timeout=8) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
def source(self, uid, path, **params):
|
||||||
|
return self.get(f"/api/datasources/proxy/uid/{uid}{path}", **params)
|
||||||
|
|
||||||
|
def scalar(self, query, optional=False):
|
||||||
|
result = self.source("prometheus", "/api/v1/query", query=query)["data"]["result"]
|
||||||
|
if not result and optional:
|
||||||
|
return None
|
||||||
|
check(len(result) == 1, "expected one Prometheus series for " + query)
|
||||||
|
value = float(result[0]["value"][1])
|
||||||
|
return value if math.isfinite(value) else None
|
||||||
|
|
||||||
|
def alert(self, name):
|
||||||
|
groups = self.source("prometheus", "/api/v1/rules", type="alert")["data"]["groups"]
|
||||||
|
rule = next(rule for group in groups for rule in group["rules"] if rule["name"] == name)
|
||||||
|
check(rule["health"] == "ok", "Prometheus error evaluating " + name)
|
||||||
|
return rule["state"]
|
||||||
|
|
||||||
|
def logs(self, trace_id):
|
||||||
|
data = self.source("loki", "/loki/api/v1/query_range",
|
||||||
|
query='{service_name=~"messenger-.*"} | trace_id="' + trace_id + '"',
|
||||||
|
since="15m", limit=100)
|
||||||
|
result = []
|
||||||
|
for stream in data["data"]["result"]:
|
||||||
|
for ts, event, *extra in stream["values"]:
|
||||||
|
labels = dict(stream["stream"])
|
||||||
|
for fields in extra:
|
||||||
|
labels.update(fields.get("structuredMetadata", fields))
|
||||||
|
result.append({"timestamp_unix_ns": ts, "event": event, **labels})
|
||||||
|
return result
|
||||||
|
|
||||||
|
def spans(self, trace_id):
|
||||||
|
try:
|
||||||
|
trace = self.source("tempo", "/api/traces/" + trace_id)
|
||||||
|
except HTTPError as error:
|
||||||
|
if error.code == 404:
|
||||||
|
return []
|
||||||
|
raise
|
||||||
|
result = []
|
||||||
|
for batch in trace.get("batches", trace.get("resourceSpans", [])):
|
||||||
|
resource = attrs(batch["resource"]["attributes"])
|
||||||
|
for scope in batch.get("scopeSpans", batch.get("instrumentationLibrarySpans", [])):
|
||||||
|
for s in scope["spans"]:
|
||||||
|
result.append({
|
||||||
|
"name": s["name"], "kind": s.get("kind"), "resource": resource,
|
||||||
|
"span_id": span_id(s["spanId"]), "parent_span_id": span_id(s.get("parentSpanId", "")),
|
||||||
|
"tracestate": s.get("traceState", ""), "status": s.get("status", {}),
|
||||||
|
"duration_ms": (int(s["endTimeUnixNano"]) - int(s["startTimeUnixNano"])) / 1e6,
|
||||||
|
"attributes": attrs(s.get("attributes", [])),
|
||||||
|
})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def check_private(actor, chat, evidence, *markers):
|
||||||
|
text = json.dumps(evidence, ensure_ascii=False)
|
||||||
|
for value in (actor["token"], actor["registration"]["password"], actor["id"], chat["id"], *markers):
|
||||||
|
check(value not in text, "synthetic private marker appeared in telemetry")
|
||||||
|
|
||||||
|
|
||||||
|
def verify_queue(c, g, actor, chat):
|
||||||
|
alert = "MessengerQueueLag"
|
||||||
|
upload_route = f"/api/v1/chats/{chat['id']}/attachments"
|
||||||
|
trace_id, client_parent, carrier = trace_headers()
|
||||||
|
filename = "private-" + uuid4().hex + ".png"
|
||||||
|
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||||
|
series = []
|
||||||
|
|
||||||
|
def sample():
|
||||||
|
data = {
|
||||||
|
"at": now(), "state": g.alert(alert), "depth": g.scalar("max(messenger_queue_depth)"),
|
||||||
|
"oldest_seconds": g.scalar("max(messenger_queue_oldest_age_seconds)"),
|
||||||
|
}
|
||||||
|
series.append(data)
|
||||||
|
return data
|
||||||
|
|
||||||
|
print("Останавливаем worker и проверяем возраст очереди", flush=True)
|
||||||
|
check(sample()["state"] == "inactive", "queue alert must start inactive")
|
||||||
|
with stopped("worker"):
|
||||||
|
stopped_at = now()
|
||||||
|
accepted = c.call("POST", upload_route + "?filename=" + filename, 202, actor=actor, raw=fixture,
|
||||||
|
headers={**carrier, "Content-Type": "image/png"}, schema="Attachment")
|
||||||
|
attachment = accepted["json"]
|
||||||
|
extra, _ = c.attachment(actor, chat)
|
||||||
|
wait_for(lambda: (state := sample())["state"] == "firing" and state["depth"] >= 2,
|
||||||
|
"queue alarm firing", timeout=55)
|
||||||
|
print("Алерт очереди firing. Проверяем retry при кратком отказе S3-прокси", flush=True)
|
||||||
|
with stopped("s3-proxy"):
|
||||||
|
start_only("worker")
|
||||||
|
wait_for(lambda: any(x["event"] == "attachment.attempt_failed" for x in g.logs(trace_id)),
|
||||||
|
"worker attempt failed in Loki", timeout=22, interval=0.5)
|
||||||
|
recovered_at = now()
|
||||||
|
wait_for(lambda: ready(c), "API readiness after S3 restart", timeout=35)
|
||||||
|
ready_one, ready_two = c.wait_ready(actor, attachment), c.wait_ready(actor, extra)
|
||||||
|
original = c.call("GET", f"/api/v1/attachments/{ready_one['id']}/content", actor=actor)
|
||||||
|
check(original["bytes"] == fixture, "original changed after retry")
|
||||||
|
wait_for(lambda: (state := sample())["state"] == "inactive" and state["depth"] == 0,
|
||||||
|
"queue alarm resolved")
|
||||||
|
spans = wait_for(lambda: (found := g.spans(trace_id)) and
|
||||||
|
any(x["name"] == "db.job.complete" for x in found) and found, "complete upload trace")
|
||||||
|
logs = wait_for(lambda: (found := g.logs(trace_id)) and any(x["event"] == "attachment.ready" for x in found)
|
||||||
|
and found, "worker completion log")
|
||||||
|
server = next(s for s in spans if s["kind"] in (2, "SPAN_KIND_SERVER"))
|
||||||
|
accept = next(s for s in spans if s["name"] == "db.attachment.accept")
|
||||||
|
check(server["parent_span_id"] == client_parent and accept["parent_span_id"] == server["span_id"],
|
||||||
|
"API trace lost client or acceptance parent")
|
||||||
|
producers = {s["attributes"]["job.attempt"]: s for s in spans if s["kind"] in (4, "SPAN_KIND_PRODUCER")}
|
||||||
|
consumers = {s["attributes"]["job.attempt"]: s for s in spans if s["kind"] in (5, "SPAN_KIND_CONSUMER")}
|
||||||
|
check(len(consumers) >= 2 and len(producers) >= 2, "retry missing in trace")
|
||||||
|
for attempt, consumer in consumers.items():
|
||||||
|
producer = producers[attempt]
|
||||||
|
check(producer["parent_span_id"] == accept["span_id"] and consumer["parent_span_id"] == producer["span_id"],
|
||||||
|
"Redis did not preserve producer/consumer linkage")
|
||||||
|
check(consumer["tracestate"] == carrier["tracestate"], "worker lost W3C tracestate")
|
||||||
|
check(consumers[min(consumers)]["attributes"]["job.outcome"] == "error", "first attempt should fail")
|
||||||
|
last = consumers[max(consumers)]
|
||||||
|
check(last["attributes"]["job.outcome"] == "success"
|
||||||
|
and any(s["name"] == "db.job.complete" and s["parent_span_id"] == last["span_id"] for s in spans)
|
||||||
|
and any(s["name"] == "s3.put_object" and s["parent_span_id"] == last["span_id"] for s in spans),
|
||||||
|
"successful retry must write S3 and commit DB in the same trace")
|
||||||
|
request_id = accepted["headers"]["X-Request-Id"]
|
||||||
|
check(any(x.get("request_id") == request_id and x.get("span_id") == server["span_id"] for x in logs)
|
||||||
|
and any(x["event"] == "attachment.ready" and x.get("span_id") == last["span_id"] for x in logs),
|
||||||
|
"logs lack request ID or matching span ID")
|
||||||
|
check_private(actor, chat, [spans, logs], filename, attachment["id"], base64.b64encode(fixture).decode())
|
||||||
|
return {"worker_stopped_at": stopped_at, "services_restored_at": recovered_at, "timeline": series,
|
||||||
|
"trace_id": trace_id, "request_id": request_id, "spans": spans, "logs": logs,
|
||||||
|
"durable_ready": [ready_one["status"], ready_two["status"]], "original_matches_fixture": True}
|
||||||
|
|
||||||
|
|
||||||
|
def ready(client):
|
||||||
|
try:
|
||||||
|
with urlopen(client.base + "/health/ready", timeout=3) as response:
|
||||||
|
return response.status == 200
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def verify_db(c, g, actor, chat, message_path):
|
||||||
|
alert = "MessengerHighErrorRate"
|
||||||
|
timeline = []
|
||||||
|
marker = "private-message-" + uuid4().hex
|
||||||
|
fired = Event()
|
||||||
|
stop = Event()
|
||||||
|
results = []
|
||||||
|
|
||||||
|
def write_messages():
|
||||||
|
while not stop.is_set():
|
||||||
|
trace_id, _, carrier = trace_headers()
|
||||||
|
reply = c.call("POST", message_path, [201, 500], actor=actor, body={"text": marker}, schema="Message",
|
||||||
|
headers={**carrier, "Idempotency-Key": uuid4().hex})
|
||||||
|
results.append({"status": reply["status"], "request_id": reply["headers"]["X-Request-Id"],
|
||||||
|
"trace_id": trace_id, "ms": round(1000 * reply["elapsed"], 2)})
|
||||||
|
stop.wait(0.4)
|
||||||
|
|
||||||
|
def sample():
|
||||||
|
data = {
|
||||||
|
"at": now(), "state": g.alert(alert),
|
||||||
|
"error_ratio_1m": g.scalar("messenger:api_errors:ratio1m", optional=True),
|
||||||
|
"lock_waiters": g.scalar("max(messenger_db_messages_lock_waiters)"),
|
||||||
|
}
|
||||||
|
timeline.append(data)
|
||||||
|
if data["state"] == "firing":
|
||||||
|
fired.set()
|
||||||
|
return data
|
||||||
|
|
||||||
|
print("Блокируем запись в messages и проверяем алерт 5xx", flush=True)
|
||||||
|
check(sample()["state"] == "inactive", "HTTP alert must start inactive")
|
||||||
|
lock_sql = "BEGIN; SET LOCAL lock_timeout='2s'; LOCK TABLE messages IN SHARE MODE;\n"
|
||||||
|
lock_sql += "SELECT 'lab6_lock_acquired'; SELECT pg_sleep(40); ROLLBACK;\n"
|
||||||
|
command = ["docker", "compose", "exec", "-T", "postgres", "sh", "-c",
|
||||||
|
'exec psql -XqAt -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"']
|
||||||
|
with subprocess.Popen(command, cwd=ROOT, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as lock:
|
||||||
|
lock.stdin.write(lock_sql)
|
||||||
|
lock.stdin.close()
|
||||||
|
check(select.select([lock.stdout], [], [], 15)[0] and lock.stdout.readline().strip() == "lab6_lock_acquired",
|
||||||
|
"could not acquire the bounded database lock")
|
||||||
|
locked_at = now()
|
||||||
|
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||||
|
writers = [pool.submit(write_messages) for _ in range(3)]
|
||||||
|
try:
|
||||||
|
while lock.poll() is None:
|
||||||
|
sample()
|
||||||
|
time.sleep(2)
|
||||||
|
check(lock.returncode == 0 and fired.is_set(), "HTTP alert did not fire during database degradation")
|
||||||
|
released_at = now()
|
||||||
|
check(c.message(actor, chat, marker)["status"] == 201, "message write did not recover")
|
||||||
|
wait_for(lambda: (state := sample())["state"] == "inactive" and state["lock_waiters"] == 0,
|
||||||
|
"HTTP alarm resolved", timeout=85)
|
||||||
|
finally:
|
||||||
|
stop.set()
|
||||||
|
for writer in writers:
|
||||||
|
writer.result()
|
||||||
|
failure = next(reply for reply in results if reply["status"] == 500)
|
||||||
|
spans = wait_for(lambda: g.spans(failure["trace_id"]), "failed write trace")
|
||||||
|
logs = wait_for(lambda: g.logs(failure["trace_id"]), "failed write log")
|
||||||
|
check(any(s["name"] == "db.query" and s["duration_ms"] > 3500
|
||||||
|
and s["attributes"].get("db.operation.name") == "INSERT"
|
||||||
|
and s["attributes"].get("error.type") == "deadline_exceeded" for s in spans),
|
||||||
|
"trace did not attribute the timeout to PostgreSQL INSERT")
|
||||||
|
check(max(row["lock_waiters"] for row in timeline) > 0 and
|
||||||
|
any(x.get("request_id") == failure["request_id"] for x in logs), "database or request correlation incomplete")
|
||||||
|
check_private(actor, chat, [spans, logs], marker)
|
||||||
|
return {"locked_at": locked_at, "released_at": released_at, "timeline": timeline, "failed_write": failure,
|
||||||
|
"spans": spans, "logs": logs, "writes_201": sum(x["status"] == 201 for x in results),
|
||||||
|
"writes_500": sum(x["status"] == 500 for x in results)}
|
||||||
|
|
||||||
|
|
||||||
|
def verify_loki(c, g, actor, chat, message_path):
|
||||||
|
def exporter(metric, optional=False):
|
||||||
|
return g.scalar(f'sum({{__name__=~"otelcol_exporter_{metric}(_total)?",exporter="otlphttp/loki"}})',
|
||||||
|
optional=optional)
|
||||||
|
|
||||||
|
def sample():
|
||||||
|
return {
|
||||||
|
"at": now(), "capacity": exporter("queue_capacity"), "queue": exporter("queue_size"),
|
||||||
|
"send_failed": exporter("send_failed_log_records", optional=True) or 0,
|
||||||
|
"enqueue_failed": exporter("enqueue_failed_log_records", optional=True) or 0,
|
||||||
|
"sent": exporter("sent_log_records"),
|
||||||
|
"accepted": g.scalar('sum({__name__=~"otelcol_receiver_accepted_log_records(_total)?"})'),
|
||||||
|
"rss_bytes": g.scalar('max({__name__=~"otelcol_process_memory_rss(_bytes)?",job="otel-collector"})'),
|
||||||
|
}
|
||||||
|
|
||||||
|
print("Останавливаем Loki и проверяем запись сообщений и буфер Collector", flush=True)
|
||||||
|
wait_for(lambda: exporter("queue_size") == 0, "initial empty log queue")
|
||||||
|
collector_start = collector_started_at()
|
||||||
|
timeline = [sample()]
|
||||||
|
total = 0
|
||||||
|
marker = "loki-outage-" + uuid4().hex
|
||||||
|
dropped_trace_id, _, drop_carrier = trace_headers()
|
||||||
|
with stopped("loki"):
|
||||||
|
stopped_at = now()
|
||||||
|
written = c.call("POST", message_path, 201, actor=actor, body={"text": marker}, schema="Message",
|
||||||
|
headers={**drop_carrier, "Idempotency-Key": uuid4().hex})["json"]
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
next_sample = time.monotonic()
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
c.message(actor, chat, "synthetic Loki outage load")
|
||||||
|
total += 1
|
||||||
|
if time.monotonic() >= next_sample:
|
||||||
|
timeline.append(sample())
|
||||||
|
next_sample = time.monotonic() + 3
|
||||||
|
time.sleep(0.12)
|
||||||
|
timeline.append(sample())
|
||||||
|
restarted_at = now()
|
||||||
|
page = c.call("GET", message_path + "?limit=100", actor=actor, schema="MessagePage")["json"]
|
||||||
|
check(any(msg["id"] == written["id"] for msg in page["items"]), "message written during Loki outage disappeared")
|
||||||
|
|
||||||
|
wait_for(lambda: g.logs(dropped_trace_id) is not None, "Loki query endpoint", timeout=70)
|
||||||
|
wait_for(lambda: exporter("queue_size") == 0, "log queue drain", timeout=50)
|
||||||
|
trace_id, _, carrier = trace_headers()
|
||||||
|
probe = c.call("POST", message_path, 201, actor=actor, body={"text": marker},
|
||||||
|
schema="Message", headers={**carrier, "Idempotency-Key": uuid4().hex})
|
||||||
|
wait_for(lambda: g.logs(trace_id), "post-outage logs", timeout=35)
|
||||||
|
wait_for(lambda: exporter("sent_log_records") > timeline[-1]["sent"], "post-outage Prometheus scrape")
|
||||||
|
timeline.append(sample())
|
||||||
|
before, after = timeline[0], timeline[-1]
|
||||||
|
estimated_missing = round((after["accepted"] - before["accepted"]) - (after["sent"] - before["sent"]))
|
||||||
|
check(all(0 <= x["queue"] <= x["capacity"] == 8 for x in timeline), "collector queue exceeded its configured bound")
|
||||||
|
check(max(s["rss_bytes"] for s in timeline) < 256 * 1024**2, "collector RSS exceeded its budget")
|
||||||
|
check(collector_started_at() == collector_start, "collector restarted during the outage")
|
||||||
|
check(estimated_missing > 0 and not g.logs(dropped_trace_id) and g.spans(dropped_trace_id),
|
||||||
|
"collector log loss during the outage was not measurable")
|
||||||
|
timeline_summary = {"writes_201_during_outage": total + 1, "persisted_during_outage": True,
|
||||||
|
"probe_201_after_recovery": probe["status"], "resumed_trace_id": trace_id,
|
||||||
|
"dropped_log_trace_id": dropped_trace_id, "estimated_lost_log_records": estimated_missing,
|
||||||
|
"collector_started_at": collector_start}
|
||||||
|
return {"stopped_at": stopped_at, "restarted_at": restarted_at, "timeline": timeline, **timeline_summary}
|
||||||
|
|
||||||
|
|
||||||
|
def verify_history(g, trace_id):
|
||||||
|
print("Проверяем, что Loki, Prometheus и Tempo сохранили историю", flush=True)
|
||||||
|
check(bool(g.logs(trace_id)), "logs written before the Loki restart were lost")
|
||||||
|
compose("restart", "prometheus", "tempo")
|
||||||
|
|
||||||
|
def history():
|
||||||
|
try:
|
||||||
|
alerts = g.source("prometheus", "/api/v1/query",
|
||||||
|
query='max_over_time(ALERTS{alertstate="firing"}[15m])')["data"]["result"]
|
||||||
|
names = sorted(row["metric"]["alertname"] for row in alerts)
|
||||||
|
traces = g.spans(trace_id)
|
||||||
|
if {"MessengerHighErrorRate", "MessengerQueueLag"}.issubset(names) and traces:
|
||||||
|
return {"retained_trace_id": trace_id, "retained_spans": len(traces), "retained_alerts": names,
|
||||||
|
"retained_logs": len(g.logs(trace_id))}
|
||||||
|
return None
|
||||||
|
except HTTPError as error:
|
||||||
|
if error.code in (502, 503):
|
||||||
|
return None
|
||||||
|
raise
|
||||||
|
|
||||||
|
return wait_for(history, "telemetry history after storage restart", timeout=70)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_metrics(g):
|
||||||
|
required = {
|
||||||
|
"messenger_http_requests_total", "messenger_http_request_duration_seconds_bucket",
|
||||||
|
"messenger_job_attempts_total", "messenger_job_processing_duration_seconds_bucket",
|
||||||
|
"messenger_attachment_time_to_ready_seconds_bucket", "messenger_queue_depth",
|
||||||
|
"messenger_queue_oldest_age_seconds", "messenger_db_pool_used", "messenger_db_pool_waiting",
|
||||||
|
"messenger_db_pool_capacity", "messenger_worker_busy", "messenger_worker_capacity",
|
||||||
|
"messenger_process_cpu_time_seconds_total", "messenger_process_memory_rss_bytes",
|
||||||
|
}
|
||||||
|
series = g.source("prometheus", "/api/v1/series", **{"match[]": '{__name__=~"messenger_.+"}'})["data"]
|
||||||
|
check(required.issubset({entry["__name__"] for entry in series}), "missing dashboard metric series")
|
||||||
|
forbidden = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "filename", "url", "text"}
|
||||||
|
check(all(not forbidden.intersection(entry) for entry in series), "private or high-cardinality metric label")
|
||||||
|
requests = [entry for entry in series if entry["__name__"] == "messenger_http_requests_total"]
|
||||||
|
instances = {entry["service_instance_id"] for entry in requests
|
||||||
|
if entry.get("service_name") == "messenger-api" and entry.get("deployment_environment_name") == "lab"}
|
||||||
|
check(len(instances) >= 2, "HTTP metric series should cover at least two API replicas")
|
||||||
|
values = {}
|
||||||
|
metrics = {
|
||||||
|
"http": "messenger_http_request_duration_seconds_bucket",
|
||||||
|
"worker": "messenger_job_processing_duration_seconds_bucket",
|
||||||
|
"time_to_ready": "messenger_attachment_time_to_ready_seconds_bucket",
|
||||||
|
}
|
||||||
|
for name, metric in metrics.items():
|
||||||
|
values[name] = {}
|
||||||
|
for q in (0.5, 0.95, 0.99):
|
||||||
|
value = g.scalar(f"histogram_quantile({q}, sum by (le) (rate({metric}[10m])))")
|
||||||
|
check(value is not None, "missing percentile for " + metric)
|
||||||
|
values[name][f"p{int(100 * q)}"] = value
|
||||||
|
return {"prometheus_series": len(series), "api_instances": sorted(instances), "percentile_seconds": values,
|
||||||
|
"sli_ratio30m": g.scalar("messenger:api_availability:ratio30m")}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||||
|
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
||||||
|
parser.add_argument("--output", default=str(ROOT / "evidence/lab6-observability.json"))
|
||||||
|
args = parser.parse_args()
|
||||||
|
c, g = Client(args.base_url), Grafana(args.grafana_url)
|
||||||
|
dashboard = g.get("/api/dashboards/uid/messenger-lab6")["dashboard"]
|
||||||
|
wait_for(lambda: g.scalar("max(messenger_queue_depth)", optional=True) is not None,
|
||||||
|
"queue metrics in Prometheus")
|
||||||
|
actor, _, _, chat = c.bootstrap()
|
||||||
|
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||||
|
queue = verify_queue(c, g, actor, chat)
|
||||||
|
db = verify_db(c, g, actor, chat, path)
|
||||||
|
outage_chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
|
||||||
|
body={"title": "Loki outage", "member_ids": [actor["id"]]})["json"]
|
||||||
|
loki = verify_loki(c, g, actor, outage_chat, f"/api/v1/chats/{outage_chat['id']}/messages")
|
||||||
|
metrics = verify_metrics(g)
|
||||||
|
history = verify_history(g, queue["trace_id"])
|
||||||
|
summary = {"dashboard": dashboard["title"], "panels": len(dashboard["panels"]), "at": now(),
|
||||||
|
"queue_and_retry": queue, "postgres_lock": db, "loki_outage": loki, "metrics": metrics,
|
||||||
|
"storage_history": history}
|
||||||
|
output = Path(args.output)
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
output.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
print(f"PASS alerts, retry, log correlation and bounded Collector queue: {output}", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(main)
|
||||||
Reference in New Issue
Block a user