feat: implement lab 6 observability and telemetry cost research
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
# OpenTelemetry Collector contrib 0.164.0 стенда vladimirceva-lab6.
|
||||
#
|
||||
# Collector — не хранилище: принимает OTLP от api, worker и relay, держит
|
||||
# ограниченный буфер и раскладывает сигналы по трём backend:
|
||||
# метрики → экспортёр prometheus :8889 → его забирает Prometheus;
|
||||
# логи → OTLP/HTTP в Loki (родной приёмник /otlp);
|
||||
# трассы → OTLP/HTTP в Tempo.
|
||||
# Порты слушаются на всех интерфейсах контейнера, но наружу не
|
||||
# опубликованы: 4318 виден только в сети приложения, 8888 и 8889 — в сетях
|
||||
# стенда (compose.yaml). Аутентификации у приёмника нет — поэтому и нет
|
||||
# публикации.
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
# SDK приложения шлёт только OTLP/HTTP protobuf; gRPC не включён
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
# первым: при нехватке памяти Collector отказывает приёмнику (SDK
|
||||
# получит ошибку и отбросит пакет), а не растёт до OOM. Мягкий предел —
|
||||
# 180 − 36 МиБ, жёсткий — 180 МиБ при лимите контейнера 256 МиБ
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 180
|
||||
spike_limit_mib: 36
|
||||
# пакеты к backend: по 512 элементов или раз в 2 с
|
||||
batch:
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
timeout: 2s
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
# классические имена Prometheus: единица и _total суффиксами
|
||||
# (http_server_request_duration_seconds_bucket, messenger_relay_jobs_total)
|
||||
translation_strategy: UnderscoreEscapingWithSuffixes
|
||||
# ряды остановленной реплики уходят из экспортёра через 3 мин
|
||||
metric_expiration: 3m
|
||||
# ресурс не размножает метки: service.name → job,
|
||||
# service.instance.id → instance, остальное — в target_info
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: false
|
||||
|
||||
# Очередь экспорта ограничена числом элементов и не блокирует приём:
|
||||
# пока backend недоступен, Collector повторяет отправку до минуты, затем
|
||||
# отбрасывает пакет; переполненная очередь отбрасывает новое. Потери видны
|
||||
# в собственных метриках Collector (otelcol_exporter_send_failed_*,
|
||||
# otelcol_exporter_enqueue_failed_*)
|
||||
otlp_http/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
sizer: items
|
||||
queue_size: 20000
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 2s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
|
||||
otlp_http/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
sizer: items
|
||||
queue_size: 20000
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 2s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
# собственные метрики 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]
|
||||
@@ -0,0 +1,17 @@
|
||||
# Dashboard стенда грузится из файлов infra/otel/grafana/dashboards/
|
||||
# (в контейнере — /var/lib/grafana-dashboards). Правки через UI не
|
||||
# сохраняются: источник правды — JSON в git, его же можно импортировать в
|
||||
# другую Grafana руками (Dashboards → New → Import).
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: vladimirceva-messenger
|
||||
orgId: 1
|
||||
folder: Messenger lab 6
|
||||
folderUid: messenger-lab6
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /var/lib/grafana-dashboards
|
||||
@@ -0,0 +1,414 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — API, worker, relay (lab 6)",
|
||||
"description": "Signals of contracts/observability.md, levels 3 and 4 (backlog, saturation, time to ready, SLO and alerts — the last row). Metric names are Prometheus forms of OTel instruments: http.server.request.duration -> http_server_request_duration_seconds_*, messenger.job.duration -> messenger_job_duration_seconds_*, messenger.relay.jobs -> messenger_relay_jobs_total. Request counts are _count of the duration histogram; health is not recorded.",
|
||||
"tags": ["messenger", "lab6", "opentelemetry"],
|
||||
"editable": false,
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"time": {"from": "now-30m", "to": "now"},
|
||||
"refresh": "30s",
|
||||
"timezone": "utc",
|
||||
"graphTooltip": 1,
|
||||
"templating": {"list": []},
|
||||
"annotations": {"list": []},
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "row",
|
||||
"title": "Messenger API replicas",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 0},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "Request rate: route x status class",
|
||||
"description": "rate of http_server_request_duration_seconds_count over all replicas; label http_route is the route template.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 1},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (http_request_method, http_route, http_response_status_class) (rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{http_request_method}} {{http_route}} {{http_response_status_class}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "Server error ratio (5xx / all business requests)",
|
||||
"description": "Numerator: responses 5xx of the API replicas. Denominator: all API responses except health (health is not recorded). 4xx — client errors, shown separately.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 12, "y": 1},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "(sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_response_status_class=\"5xx\"}[5m])) or vector(0)) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]))",
|
||||
"legendFormat": "5xx ratio"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Client errors (4xx) per second by route",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 18, "y": 1},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (http_route, http_response_status_code) (rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_response_status_class=\"4xx\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{http_response_status_code}} {{http_route}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Request duration p50 / p95 / p99 (from histogram buckets of all replicas)",
|
||||
"description": "Unit: seconds. histogram_quantile(q, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m]))) for q = 0.5, 0.95, 0.99 — buckets of every replica are summed first, not an average of per-replica percentiles. Accuracy is bounded by bucket edges (TELEMETRY_HISTOGRAM_BUCKETS).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 9},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"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": "metrics"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "timeseries",
|
||||
"title": "p95 latency per route",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 9},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"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": "Background processing (messenger-worker, messenger-relay)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 17},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "timeseries",
|
||||
"title": "Job deliveries per second by outcome",
|
||||
"description": "ready — variants committed; failed — permanent error; retry — scheduled again with backoff; finished/leased/stale/fenced — no-op duplicates; unavailable/error/rejected/cancelled — delivery not completed.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 18},
|
||||
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_job_type, messenger_job_outcome) (rate(messenger_job_duration_seconds_count{job=\"messenger-worker\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"type": "stat",
|
||||
"title": "Unsuccessful job deliveries, last 1h",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 4, "x": 8, "y": 18},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0}, "overrides": []},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "value", "textMode": "value_and_name"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_job_outcome) (increase(messenger_job_duration_seconds_count{job=\"messenger-worker\", messenger_job_outcome=~\"failed|retry|error|unavailable|rejected|cancelled\"}[1h]))",
|
||||
"legendFormat": "{{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "timeseries",
|
||||
"title": "Job delivery duration p50 / p95 by outcome",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 18},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "histogram_quantile(0.5, sum by (le, messenger_job_outcome) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p50 {{messenger_job_outcome}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le, messenger_job_outcome) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p95 {{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "timeseries",
|
||||
"title": "Relay: jobs per second by action",
|
||||
"description": "published — confirmed by the broker; requeued/exhausted — expired leases; republished — lost messages; failed_* — passes interrupted by the broker or PostgreSQL.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 7, "w": 12, "x": 0, "y": 26},
|
||||
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_relay_action) (rate(messenger_relay_jobs_total{job=\"messenger-relay\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{messenger_relay_action}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"type": "stat",
|
||||
"title": "Scrape targets up",
|
||||
"description": "messenger — exporter of the Collector with application metrics; the rest — the telemetry pipeline itself.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 7, "w": 12, "x": 12, "y": 26},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 1}]}}, "overrides": []},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "background", "textMode": "value_and_name"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "up",
|
||||
"legendFormat": "{{job}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"type": "row",
|
||||
"title": "Loki logs and Tempo traces",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 33},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"type": "logs",
|
||||
"title": "Application logs (Loki): messenger-api, messenger-worker, messenger-relay",
|
||||
"description": "Each record carries event, logger, request_id (inside a request) and trace_id/span_id (inside a sampled span); the TraceID link opens the trace in Tempo.",
|
||||
"datasource": {"type": "loki", "uid": "logs"},
|
||||
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 34},
|
||||
"options": {"showTime": true, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true, "dedupStrategy": "none"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "loki", "uid": "logs"},
|
||||
"expr": "{service_name=~\"messenger-.+\"}",
|
||||
"queryType": "range"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"type": "table",
|
||||
"title": "Recent traces (Tempo): API requests and worker jobs",
|
||||
"description": "TraceQL search; open a trace ID to see server/consumer spans with PostgreSQL, S3 and render children.",
|
||||
"datasource": {"type": "tempo", "uid": "traces"},
|
||||
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 44},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "tempo", "uid": "traces"},
|
||||
"queryType": "traceql",
|
||||
"query": "{resource.service.name=~\"messenger-.+\" && (kind=server || kind=consumer)}",
|
||||
"limit": 20,
|
||||
"tableType": "traces"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"type": "row",
|
||||
"title": "Backlog, saturation and SLO (level 4)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 54},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"type": "timeseries",
|
||||
"title": "Job queue depth by state",
|
||||
"description": "Unit: jobs. sum by (messenger_job_state) (messenger_job_queue_depth). Source: PostgreSQL attachment_jobs counted over partial indexes by relay every 5 s (not the broker queue): outbox — accepted, not yet published; published — in the broker or waiting for retry backoff; processing — leased by worker. Backlog, not processing latency.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 55},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "custom": {"stacking": {"mode": "normal"}, "fillOpacity": 30}}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_job_state) (messenger_job_queue_depth)",
|
||||
"legendFormat": "{{messenger_job_state}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"type": "timeseries",
|
||||
"title": "Oldest unfinished job age",
|
||||
"description": "Unit: seconds. max by (messaging_destination_name) (messenger_job_queue_oldest_age_seconds): age of the oldest queued or processing job (from its durable acceptance). Red line — threshold of MessengerQueueLagGrowing (60 s for 1 m).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 55},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0, "custom": {"thresholdsStyle": {"mode": "line"}}, "thresholds": {"mode": "absolute", "steps": [{"color": "green", "value": null}, {"color": "red", "value": 60}]}}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "max by (messaging_destination_name) (messenger_job_queue_oldest_age_seconds)",
|
||||
"legendFormat": "{{messaging_destination_name}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"type": "timeseries",
|
||||
"title": "Time to ready p50 / p95 / p99 (upload accepted → ready)",
|
||||
"description": "Unit: seconds. histogram_quantile(q, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m]))). Recorded by worker when ready is committed; start — created_at of the job row written before 202. Includes broker wait, retries and backoff. Latency SLO: 95% of successful ready transitions within 30 s over 7 days; failed and unfinished jobs are excluded from this histogram.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 55},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p50"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p95"},
|
||||
{"refId": "C", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p99"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"type": "timeseries",
|
||||
"title": "DB pool: used / waiting / max by process",
|
||||
"description": "Unit: connections and operations. db_client_connection_count{db_client_connection_state=\"used\"} — checked out of the SQLAlchemy pool; db_client_connection_pending_requests — operations waiting for a connection (counted in src/db.py); db_client_connection_max — DB_POOL_SIZE + DB_POOL_OVERFLOW. Summed per job (messenger-api replicas together).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 63},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "legendFormat": "used {{job}}"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job) (db_client_connection_pending_requests)", "legendFormat": "waiting {{job}}"},
|
||||
{"refId": "C", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job) (db_client_connection_max)", "legendFormat": "max {{job}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"type": "timeseries",
|
||||
"title": "Worker saturation: busy / capacity",
|
||||
"description": "Unit: tasks. messenger_worker_busy — tasks processing a delivery now; messenger_worker_capacity — WORKER_CONCURRENCY. busy = capacity for long with a growing queue — the worker is the bottleneck. Sampled at metric export (15 s), short bursts are not visible.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 63},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum(messenger_worker_busy)", "legendFormat": "busy"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum(messenger_worker_capacity)", "legendFormat": "capacity"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"type": "timeseries",
|
||||
"title": "Process CPU (cores) by service and instance",
|
||||
"description": "Unit: CPU cores. sum by (job, instance) (rate(process_cpu_time_seconds_total[$__rate_interval])): user + system time of each process; worker includes its finished render subprocesses (os.times children).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 63},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job, instance) (rate(process_cpu_time_seconds_total[$__rate_interval]))", "legendFormat": "{{job}} {{instance}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"type": "timeseries",
|
||||
"title": "Process RSS by service and instance",
|
||||
"description": "Unit: bytes. process_memory_usage_bytes: resident set of each application process (/proc/self/statm). Collector: otelcol_process_memory_rss (bytes, no unit suffix in 0.164).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 71},
|
||||
"fieldConfig": {"defaults": {"unit": "bytes", "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "process_memory_usage_bytes", "legendFormat": "{{job}} {{instance}}"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "otelcol_process_memory_rss", "legendFormat": "otel-collector"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"type": "stat",
|
||||
"title": "7-day SLO: API ≥ 99.5%, 95% of successful jobs ready within 30 s",
|
||||
"description": "Unit: ratio. messenger:http_availability:ratio_7d = 1 − 5xx / all recorded API responses (health excluded; failures before API entry are not measured). messenger:attachment_ready_30s:ratio_7d = successful ready transitions within 30 s / all observed successful ready transitions; failed and unfinished jobs are excluded. This is a conditional latency SLI, not the success ratio of all accepted uploads. Recording rules: infra/otel/prometheus/rules.yml.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 71},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "decimals": 2, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.995}]}}, "overrides": [{"matcher": {"id": "byName", "options": "ready ≤ 30 s"}, "properties": [{"id": "thresholds", "value": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.95}]}}]}]},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "background", "textMode": "value_and_name"},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "messenger:http_availability:ratio_7d", "legendFormat": "API availability"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "messenger:attachment_ready_30s:ratio_7d", "legendFormat": "ready ≤ 30 s"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 25,
|
||||
"type": "timeseries",
|
||||
"title": "Alerts: pending / firing",
|
||||
"description": "Unit: alerts. sum by (alertname, alertstate) (ALERTS) — built-in series of Prometheus rule evaluation; absence means resolved. Runbooks: infra/otel/runbooks/.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 71},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (alertname, alertstate) (ALERTS)", "legendFormat": "{{alertname}} {{alertstate}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"type": "timeseries",
|
||||
"title": "Telemetry losses and export queue (Collector)",
|
||||
"description": "Unit: items per second and items. Collector 0.164 exposes its counters without the _total suffix. rate of otelcol_exporter_send_failed_{spans,log_records} — dropped after retries (backend down), otelcol_exporter_enqueue_failed_* — dropped because the export queue (20000 items) is full (appears after the first such drop), otelcol_receiver_refused_* — refused by memory_limiter; otelcol_exporter_queue_size — items buffered now.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 79},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (exporter) (rate(otelcol_exporter_send_failed_spans[5m]) or rate(otelcol_exporter_send_failed_log_records[5m]))", "legendFormat": "send failed {{exporter}}"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (exporter) (rate(otelcol_exporter_enqueue_failed_spans[5m]) or rate(otelcol_exporter_enqueue_failed_log_records[5m]))", "legendFormat": "queue full {{exporter}}"},
|
||||
{"refId": "C", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum(rate(otelcol_receiver_refused_spans[5m]) or rate(otelcol_receiver_refused_log_records[5m]) or rate(otelcol_receiver_refused_metric_points[5m]))", "legendFormat": "refused by receiver"},
|
||||
{"refId": "D", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (exporter) (otelcol_exporter_queue_size)", "legendFormat": "queue size {{exporter}}"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
# Источники Grafana стенда: три хранилища, по одному на сигнал. uid
|
||||
# постоянные — на них ссылаются dashboard и scripts/lab6.py
|
||||
# (telemetry-check ходит в хранилища через прокси источников Grafana).
|
||||
# Из UI не меняются; удалённый из файла источник удаляется (prune).
|
||||
apiVersion: 1
|
||||
prune: true
|
||||
|
||||
datasources:
|
||||
- name: Metrics (Prometheus)
|
||||
uid: metrics
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
httpMethod: POST
|
||||
# равно scrape_interval: rate() по окну меньше двух точек пуст
|
||||
timeInterval: 15s
|
||||
|
||||
- name: Logs (Loki)
|
||||
uid: logs
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
maxLines: 500
|
||||
# из записи журнала — переход в её трассу по trace_id (structured
|
||||
# metadata записи OTLP)
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: traces
|
||||
url: "$${__value.raw}"
|
||||
urlDisplayLabel: Open trace
|
||||
|
||||
- name: Traces (Tempo)
|
||||
uid: traces
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
# из span — записи журнала того же сервиса с этим trace_id
|
||||
tracesToLogsV2:
|
||||
datasourceUid: logs
|
||||
spanStartTimeShift: "-2m"
|
||||
spanEndTimeShift: "2m"
|
||||
customQuery: true
|
||||
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
|
||||
search:
|
||||
hide: false
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
@@ -0,0 +1,48 @@
|
||||
# Loki 3.7.9: хранилище логов стенда, один процесс, данные — файлы в
|
||||
# volume lokidata (/loki). Записи приходят от Collector по OTLP:
|
||||
# service.name, service.instance.id и deployment.environment.name
|
||||
# становятся метками потока (service_name, ...), атрибуты записи (event,
|
||||
# request_id, logger) и trace_id/span_id — structured metadata, тело —
|
||||
# сообщение. Срок хранения — 7 суток (compactor).
|
||||
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2026-11-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
retention_period: 168h
|
||||
# structured metadata нужна для trace_id и атрибутов записи
|
||||
allow_structured_metadata: true
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
|
||||
# без отправки статистики разработчикам Loki
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,36 @@
|
||||
# Prometheus v3.15.1: хранилище метрик стенда. Метрики приложения сюда
|
||||
# не пушатся — Prometheus сам забирает экспортёр Collector (:8889), куда
|
||||
# SDK api, worker и relay отправляют OTLP. Срок (7d) и объём (1GB) хранения
|
||||
# — флаги в compose.yaml; volume promdata.
|
||||
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
evaluation_interval: 15s
|
||||
|
||||
# SLI и alert rules (уровень 4). Оповещения наружу не уходят: Alertmanager
|
||||
# не подключён, состояние pending/firing видно в /api/v1/alerts и в Grafana
|
||||
rule_files:
|
||||
- /etc/prometheus/rules.yml
|
||||
|
||||
scrape_configs:
|
||||
# метрики приложения: job и instance уже проставил Collector из ресурса
|
||||
# (service.name, service.instance.id) — honor_labels их сохраняет
|
||||
- job_name: messenger
|
||||
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"]
|
||||
@@ -0,0 +1,104 @@
|
||||
# promtool test rules (make alerts-test): каждое правило — сработало при
|
||||
# поломке, не сработало до неё и ушло после восстановления.
|
||||
|
||||
rule_files:
|
||||
- rules.yml
|
||||
|
||||
evaluation_interval: 15s
|
||||
|
||||
tests:
|
||||
# 5xx начинаются на 150-й секунде: треть ответов
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/users/me", http_response_status_class="2xx"}'
|
||||
values: '0+10x60'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/users/me", http_response_status_class="5xx"}'
|
||||
values: '0+0x10 5+5x20 105+0x29'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 6m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
exp_annotations:
|
||||
summary: API answers 5xx to more than 5% of business requests
|
||||
description: >-
|
||||
Ratio of 5xx to all API responses (health excluded) over 2m stayed
|
||||
above 0.05 for 1m. Check PostgreSQL first: database unavailable
|
||||
lines and the postgresql spans of failing requests.
|
||||
runbook_url: infra/otel/runbooks/high-error-rate.md
|
||||
# ошибки кончились на 450-й секунде, окно 2 мин прошло
|
||||
- eval_time: 10m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
promql_expr_test:
|
||||
- expr: messenger:http_errors:ratio_rate2m
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'messenger:http_errors:ratio_rate2m'
|
||||
value: 0.3333333333333333
|
||||
|
||||
# одиночная ошибка при почти нулевом трафике не будит
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/users/me", http_response_status_class="5xx"}'
|
||||
values: '0+0x10 1+0x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 5m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# worker остановлен на 5 мин: возраст растёт, затем backlog разобран
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_job_queue_oldest_age_seconds{job="messenger-relay", instance="relay-1", messaging_destination_name="messenger.attachment-jobs"}'
|
||||
values: '0+15x20 0x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts: []
|
||||
- eval_time: 4m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
messaging_destination_name: messenger.attachment-jobs
|
||||
exp_annotations:
|
||||
summary: Oldest unfinished attachment job is older than 60s
|
||||
description: >-
|
||||
Oldest queued or processing job has waited more than 60s for 1m:
|
||||
jobs are accepted (202) but not finished. Usual causes: worker
|
||||
stopped, broker unavailable, relay stuck, retries with backoff.
|
||||
runbook_url: infra/otel/runbooks/queue-lag.md
|
||||
- eval_time: 7m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts: []
|
||||
|
||||
# Collector не отвечает на scrape
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'up{job="otel-collector", instance="otel-collector:8888"}'
|
||||
values: '1x5 0x10 1x10'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerTelemetryTargetDown
|
||||
exp_alerts: []
|
||||
- eval_time: 3m
|
||||
alertname: MessengerTelemetryTargetDown
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: ticket
|
||||
job: otel-collector
|
||||
instance: otel-collector:8888
|
||||
exp_annotations:
|
||||
summary: Prometheus cannot scrape the telemetry Collector
|
||||
description: >-
|
||||
Scrape target of the Collector (application metrics or its own
|
||||
metrics) is down for 1m; application alerts are blind meanwhile.
|
||||
runbook_url: infra/otel/runbooks/telemetry-down.md
|
||||
- eval_time: 6m
|
||||
alertname: MessengerTelemetryTargetDown
|
||||
exp_alerts: []
|
||||
@@ -0,0 +1,86 @@
|
||||
# SLI, SLO и alert rules стенда vladimirceva-lab6 (уровень 4).
|
||||
#
|
||||
# Цели SLO считаются за 7 суток; ровно столько Prometheus держит данные.
|
||||
# API: ≥ 99,5 % бизнес-запросов без 5xx. Числитель — ответы 5xx
|
||||
# реплик API, знаменатель — все их ответы; health в метрику не
|
||||
# попадает вовсе, 4xx (неверный пароль, 404) — не отказ сервиса.
|
||||
# загрузка: ≥ 95 % вложений становятся ready не позже 30 с после 202
|
||||
# (histogram messenger_attachment_time_to_ready_seconds,
|
||||
# корзина le="30.0").
|
||||
# Оповещения быстрые, на явную поломку, а не burn rate: окно 2–5 мин и
|
||||
# `for` 1 мин. Alertmanager не подключён: состояние pending → firing →
|
||||
# (нет в списке) resolved видно в Prometheus /api/v1/alerts и в Grafana.
|
||||
# Тесты правил: make alerts-test (promtool, infra/otel/prometheus/rules.test.yml).
|
||||
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 15s
|
||||
rules:
|
||||
- record: messenger:http_requests:rate2m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[2m]))
|
||||
- record: messenger:http_errors:ratio_rate2m
|
||||
expr: |
|
||||
(sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_response_status_class="5xx"}[2m])) or vector(0))
|
||||
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[2m]))
|
||||
# SLI доступности за окно SLO; 1 − значение = израсходованная доля
|
||||
- record: messenger:http_availability:ratio_7d
|
||||
expr: |
|
||||
1 - (
|
||||
(sum(increase(http_server_request_duration_seconds_count{job="messenger-api", http_response_status_class="5xx"}[7d])) or vector(0))
|
||||
/ sum(increase(http_server_request_duration_seconds_count{job="messenger-api"}[7d]))
|
||||
)
|
||||
# SLI времени до ready: доля готовых за 30 с (экспортёр Collector пишет
|
||||
# границы с дробной частью: le="30.0")
|
||||
- record: messenger:attachment_ready_30s:ratio_7d
|
||||
expr: |
|
||||
sum(increase(messenger_attachment_time_to_ready_seconds_bucket{le="30.0"}[7d]))
|
||||
/ sum(increase(messenger_attachment_time_to_ready_seconds_count[7d]))
|
||||
|
||||
- name: messenger-alerts
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
# 5 % = 10 × бюджет SLO; нижний порог трафика (≈ 6 запросов за 2 мин),
|
||||
# чтобы одиночный 503 в тишине не будил
|
||||
expr: |
|
||||
messenger:http_errors:ratio_rate2m > 0.05
|
||||
and messenger:http_requests:rate2m > 0.05
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: API answers 5xx to more than 5% of business requests
|
||||
description: >-
|
||||
Ratio of 5xx to all API responses (health excluded) over 2m stayed
|
||||
above 0.05 for 1m. Check PostgreSQL first: database unavailable
|
||||
lines and the postgresql spans of failing requests.
|
||||
runbook_url: infra/otel/runbooks/high-error-rate.md
|
||||
|
||||
- alert: MessengerQueueLagGrowing
|
||||
# возраст старейшего незавершённого задания (outbox, брокер, аренда)
|
||||
# из PostgreSQL; без worker растёт на 1 с в секунду
|
||||
expr: max by (messaging_destination_name) (messenger_job_queue_oldest_age_seconds) > 60
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: Oldest unfinished attachment job is older than 60s
|
||||
description: >-
|
||||
Oldest queued or processing job has waited more than 60s for 1m:
|
||||
jobs are accepted (202) but not finished. Usual causes: worker
|
||||
stopped, broker unavailable, relay stuck, retries with backoff.
|
||||
runbook_url: infra/otel/runbooks/queue-lag.md
|
||||
|
||||
- alert: MessengerTelemetryTargetDown
|
||||
# без Collector пропадают метрики приложения, и два правила выше
|
||||
# молча перестают срабатывать
|
||||
expr: up{job=~"messenger|otel-collector"} == 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: ticket
|
||||
annotations:
|
||||
summary: Prometheus cannot scrape the telemetry Collector
|
||||
description: >-
|
||||
Scrape target of the Collector (application metrics or its own
|
||||
metrics) is down for 1m; application alerts are blind meanwhile.
|
||||
runbook_url: infra/otel/runbooks/telemetry-down.md
|
||||
@@ -0,0 +1,38 @@
|
||||
# MessengerHighErrorRate — API отвечает 5xx
|
||||
|
||||
**Условие.** `messenger:http_errors:ratio_rate2m > 0.05` при трафике больше
|
||||
0,05 запроса/с, держится 1 мин (`infra/otel/prometheus/rules.yml`). 5 % —
|
||||
в 10 раз выше бюджета SLO 99,5 % за 7 суток.
|
||||
|
||||
**Что это значит для пользователя.** Часть запросов получает 503 (чаще
|
||||
всего) или 500. Health в метрике нет, 4xx не считаются.
|
||||
|
||||
## Шаги
|
||||
|
||||
1. Grafana → dashboard `messenger-lab6`, панель «Server error ratio» и
|
||||
«Request rate: route x status class»: все маршруты или
|
||||
один? Все — общий ресурс (PostgreSQL, пул); только загрузки и
|
||||
скачивание — S3.
|
||||
2. Панель «DB pool: used / waiting». `waiting > 0` и `used` у предела —
|
||||
база медленная или зависла: запросы стоят в очереди за соединением.
|
||||
3. Tempo: `{resource.service.name="messenger-api" && status=error}`.
|
||||
Открыть трассу:
|
||||
- длинный span `postgresql read|transaction` (≈ 5–6 с, `error.type`
|
||||
`Unavailable`/`TimeoutError`) почти на всю длину server span —
|
||||
виновата база, а не код ручки;
|
||||
- span базы короткий, а server span длинный — медленный handler
|
||||
(CPU, Argon2, S3): смотреть детей span'а и CPU процесса.
|
||||
4. Loki: `{service_name="messenger-api"} |= "database unavailable"` —
|
||||
класс ошибки драйвера (`error_type=`): `ConnectionRefusedError` —
|
||||
база остановлена, `TimeoutError`/`QueryCanceledError` — зависла или
|
||||
держит блокировку.
|
||||
5. В PostgreSQL (`docker compose exec postgres psql -U messenger messenger`):
|
||||
`SELECT pid, state, wait_event_type, now() - xact_start AS age, left(query, 60)
|
||||
FROM pg_stat_activity WHERE datname = current_database() ORDER BY age DESC NULLS LAST;`
|
||||
долгая транзакция с `Lock` у остальных — её завершить
|
||||
`pg_terminate_backend(pid)`.
|
||||
|
||||
## Восстановление и проверка
|
||||
|
||||
После устранения причины доля 5xx падает за окно 2 мин, alert уходит из
|
||||
`/api/v1/alerts` (resolved). Повтор проверки — `make alerts-check`.
|
||||
@@ -0,0 +1,36 @@
|
||||
# MessengerQueueLagGrowing — задания не доходят до ready
|
||||
|
||||
**Условие.** `max by (messaging_destination_name)
|
||||
(messenger_job_queue_oldest_age_seconds) > 60` в течение 1 мин. Метрику
|
||||
снимает relay раз в 5 с из PostgreSQL (частичный индекс незавершённых
|
||||
заданий): это возраст старейшего задания в состоянии `queued` или
|
||||
`processing`, где бы оно ни ждало — в outbox, в брокере или у worker.
|
||||
|
||||
**Что это значит для пользователя.** Загрузки отвечают 202, но вложения
|
||||
долго остаются `queued`/`processing`; ссылки на них в сообщениях есть, а
|
||||
байтов (`/content`) нет — 409.
|
||||
|
||||
## Шаги
|
||||
|
||||
1. Dashboard, панель «Job queue depth by state»:
|
||||
- растёт `outbox` — relay не публикует: брокер недоступен или relay
|
||||
остановлен (`docker compose ps relay rabbitmq`, журнал relay:
|
||||
`broker publish failed`, `relay pass failed`);
|
||||
- растёт `published`, `processing` ≈ 0 — worker не берёт:
|
||||
«Worker busy / capacity» пусто или 0 → worker остановлен
|
||||
(`make pipeline-state`, `docker compose ps worker`);
|
||||
- `processing` = capacity долго — worker занят до предела: смотреть
|
||||
«Job delivery duration» и CPU worker.
|
||||
2. Loki: `{service_name="messenger-worker"} |= "attachment processed"` —
|
||||
последние исходы; `retry` с растущими задержками — временный отказ
|
||||
S3, задания ждут backoff (до `JOB_RETRY_MAX_SECONDS`).
|
||||
3. Трасса одной зависшей загрузки: `make trace-chain` показывает, как
|
||||
найти её по id вложения (`messenger.attachment.id`) и где цепочка
|
||||
оборвалась (нет producer — relay; нет consumer — брокер или worker).
|
||||
|
||||
## Восстановление и проверка
|
||||
|
||||
Запустить остановленное (`make start-worker`, `docker compose start relay`).
|
||||
Backlog разбирается со скоростью панели «Job deliveries per second»;
|
||||
когда старейшее задание завершено, возраст падает, alert resolved.
|
||||
Повтор проверки — `make alerts-check`.
|
||||
@@ -0,0 +1,27 @@
|
||||
# MessengerTelemetryTargetDown — Prometheus не видит Collector
|
||||
|
||||
**Условие.** `up{job=~"messenger|otel-collector"} == 0` 1 мин. Метрики
|
||||
приложения приходят в Prometheus только через экспортёр Collector, поэтому
|
||||
без него alerts по ошибкам и очереди молчат, хотя сервис может работать.
|
||||
|
||||
**Что это значит для пользователя.** Ничего: сообщения и загрузки от
|
||||
телеметрии не зависят (SDK держит ограниченную очередь и отбрасывает
|
||||
лишнее). Теряются сигналы.
|
||||
|
||||
## Шаги
|
||||
|
||||
1. `docker compose ps otel-collector` — остановлен или перезапускается
|
||||
(OOM: лимит контейнера 256 МиБ, `memory_limiter` 180 МиБ).
|
||||
2. `make logs-telemetry`: `memory limiter` — отказ приёма по памяти,
|
||||
`Exporting failed` — backend (Tempo/Loki) недоступен.
|
||||
3. Потери (у Collector 0.164 счётчики без суффикса `_total`):
|
||||
`otelcol_receiver_refused_*` (отказано SDK),
|
||||
`otelcol_exporter_send_failed_*` и `otelcol_exporter_enqueue_failed_*`
|
||||
(не доставлено в backend), `otelcol_exporter_queue_size` против
|
||||
`otelcol_exporter_queue_capacity`. В stdout процессов приложения —
|
||||
не чаще раза в минуту `Failed to export …` со счётчиком пропущенных.
|
||||
|
||||
## Восстановление и проверка
|
||||
|
||||
`docker compose up -d otel-collector`; `up` снова 1, alert resolved.
|
||||
Отказ хранилища телеметрии под нагрузкой — `make telemetry-outage`.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Tempo 3.1.1: хранилище трасс стенда, монолит (-target=all в compose.yaml)
|
||||
# без Kafka. Принимает OTLP/HTTP от Collector на :4318, API запросов — :3200
|
||||
# (поиск TraceQL, /api/v2/traces/<id>). Блоки и WAL — в volume tempodata,
|
||||
# срок хранения блоков — 7 суток.
|
||||
|
||||
stream_over_http_enabled: true
|
||||
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
log_level: warn
|
||||
|
||||
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
|
||||
|
||||
# в 3.x срок блоков задают планировщик и исполнитель уплотнения
|
||||
backend_scheduler:
|
||||
provider:
|
||||
compaction:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
backend_worker:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
Reference in New Issue
Block a user