Щербацевич-БПИ2302-на 3

This commit is contained in:
2026-11-27 21:28:16 +03:00
parent 20afc2c790
commit bd3a530df3
119 changed files with 10026 additions and 18 deletions
+212
View File
@@ -0,0 +1,212 @@
{
"annotations": {"list": []},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"links": [],
"refresh": "10s",
"schemaVersion": 39,
"tags": ["messenger", "lab6"],
"time": {"from": "now-1h", "to": "now"},
"timezone": "browser",
"title": "Messenger observability",
"uid": "messenger-lab6",
"version": 1,
"panels": [
{
"type": "text",
"id": 1,
"title": "SLI и единицы",
"gridPos": {"h": 5, "w": 24, "x": 0, "y": 0},
"options": {
"mode": "markdown",
"content": "**API availability.** SLI = бизнес-ответы 5xx / все бизнес-запросы, без `/health`. SLO = 99% успеха на окне 5 минут. Алерт смотрит окно 1 минута и порог 5%.\n\n**Time to ready.** SLI = гистограмма секунд от записи вложения до `ready`. SLO = p95 не выше 60 с. Алерт смотрит возраст старейшей queued/processing задачи и порог 30 с. Это backlog, не среднее время обработки.\n\nПроцентили считаются `histogram_quantile` по сумме bucket всех реплик (`sum by (le)`), а не как среднее готовых p95. Единицы: RPS — запросы/с, длительность и возраст — секунды, пул и worker — штуки, память — байты, CPU — ядра."
}
},
{
"type": "timeseries",
"id": 2,
"title": "API RPS",
"description": "Запросы в секунду, только sli=business. Единица req/s.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 5},
"fieldConfig": {"defaults": {"unit": "reqps", "custom": {"drawStyle": "line", "fillOpacity": 15}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (status_class) (rate(http_server_requests_total{service_name=\"messenger-api\",sli=\"business\"}[1m]))",
"legendFormat": "{{status_class}}"
}
]
},
{
"type": "timeseries",
"id": 3,
"title": "Ошибки API",
"description": "Сколько бизнес-ответов 4xx и 5xx накоплено. 4xx — ошибка запроса, 5xx — сбой сервера. Алерт и SLO по-прежнему только про 5xx.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 5},
"fieldConfig": {"defaults": {"unit": "short", "min": 0, "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (status_class) (http_server_requests_total{service_name=\"messenger-api\",sli=\"business\",status_class=~\"4xx|5xx\"}) or label_replace(vector(0), \"status_class\", \"4xx\", \"\", \"\") or label_replace(vector(0), \"status_class\", \"5xx\", \"\", \"\")",
"legendFormat": "{{status_class}}"
}
]
},
{
"type": "timeseries",
"id": 4,
"title": "API duration",
"description": "Секунды. histogram_quantile от суммы bucket всех реплик API.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 5},
"fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",sli=\"business\"}[5m])))", "legendFormat": "p50"},
{"refId": "B", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",sli=\"business\"}[5m])))", "legendFormat": "p95"},
{"refId": "C", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",sli=\"business\"}[5m])))", "legendFormat": "p99"}
]
},
{
"type": "timeseries",
"id": 5,
"title": "Jobs",
"description": "Задачи в секунду по outcome. Единица jobs/s.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 13},
"fieldConfig": {"defaults": {"unit": "ops", "custom": {"drawStyle": "line", "fillOpacity": 15}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (outcome) (rate(jobs_processed_total{job_type=\"attachment.process.v1\",outcome=~\"ready|failed|retry\"}[5m]))", "legendFormat": "{{outcome}}"}
]
},
{
"type": "timeseries",
"id": 6,
"title": "Job duration",
"description": "Секунды обработки. p95 из гистограммы, отдельно для ready и failed.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 13},
"fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.50, sum by (le) (rate(jobs_duration_seconds_bucket{outcome=~\"ready|failed|retry\"}[5m])))", "legendFormat": "p50"},
{"refId": "B", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(jobs_duration_seconds_bucket{outcome=~\"ready|failed|retry\"}[5m])))", "legendFormat": "p95"},
{"refId": "C", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(jobs_duration_seconds_bucket{outcome=~\"ready|failed|retry\"}[5m])))", "legendFormat": "p99"}
]
},
{
"type": "timeseries",
"id": 7,
"title": "Time to ready",
"description": "Секунды от принятия вложения до ready. p95 — SLO 60 с.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 13},
"fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.50, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p50"},
{"refId": "B", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p95"},
{"refId": "C", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p99"}
]
},
{
"type": "timeseries",
"id": 8,
"title": "Queue depth",
"description": "Число задач queued или processing. max, чтобы две реплики API не удваивали одно наблюдение.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 21},
"fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 15}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "max(queue_depth_ratio{queue=\"attachment.jobs\"})", "legendFormat": "attachment.jobs"}
]
},
{
"type": "timeseries",
"id": 9,
"title": "Oldest job age",
"description": "Секунды. Порог алерта 30 с отмечен как backlog, не как latency worker.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 21},
"fieldConfig": {"defaults": {"unit": "s", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "max(queue_oldest_age_seconds{queue=\"attachment.jobs\"})", "legendFormat": "oldest"}
]
},
{
"type": "timeseries",
"id": 10,
"title": "DB pool",
"description": "Соединения: used — занятые, waiting — ждущие checkout, capacity — размер пула с overflow. Сумма по репликам API.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 21},
"fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (state) (db_pool_connections_ratio{service_name=\"messenger-api\"})", "legendFormat": "{{state}}"}
]
},
{
"type": "timeseries",
"id": 11,
"title": "Worker saturation",
"description": "busy — занятые слоты, capacity — WORKER_CONCURRENCY.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 29},
"fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "max by (state) (worker_slots_ratio{service_name=\"messenger-worker\"})", "legendFormat": "{{state}}"}
]
},
{
"type": "timeseries",
"id": 12,
"title": "Process CPU",
"description": "Секунды CPU на секунду стены, сумма процессов сервиса. Единица — ядра.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 29},
"fieldConfig": {"defaults": {"unit": "short", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (service_name) (process_cpu_utilization_ratio)", "legendFormat": "{{service_name}}"}
]
},
{
"type": "timeseries",
"id": 13,
"title": "Process memory",
"description": "RSS процессов, байты.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 29},
"fieldConfig": {"defaults": {"unit": "bytes", "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "sum by (service_name) (process_memory_usage_bytes)", "legendFormat": "{{service_name}}"}
]
},
{
"type": "timeseries",
"id": 14,
"title": "Prometheus alert state",
"description": "1 — firing. Пропавший ряд — resolved/inactive. Имена HighApiErrorRate и QueueLagHigh.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 37},
"fieldConfig": {"defaults": {"unit": "short", "min": 0, "max": 1, "custom": {"drawStyle": "line", "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
"targets": [
{"refId": "A", "datasource": {"type": "prometheus", "uid": "prometheus"}, "expr": "ALERTS{alertname=~\"HighApiErrorRate|QueueLagHigh\"}", "legendFormat": "{{alertname}} {{alertstate}}"}
]
}
]
}
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
export GF_SECURITY_ADMIN_USER=admin
export GF_SECURITY_ADMIN_PASSWORD="$(cat /run/secrets/grafana_admin_password)"
export GF_AUTH_ANONYMOUS_ENABLED=false
export GF_USERS_ALLOW_SIGN_UP=false
export GF_ANALYTICS_REPORTING_ENABLED=false
export GF_ANALYTICS_CHECK_FOR_UPDATES=false
exec /run.sh
@@ -0,0 +1,12 @@
apiVersion: 1
contactPoints:
- orgId: 1
name: messenger-local
receivers:
- uid: messenger-local-none
type: webhook
settings:
url: http://127.0.0.1:9/unused
httpMethod: POST
disableResolveMessage: false
@@ -0,0 +1,8 @@
apiVersion: 1
policies:
- orgId: 1
receiver: messenger-local
group_by:
- grafana_folder
- alertname
@@ -0,0 +1,120 @@
apiVersion: 1
groups:
- orgId: 1
name: messenger-slo
folder: Messenger
interval: 30s
rules:
- uid: high-api-error-rate
title: High API error rate
condition: B
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
datasource:
type: prometheus
uid: prometheus
editorMode: code
expr: sum(rate(http_server_requests_total{service_name="messenger-api",sli="business",status_class="5xx"}[1m])) / clamp_min(sum(rate(http_server_requests_total{service_name="messenger-api",sli="business"}[1m])), 1e-9)
instant: true
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange:
from: 0
to: 0
datasourceUid: __expr__
model:
conditions:
- evaluator:
params:
- 0.05
type: gt
operator:
type: and
query:
params:
- B
reducer:
params: []
type: last
type: query
datasource:
type: __expr__
uid: __expr__
expression: A
intervalMs: 1000
maxDataPoints: 43200
refId: B
type: threshold
noDataState: OK
execErrState: Error
for: 1m
annotations:
summary: Доля бизнес 5xx выше 5% на окне 1 минута.
description: SLI исключает /health. SLO — 99% успеха на окне 5 минут. Runbook — infra/grafana/runbooks/high-error-rate.md.
labels:
severity: warning
isPaused: false
- uid: queue-lag-high
title: Queue lag high
condition: B
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
datasource:
type: prometheus
uid: prometheus
editorMode: code
expr: max(queue_oldest_age_seconds{queue="attachment.jobs"})
instant: true
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange:
from: 0
to: 0
datasourceUid: __expr__
model:
conditions:
- evaluator:
params:
- 30
type: gt
operator:
type: and
query:
params:
- B
reducer:
params: []
type: last
type: query
datasource:
type: __expr__
uid: __expr__
expression: A
intervalMs: 1000
maxDataPoints: 43200
refId: B
type: threshold
noDataState: OK
execErrState: Error
for: 1m
annotations:
summary: Возраст старейшей задачи больше 30 секунд.
description: Backlog, не latency обработки. SLO p95 time-to-ready — 60 секунд. Runbook — infra/grafana/runbooks/queue-lag.md.
labels:
severity: warning
isPaused: false
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: Messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /etc/grafana/dashboards
@@ -0,0 +1,45 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 10s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: trace_id
matcherRegex: "\"trace_id\":\"([0-9a-f]+)\""
url: "$${__value.raw}"
datasourceUid: tempo
urlDisplayLabel: Открыть трассу
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: false
customQuery: true
query: '{service_name=~"messenger-.+"} | trace_id="$${__trace.traceId}"'
tracesToMetrics:
datasourceUid: prometheus
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
lokiSearch:
datasourceUid: loki
+13
View File
@@ -0,0 +1,13 @@
# High API error rate
SLI: доля ответов 5xx среди бизнес-запросов (`sli="business"`). Проверки `/health/*` в числитель и знаменатель не входят: отказ клиента с неверным паролем — это 401, а не отказ базы.
SLO: не меньше 99% успешных бизнес-запросов на скользящем окне 5 минут.
Алерт: та же доля на окне 1 минута выше 5% в течение 1 минуты. Окно короче SLO, чтобы короткий отказ успел зажечься и погаснуть на защите.
1. На дашборде Messenger сравнить панель доли ошибок и p95 длительности.
2. Открыть трассу запроса со статусом 5xx. Если время в `db.finalize` или запрос оборвался таймаутом пула, это база. Если span handler длинный без дочернего db/s3, это код обработчика.
3. Сверить `db.pool.connections` со `state=used` и `state=waiting`. Рост waiting при полном used — насыщение пула, а не медленный Python.
4. Вернуть Postgres (`docker compose unpause postgres` или `start`).
5. Убедиться, что алерт перешёл из firing в inactive. Доставка уведомлений наружу не используется.
+12
View File
@@ -0,0 +1,12 @@
# Queue lag
Backlog — число задач `attachment.jobs` в статусе queued или processing и возраст старейшей из них. Это не latency успешной обработки: её показывает гистограмма `attachment.time_to_ready`.
SLO: p95 времени от принятой загрузки до `ready` не выше 60 секунд.
Алерт: возраст старейшей задачи больше 30 секунд в течение 1 минуты.
1. Сравнить queue depth / oldest age с `worker.slots`. Если capacity пропала, контейнер worker остановлен.
2. По trace id загрузки найти server span API, producer span relay (`publish attachment.jobs`) и consumer span worker. Разрыв после producer при живом API означает, что consumer не забирает сообщения.
3. В логах Loki по тому же trace id проверить `outbox published` и отсутствие `job ready`.
4. Запустить worker. Глубина и возраст должны уменьшиться, алерт стать inactive.