ЛР7: перенести минимум lab6 в приложение (API, worker, OTel)

- бизнес-API без изменений контракта; транспорт теперь HTTPS за mTLS-relay
- retry задачи переопубликовывается через outbox (в lab6 задача после
  ошибки оставалась в queued навсегда); trace context сохраняется в
  outbox.headers, поэтому API -> broker -> worker остаётся одной трассой
- структурные JSON-логи: trace_id/span_id в теле строки (SDK игнорирует
  formatter, поэтому добавлен JsonLoggingHandler)
- закрыты дефекты lab6: закреплён uid datasource в dashboard, убрана
  зависимость от Valkey (сессии и rate limit - в PostgreSQL)
- метрики/логи/трассы уходят в Collector по OTLP с клиентским сертификатом

Co-Authored-By: O3 Agent Claude <noreply@ozon.ru>
This commit is contained in:
2026-11-27 19:58:21 +03:00
co-authored by O3 Agent Claude
parent 20afc2c790
commit 23ac69428e
45 changed files with 3961 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
groups:
- name: messenger-api
interval: 15s
rules:
# Доля 5xx среди бизнес-запросов (health исключён) > 5% за 2 минуты.
- alert: ApiHighErrorRate
expr: |
(
sum(rate(http_server_duration_milliseconds_count{
http_status_code=~"5..",
http_target!~"/health/.*"
}[2m]))
/
sum(rate(http_server_duration_milliseconds_count{
http_target!~"/health/.*"
}[2m]))
) > 0.05
for: 2m
labels:
severity: warning
annotations:
summary: "API error rate > 5% за 2 минуты"
description: "5xx доля бизнес-запросов превысила 5% в течение 2 минут."
runbook: "Проверить /api/v1 logs в Loki по trace_id из ошибки; проверить health БД/S3/broker."
- alert: QueueLagHigh
expr: messenger_queue_oldest_job_age_seconds > 60
for: 2m
labels:
severity: warning
annotations:
summary: "Очередь обработки отстаёт > 60s"
description: "Самая старая задача в queued старше 60 секунд."
runbook: "Проверить worker (docker compose ps worker, logs worker); проверить RabbitMQ; проверить S3/DB latency."
- alert: QueueLagCritical
expr: messenger_queue_oldest_job_age_seconds > 300
for: 1m
labels:
severity: critical
annotations:
summary: "Очередь обработки отстаёт > 5 минут"
description: "Обработка не продвигается; возможен отказ worker."
runbook: "Остановить worker → проверить логи; проверить RabbitMQ; replay failed."
+431
View File
@@ -0,0 +1,431 @@
{
"annotations": {
"list": []
},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"links": [],
"panels": [
{
"type": "row",
"title": "API HTTP",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 0
},
"collapsed": false,
"panels": []
},
{
"type": "timeseries",
"title": "RPS по route template",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 1
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "reqps",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"targets": [
{
"expr": "sum by (http_target) (rate(http_server_duration_milliseconds_count{http_target!~\"/health/.*\"}[1m]))",
"legendFormat": "{{http_target}}"
}
]
},
{
"type": "timeseries",
"title": "Error ratio (5xx / всё, health исключён)",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 1
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"targets": [
{
"expr": "(sum(rate(http_server_duration_milliseconds_count{http_status_code=~\"5..\",http_target!~\"/health/.*\"}[2m])) or vector(0)) / sum(rate(http_server_duration_milliseconds_count{http_target!~\"/health/.*\"}[2m]))",
"legendFormat": "5xx ratio"
}
]
},
{
"type": "timeseries",
"title": "Latency p50/p95/p99 (API, ms)",
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 9
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "ms",
"custom": {
"drawStyle": "line",
"fillOpacity": 0
}
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))",
"legendFormat": "p50"
},
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))",
"legendFormat": "p95"
},
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))",
"legendFormat": "p99"
}
]
},
{
"type": "row",
"title": "Worker / Queue",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 17
},
"collapsed": false,
"panels": []
},
{
"type": "timeseries",
"title": "Jobs по outcome (rate, 1m)",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 18
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "ops",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"targets": [
{
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"type": "timeseries",
"title": "Job processing duration p50/p95/p99 (s)",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 18
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 0
}
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
},
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))",
"legendFormat": "p99"
}
]
},
{
"type": "timeseries",
"title": "Queue depth (queued)",
"gridPos": {
"h": 8,
"w": 8,
"x": 0,
"y": 26
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"targets": [
{
"expr": "sum(messenger_queue_depth)",
"legendFormat": "depth"
}
]
},
{
"type": "timeseries",
"title": "Oldest job age (s)",
"gridPos": {
"h": 8,
"w": 8,
"x": 8,
"y": 26
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "yellow",
"value": 60
},
{
"color": "red",
"value": 300
}
]
}
},
"overrides": []
},
"targets": [
{
"expr": "max(messenger_queue_oldest_job_age_seconds)",
"legendFormat": "oldest age"
}
]
},
{
"type": "timeseries",
"title": "Time to ready p50/p95 (s)",
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 26
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"drawStyle": "line",
"fillOpacity": 0
}
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95"
}
]
},
{
"type": "row",
"title": "Saturation",
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 34
},
"collapsed": false,
"panels": []
},
{
"type": "timeseries",
"title": "Worker busy slots (capacity 2)",
"gridPos": {
"h": 8,
"w": 8,
"x": 0,
"y": 35
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
},
"max": 2
},
"overrides": []
},
"targets": [
{
"expr": "sum(messenger_worker_busy)",
"legendFormat": "busy"
}
]
},
{
"type": "timeseries",
"title": "DB pool (available / waiting)",
"gridPos": {
"h": 8,
"w": 8,
"x": 8,
"y": 35
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"targets": [
{
"expr": "sum by (state) (messenger_db_pool)",
"legendFormat": "{{state}}"
}
]
},
{
"type": "timeseries",
"title": "Active HTTP requests",
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 35
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"drawStyle": "line",
"fillOpacity": 10
}
},
"overrides": []
},
"targets": [
{
"expr": "sum(http_server_active_requests)",
"legendFormat": "active"
}
]
}
],
"refresh": "10s",
"schemaVersion": 39,
"tags": [
"messenger",
"lab7"
],
"templating": {
"list": []
},
"time": {
"from": "now-15m",
"to": "now"
},
"timezone": "browser",
"title": "Messenger — lab7",
"uid": "messenger-lab7"
}
@@ -0,0 +1,12 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,38 @@
apiVersion: 1
# Все источники — по HTTPS с проверкой сервера. CA стенда добавлен в trust
# через SSL_CERT_FILE (см. compose.yaml, сервис grafana).
# uid закреплены явно: dashboard не должен зависеть от случайного uid Grafana.
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
jsonData:
timeInterval: 10s
tlsSkipVerify: false
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
jsonData:
derivedFields:
# Логи — JSON: trace_id лежит в теле строки.
- datasourceUid: tempo
matcherRegex: '"trace_id":\s*"([0-9a-f]{16,32})"'
name: TraceID
url: "$${__value.raw}"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
serviceMap:
datasourceUid: prometheus
+57
View File
@@ -0,0 +1,57 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
http_tls_config:
cert_file: /run/secrets/loki_crt
key_file: /run/secrets/loki_key
min_version: TLS12
common:
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
instance_addr: 127.0.0.1
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 24h
reject_old_samples: false
# Явная карта OTLP resource attributes → labels/structured metadata.
# service.name становится индексной меткой service_name (используется в
# Grafana и в student-tests).
otlp_config:
resource_attributes:
attributes_config:
- action: index_label
attributes:
- service.name
- action: structured_metadata
attributes:
- service.namespace
- service.version
- service.instance.id
- deployment.environment.name
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
+70
View File
@@ -0,0 +1,70 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
# TLS обязателен: даже внутри стенда OTLP не принимается plaintext.
# Identity клиента (CN=messenger-api|messenger-worker) проверяет OTLP-ingress
# (nginx :4318) — Collector доступен только из этой сети.
tls:
cert_file: /run/secrets/collector_crt
key_file: /run/secrets/collector_key
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /run/secrets/collector_crt
key_file: /run/secrets/collector_key
processors:
memory_limiter:
check_interval: 1s
limit_mib: 200
spike_limit_mib: 50
batch:
timeout: 5s
send_batch_size: 1024
attributes/scrub:
actions:
- key: http.request.header.authorization
action: delete
- key: http.request.header.cookie
action: delete
- key: http.request.header.x-api-key
action: delete
- key: db.connection_string
action: delete
exporters:
prometheus:
endpoint: 0.0.0.0:8889
tls:
cert_file: /run/secrets/collector_crt
key_file: /run/secrets/collector_key
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls:
ca_file: /run/secrets/ca_servers
otlp/tempo:
endpoint: tempo:4317
tls:
ca_file: /run/secrets/ca_servers
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch, attributes/scrub]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch, attributes/scrub]
exporters: [otlphttp/loki]
telemetry:
logs:
level: info
+4
View File
@@ -0,0 +1,4 @@
tls_server_config:
cert_file: /run/secrets/prometheus_crt
key_file: /run/secrets/prometheus_key
min_version: TLS12
+21
View File
@@ -0,0 +1,21 @@
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/alert-rules.yml
scrape_configs:
# Метрики от OTel Collector (TLS-экспортёр :8889, сервер проверяется по CA).
- job_name: otel-collector
scheme: https
tls_config:
ca_file: /etc/prometheus/ca.crt
static_configs:
- targets: ['otel-collector:8889']
- job_name: prometheus
scheme: https
tls_config:
ca_file: /etc/prometheus/ca.crt
static_configs:
- targets: ['prometheus:9090']
+38
View File
@@ -0,0 +1,38 @@
server:
http_listen_port: 3200
grpc_listen_port: 9095
log_level: warn
tls:
cert_file: /run/secrets/tempo_crt
key_file: /run/secrets/tempo_key
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 24h
storage:
trace:
backend: local
local:
path: /var/tempo/traces
wal:
path: /var/tempo/wal
metrics_generator:
registry:
external_labels:
source: tempo
storage:
path: /var/tempo/generator/wal