forked from mtusi2026/mtusi2026lab7
54 lines
5.8 KiB
Markdown
54 lines
5.8 KiB
Markdown
# Схема сигналов v1
|
||
|
||
SDK: OpenTelemetry Go traces/metrics **1.47.0**, logs API/SDK **1.47.0**, log exporter **0.23.0**. Resource schema URL — OTel semantic conventions **1.37.0**; прикладные имена и labels ниже зафиксированы собственной схемой `mtusi-messenger/telemetry-v1`.
|
||
|
||
Resources: `service.name` = messenger-api / messenger-worker / messenger-dispatcher; `service.version=lab6-v1` (версия перенесённой business instrumentation; deployment lab7 использует TLS), `service.instance.id` = api-1/api-2/worker-1/dispatcher-1, `deployment.environment.name=lab`. Collector превращает resource attrs в Prometheus labels, например service_name.
|
||
|
||
| Prometheus metric | Тип, единица | Labels |
|
||
|---|---|---|
|
||
| messenger_http_requests_total | counter, requests | method, route template, status_class |
|
||
| messenger_http_duration_seconds_bucket/count/sum | histogram, seconds | те же |
|
||
| messenger_jobs_processed_total | counter, attempts | job_type, outcome |
|
||
| messenger_job_duration_seconds_bucket/count/sum | histogram, seconds | job_type, outcome |
|
||
| messenger_time_to_ready_seconds_bucket/count/sum | histogram, seconds | job_type |
|
||
| messenger_queue_depth | gauge, jobs | queue; только dispatcher |
|
||
| messenger_queue_oldest_age_seconds | gauge, seconds | queue; только dispatcher |
|
||
| messenger_db_pool_used/idle/waiting/capacity | gauge, connections/acquires | resource instance |
|
||
| messenger_db_pool_acquire_wait_total | counter, empty pool acquires | resource instance |
|
||
| messenger_db_pool_acquire_wait_duration_seconds_total | counter, cumulative seconds | resource instance |
|
||
| messenger_worker_busy/capacity | gauge, attempts/slots | worker instance |
|
||
| messenger_process_cpu_seconds_total | counter, Go process CPU seconds | instance |
|
||
| messenger_container_cpu_seconds_total | counter, cgroup CPU seconds including decoder | instance |
|
||
| messenger_process_memory_bytes | gauge, Go runtime reserved memory (Sys), не RSS | instance |
|
||
| messenger_container_memory_bytes/limit_bytes | gauge, cgroup bytes | instance |
|
||
| messenger_process_last_observed_seconds | gauge, Unix timestamp | instance |
|
||
| messenger_db_available | gauge, 0/1 | dispatcher |
|
||
| messenger_telemetry_export_errors | gauge, cumulative SDK export errors | instance |
|
||
|
||
`waiting` — незавершённые Acquire; EmptyAcquire counter показывает обращения к пустому пулу. Busy/capacity — текущая занятость обработчиков, а не CPU%. E2E время измерено от created_at job в транзакции durable acceptance до COMMIT ready, включает queue wait и retry. Replay использует исходное время принятия.
|
||
|
||
Percentiles вычисляются объединением histogram buckets реплик:
|
||
|
||
```promql
|
||
histogram_quantile(0.95,
|
||
sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name="messenger-api",route!~"/health/.*"}[1m])))
|
||
```
|
||
|
||
p50 и p99 используют 0.50 и 0.99. Единицы всех duration panels — секунды. Суммируются buckets, не percentiles отдельных реплик. Полные исполняемые запросы находятся в `grafana/dashboards/messenger.json`.
|
||
|
||
## Логи и трассы
|
||
|
||
API log event `http.request`: timestamp, severity, service.name, method, route template, status, duration_ms, request_id, trace_id, span_id. Worker — `job.started`, `job.completed`; dispatcher — `job.published`.
|
||
|
||
Технические request_id/job_id допустимы только в логах/трассах для корреляции синтетических работ. В labels метрик они отсутствуют. SQL text/args, URL/query, filename, headers Authorization, пароли, токены, текст сообщения и содержимое файлов не записываются.
|
||
|
||
HTTP server span принимает W3C traceparent/tracestate. Upload транзакционно сохраняет их в job. Producer span публикует свой контекст в разрешённых полях JSON брокера; consumer span извлекает его как parent. Повторы образуют новые producer/consumer ветки того же trace. S3, Redis sessions, DB acquire/query/commit и image.process имеют реальные дочерние spans.
|
||
|
||
Log body — структурный JSON, дополнительно отправляемый OTLP Log SDK с trace/span context. В Grafana Loki TraceID derived field открывает Tempo; поиск по trace_id показывает связанные события. Заголовок X-Trace-Id добавлен для диагностики; X-Request-Id и бизнес-контракт сохранены.
|
||
|
||
## Буферизация
|
||
|
||
SDK: batch queue 256, batch 64, export interval 500 ms, exporter timeout 2 s, retry SDK выключен; metrics interval 2 s. Collector: memory limiter 128 MiB со spike 32 MiB, hard limit контейнера 256 MiB; batch size 64/max128; по 32 batches и 2 consumers для traces/logs, неблокирующее переполнение, retry deadline 5 s. Метрики предоставляются ограниченным набором series на pull endpoint Collector; Prometheus хранит историю в volume. Retention storage — 24 h.
|
||
|
||
При отказе telemetry допускаются потери signals. Ошибки SDK учитываются отдельно; Collector показывает failed exports/queue, а финальные drops записывает с dropped_items. Business transaction от успешности экспорта не зависит.
|