feat: add OpenTelemetry SDK, collector and telemetry stores

Collector (contrib), Prometheus, Loki, Tempo and Grafana with provisioning
from git; SDK in API and worker with level 3 metrics, traces and logs
carrying trace_id/span_id; telemetry off by default outside the stand;
broker healthcheck runs as the broker user so a fresh stand starts once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-11 10:19:50 +03:00
co-authored by Claude Opus 5.5
parent 9b35c256b7
commit a4497e3f32
62 changed files with 6175 additions and 214 deletions
+70
View File
@@ -0,0 +1,70 @@
# OTel Collector contrib 0.164.0 (design change otel-telemetry, решения 1, 3,
# 14): получатель, обработчик и экспортёр, не хранилище. Три pipeline — каждый
# до своего хранилища: метрики — scrape Prometheus с экспортёра prometheus,
# логи — Loki (родной OTLP), трассы — Tempo. Расширений нет (pprof, zpages,
# health_check образа не берутся). Порты наружу не публикуются: OTLP
# слушает сеть приложения, :8888 и :8889 забирает Prometheus в сети
# telemetry.
receivers:
otlp:
protocols:
# только OTLP/HTTP: SDK приложения отправляет protobuf по HTTP
http:
endpoint: 0.0.0.0:4318
processors:
# предел памяти Collector: при 200 МиБ отказ приёма (SDK получает ошибку и
# теряет пакет), всплеск — 40 МиБ; GOMEMLIMIT контейнера — 160 МиБ
memory_limiter:
check_interval: 1s
limit_mib: 200
spike_limit_mib: 40
# пакеты до хранилищ: не больше 1024 элементов или раз в секунду
batch:
send_batch_size: 1024
timeout: 1s
exporters:
# метрики приложения для scrape Prometheus (honor_labels): job =
# service.name, instance = service.instance.id, остальной ресурс —
# target_info; ряды остановленной реплики уходят через 5 мин
prometheus:
endpoint: 0.0.0.0:8889
translation_strategy: UnderscoreEscapingWithSuffixes
metric_expiration: 5m
resource_to_telemetry_conversion:
enabled: false
# sending_queue и retry_on_failure — по умолчанию: явные пределы и учёт
# потерь — change 3 (уровень 4)
otlp_http/loki:
endpoint: http://loki:3100/otlp
otlp_http/tempo:
endpoint: http://tempo:4318
service:
telemetry:
logs:
level: info
encoding: json
# собственные метрики Collector — для Prometheus (жив ли конвейер)
metrics:
level: normal
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: [otlp_http/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/tempo]
+17
View File
@@ -0,0 +1,17 @@
# Провайдер dashboard из файлов (design change otel-telemetry, решение 16):
# JSON из git, правки из интерфейса не сохраняются, удалить нельзя. Каталог
# /etc/grafana/dashboards — bind mount файла dashboard (только чтение).
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
folderUid: messenger
type: file
disableDeletion: true
allowUiUpdates: false
updateIntervalSeconds: 60
options:
path: /etc/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,238 @@
{
"uid": "messenger-overview",
"title": "Messenger overview",
"description": "Level 3 signals of contracts/observability.md: API RPS, errors and duration, worker jobs and duration, logs and traces (design change otel-telemetry, decision 16). Provisioned from git, UI changes are not saved.",
"tags": ["messenger", "lab6"],
"timezone": "utc",
"editable": false,
"graphTooltip": 1,
"schemaVersion": 39,
"version": 1,
"refresh": "30s",
"time": {"from": "now-1h", "to": "now"},
"annotations": {"list": []},
"templating": {"list": []},
"links": [],
"panels": [
{
"id": 1,
"type": "row",
"title": "API (messenger-api)",
"collapsed": false,
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 0},
"panels": []
},
{
"id": 2,
"type": "timeseries",
"title": "Requests per second by route and status class",
"description": "Count of the http.server.request.duration histogram, all replicas; health is not recorded.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 1},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (http_route, status_class) (label_replace(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]), \"status_class\", \"${1}xx\", \"http_response_status_code\", \"([0-9])..\"))",
"legendFormat": "{{http_route}} {{status_class}}"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "Error ratio (5xx of all requests)",
"description": "Numerator: API responses 5xx; denominator: all recorded requests. 4xx are shown separately; responses generated by the load balancer are not in API metrics.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 6, "x": 12, "y": 1},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\",http_response_status_code=~\"5..\"}[5m])) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]))",
"legendFormat": "5xx ratio"
}
]
},
{
"id": 4,
"type": "timeseries",
"title": "Client errors ratio (4xx of all requests)",
"description": "Wrong password, foreign chat, validation: not part of the error ratio.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 6, "x": 18, "y": 1},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\",http_response_status_code=~\"4..\"}[5m])) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]))",
"legendFormat": "4xx ratio"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Request duration p50 and p95 (all replicas)",
"description": "Quantiles from the sum of buckets of all replicas, not averages of replicas.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 9},
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "p95"
}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Request duration p95 by route",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 9},
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "{{http_route}}"
}
]
},
{
"id": 7,
"type": "row",
"title": "Worker (messenger-worker)",
"collapsed": false,
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 17},
"panels": []
},
{
"id": 8,
"type": "timeseries",
"title": "Jobs per second by outcome",
"description": "Count of messenger.job.duration by messenger.job.outcome. Successful: ready; failed: failed, retry, requeued, dropped, error; skipped is neither.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 18},
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"options": {"legend": {"displayMode": "table", "placement": "bottom", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (messenger_job_outcome) (rate(messenger_job_duration_seconds_count{job=\"messenger-worker\"}[5m]))",
"legendFormat": "{{messenger_job_outcome}}"
}
]
},
{
"id": 9,
"type": "timeseries",
"title": "Successful and failed jobs per second",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 18},
"fieldConfig": {"defaults": {"unit": "ops", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(rate(messenger_job_duration_seconds_count{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m]))",
"legendFormat": "successful (ready)"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(rate(messenger_job_duration_seconds_count{job=\"messenger-worker\",messenger_job_outcome=~\"failed|retry|requeued|dropped|error\"}[5m]))",
"legendFormat": "failed"
}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Job duration p50 and p95 (ready)",
"description": "Handling of one delivery after the concurrency slot, outcome ready.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 18},
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m])))",
"legendFormat": "p95"
}
]
},
{
"id": 11,
"type": "row",
"title": "Logs and traces",
"collapsed": false,
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 26},
"panels": []
},
{
"id": 12,
"type": "logs",
"title": "API and worker logs",
"description": "Records of stdout exported through the Collector; trace_id opens the trace in Tempo.",
"datasource": {"type": "loki", "uid": "loki"},
"gridPos": {"h": 12, "w": 24, "x": 0, "y": 27},
"options": {"showTime": true, "showLabels": false, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true, "dedupStrategy": "none", "prettifyLogMessage": false},
"targets": [
{
"refId": "A",
"datasource": {"type": "loki", "uid": "loki"},
"expr": "{service_name=~\"messenger-.*\"}",
"queryType": "range"
}
]
},
{
"id": 13,
"type": "table",
"title": "Recent traces",
"description": "TraceQL search of API requests and worker deliveries; a trace opens with links to its logs.",
"datasource": {"type": "tempo", "uid": "tempo"},
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 39},
"options": {"showHeader": true},
"targets": [
{
"refId": "A",
"datasource": {"type": "tempo", "uid": "tempo"},
"queryType": "traceql",
"query": "{ resource.service.name =~ \"messenger-.*\" }",
"limit": 20,
"tableType": "traces"
}
]
}
]
}
+60
View File
@@ -0,0 +1,60 @@
# Источники Grafana (design change otel-telemetry, решение 16): постоянные uid,
# на которые ссылается dashboard; правка в интерфейсе запрещена. Переходы:
# запись Loki → трасса Tempo по полю trace_id (structured metadata OTLP), span
# Tempo → записи Loki той же трассы.
apiVersion: 1
prune: true
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
httpMethod: POST
timeInterval: 15s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
maxLines: 1000
derivedFields:
- name: trace_id
datasourceUid: tempo
# поле записи OTLP, а не текст строки
matcherType: label
matcherRegex: trace_id
url: "$${__value.raw}"
urlDisplayLabel: Trace
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-5m"
spanEndTimeShift: "5m"
filterByTraceID: false
filterBySpanID: false
customQuery: true
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: false
search:
hide: false
lokiSearch:
datasourceUid: loki
+46
View File
@@ -0,0 +1,46 @@
# Loki 3.7.9 — хранилище логов (design change otel-telemetry, решение 15).
# Монолит из конфигурации образа (/etc/loki/local-config.yaml): filesystem,
# inmemory ring, schema v13 tsdb; плюс срок хранения 7 суток, compactor и без
# отчётов об использовании. Приём — родной OTLP (/otlp) от Collector, метки
# потока по умолчанию — service_name, service_instance_id,
# deployment_environment_name; поля записи — structured metadata. Порт не
# публикуется: Collector и Grafana ходят в сети telemetry.
auth_enabled: false
server:
http_listen_port: 3100
log_level: info
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2020-10-24
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
# удаление данных старше срока делает compactor
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
limits_config:
retention_period: 168h
analytics:
reporting_enabled: false
+30
View File
@@ -0,0 +1,30 @@
# Prometheus v3.15.1 — хранилище метрик (design change otel-telemetry,
# решения 3 и 15). Метрики приложения — scrape экспортёра prometheus
# Collector (honor_labels: job = service.name, instance = service.instance.id
# из OTLP), плюс собственные метрики Collector, Loki, Tempo и самого
# Prometheus: по ним видно, жив ли конвейер. Срок и предел объёма хранения,
# путь данных — флаги команды в docker-compose.yml. Приёмников remote write и
# OTLP, admin API и lifecycle нет; порт не публикуется.
global:
scrape_interval: 15s
scrape_timeout: 10s
evaluation_interval: 15s
scrape_configs:
# метрики API и worker, пришедшие в Collector по OTLP
- job_name: otel-collector-exporter
honor_labels: true
static_configs:
- targets: ["otel-collector:8889"]
- job_name: otel-collector
static_configs:
- targets: ["otel-collector:8888"]
- job_name: loki
static_configs:
- targets: ["loki:3100"]
- job_name: tempo
static_configs:
- targets: ["tempo:3200"]
- job_name: prometheus
static_configs:
- targets: ["127.0.0.1:9090"]
+41
View File
@@ -0,0 +1,41 @@
# Tempo 3.1.1 — хранилище трасс (design change otel-telemetry, решение 15).
# Монолит (-target=all) с локальным хранилищем, без Kafka, metrics-generator и
# MCP. Приём — OTLP/HTTP от Collector на :4318, запросы Grafana — :3200; оба
# порта только в сети telemetry. Блоки и WAL — volume tempo_data
# (/var/tempo), срок хранения блоков — 7 суток.
stream_over_http_enabled: true
server:
http_listen_port: 3200
log_level: info
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
# срок хранения блоков. В Tempo 3.x задания удаления ставит backend-scheduler
# (retention provider), выполняет backend-worker; у обоих свой ключ
# block_retention (по умолчанию 336h), поэтому оба — 7 суток
backend_scheduler:
provider:
compaction:
compaction:
block_retention: 168h
backend_worker:
compaction:
block_retention: 168h
usage_report:
reporting_enabled: false