ЛР6: OpenTelemetry, Collector, Prometheus/Loki/Tempo, Grafana, алерты, исследование цены наблюдаемости

This commit is contained in:
kolya5544
2026-10-03 05:10:45 +03:00
parent 470d9d6f1e
commit 1d908578e3
79 changed files with 10501 additions and 38 deletions
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
"""Генератор dashboard JSON (infra/grafana/dashboards/messenger.json). Запуск: python infra/grafana/build_dashboard.py
Dashboard хранится в Git как JSON и импортируется provisioning-ом автоматически; генератор — только удобство правки."""
import json
import os
PROM = {"type": "prometheus", "uid": "prometheus"}
LOKI = {"type": "loki", "uid": "loki"}
TEMPO = {"type": "tempo", "uid": "tempo"}
panel_id = [0]
def _id():
panel_id[0] += 1
return panel_id[0]
def stat_or_ts(title, exprs, x, y, w=8, h=7, unit="short", kind="timeseries", desc="", thresholds=None, ds=PROM, legends=None):
p = {"id": _id(), "type": kind, "title": title, "description": desc, "datasource": ds,
"gridPos": {"x": x, "y": y, "w": w, "h": h},
"targets": [{"refId": chr(65 + i), "expr": e, "datasource": ds, "legendFormat": (legends or [""] * len(exprs))[i]}
for i, e in enumerate(exprs)],
"fieldConfig": {"defaults": {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10}}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}}}
if thresholds:
p["fieldConfig"]["defaults"]["thresholds"] = {"mode": "absolute", "steps": thresholds}
return p
def row(title, y):
return {"id": _id(), "type": "row", "title": title, "gridPos": {"x": 0, "y": y, "w": 24, "h": 1}, "collapsed": False, "panels": []}
NB = '{http_route!~"/health.*"}'
panels = []
y = 0
panels.append(row("API (бизнес-запросы без /health) — запросы, ошибки, задержки", y)); y += 1
panels += [
stat_or_ts("RPS по маршрутам", ['sum by (http_route) (rate(http_server_request_duration_seconds_count%s[1m]))' % NB], 0, y,
unit="reqps", legends=["{{http_route}}"], desc="Единицы: запросов в секунду. Источник: http_server_request_duration_seconds_count."),
stat_or_ts("Доля ошибок 5xx (SLI)", ['sli:http_error_ratio:1m'], 8, y, unit="percentunit",
desc="Числитель: 5xx; знаменатель: все запросы кроме /health. 4xx (в т.ч. неверный пароль) не считаются отказом сервиса.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 0.05}]),
stat_or_ts("Latency p50 / p95 / p99", [
'histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket%s[1m])))' % NB,
'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket%s[1m])))' % NB,
'histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket%s[1m])))' % NB],
16, y, unit="s", legends=["p50", "p95", "p99"],
desc="Процентили считаются из суммарной гистограммы всех реплик (sum by le), а не усреднением p95 реплик."),
]
y += 7
panels += [
stat_or_ts("RPS по статус-кодам", ['sum by (http_response_status_code) (rate(http_server_request_duration_seconds_count%s[1m]))' % NB],
0, y, unit="reqps", legends=["{{http_response_status_code}}"]),
stat_or_ts("Latency p95 по маршрутам", ['histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket%s[1m])))' % NB],
8, y, unit="s", legends=["{{http_route}}"]),
stat_or_ts("DB pool: занято / простаивает / ожидают", ['sum(db_client_connections_usage{state="used"})', 'sum(db_client_connections_usage{state="idle"})',
'sum(db_client_connections_waiting)'], 16, y, unit="short",
legends=["used", "idle", "waiting"], desc="Пул соединений PostgreSQL по всем репликам API. Рост waiting — насыщение пула."),
]
y += 7
panels.append(row("Задания (worker) и очередь", y)); y += 1
panels += [
stat_or_ts("Задания по исходам", ['sum by (outcome) (rate(messenger_jobs_processed_total[1m]))'], 0, y, unit="ops", legends=["{{outcome}}"],
desc="ready — успешно; failed — финальная ошибка; retried — временная ошибка, запланирован повтор; noop — повторная доставка."),
stat_or_ts("Длительность обработки p50 / p95 (worker)", [
'histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))',
'histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))'], 8, y, unit="s", legends=["p50", "p95"]),
stat_or_ts("Время до ready p50 / p95", [
'histogram_quantile(0.50, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[1m])))',
'histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[1m])))'], 16, y, unit="s", legends=["p50", "p95"],
desc="От устойчивого приёма загрузки (202) до ready. Включает ожидание в очереди."),
]
y += 7
panels += [
stat_or_ts("Глубина очереди (queued + processing)", ['max(messenger_queue_depth)'], 0, y, unit="short", legends=["jobs"]),
stat_or_ts("Возраст старейшей задачи", ['max(messenger_queue_oldest_job_age_seconds)'], 8, y, unit="s", legends=["oldest"],
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 30}],
desc="Backlog — не задержка обработки: показывает, как долго ждёт самое старое задание."),
stat_or_ts("Worker: занято / ёмкость", ['sum(messenger_worker_busy)', 'sum(messenger_worker_capacity)'], 16, y, legends=["busy", "capacity"],
desc="Насыщение worker: busy == capacity при растущей очереди означает нехватку мощности."),
]
y += 7
panels.append(row("Ресурсы процессов", y)); y += 1
panels += [
stat_or_ts("RSS по сервисам", ['sum by (service_name) (process_memory_rss_bytes)'], 0, y, unit="bytes", legends=["{{service_name}}"]),
stat_or_ts("CPU по сервисам (ядра)", ['sum by (service_name) (rate(process_cpu_time_seconds_total[1m]))'], 8, y, unit="short", legends=["{{service_name}}"],
desc="rate накопленного CPU-времени процесса: 1.0 = одно ядро."),
stat_or_ts("Collector: очередь экспорта и отказы", ['sum by (exporter) (otelcol_exporter_queue_size)',
'sum by (exporter) (rate(otelcol_exporter_send_failed_spans[1m]))',
'sum(rate(otelcol_processor_memory_limiter_refused_spans[1m]))'], 16, y, legends=["queue {{exporter}}", "failed spans {{exporter}}", "refused (memory_limiter)"],
desc="Поведение Collector при недоступном backend: ограниченная очередь, отказы, memory_limiter."),
]
y += 7
panels.append(row("Логи и алерты", y)); y += 1
panels.append({"id": _id(), "type": "logs", "title": "Структурные логи (API и worker), ошибки и предупреждения", "datasource": LOKI,
"gridPos": {"x": 0, "y": y, "w": 16, "h": 10},
"targets": [{"refId": "A", "datasource": LOKI, "expr": '{service_name=~"messenger-.*"} | detected_level=~"warn|warning|error|ERROR|WARN"'}],
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending"}})
panels.append({"id": _id(), "type": "alertlist", "title": "Алерты (firing / pending)", "datasource": PROM,
"gridPos": {"x": 16, "y": y, "w": 8, "h": 10},
"options": {"alertInstanceLabelFilter": "", "alertName": "", "dashboardAlerts": False, "groupBy": [], "groupMode": "default",
"maxItems": 20, "sortOrder": 1, "stateFilter": {"firing": True, "pending": True, "noData": True, "normal": False, "error": True}}})
y += 10
panels.append({"id": _id(), "type": "traces", "title": "Последние трассы API (Tempo)", "datasource": TEMPO,
"gridPos": {"x": 0, "y": y, "w": 24, "h": 8},
"targets": [{"refId": "A", "datasource": TEMPO, "queryType": "traceql", "query": '{ resource.service.name = "messenger-api" }', "limit": 20}]})
dashboard = {"uid": "messenger-overview", "title": "Messenger: API, очередь, worker", "tags": ["messenger", "lab6"], "timezone": "browser",
"schemaVersion": 39, "version": 1, "refresh": "5s", "time": {"from": "now-15m", "to": "now"}, "panels": panels,
"annotations": {"list": []}, "templating": {"list": []}}
out = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dashboards", "messenger.json")
with open(out, "w", encoding="utf-8") as fh:
json.dump(dashboard, fh, ensure_ascii=False, indent=1)
print("saved", out)
+917
View File
@@ -0,0 +1,917 @@
{
"uid": "messenger-overview",
"title": "Messenger: API, очередь, worker",
"tags": [
"messenger",
"lab6"
],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"type": "row",
"title": "API (бизнес-запросы без /health) — запросы, ошибки, задержки",
"gridPos": {
"x": 0,
"y": 0,
"w": 24,
"h": 1
},
"collapsed": false,
"panels": []
},
{
"id": 2,
"type": "timeseries",
"title": "RPS по маршрутам",
"description": "Единицы: запросов в секунду. Источник: http_server_request_duration_seconds_count.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 1,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum by (http_route) (rate(http_server_request_duration_seconds_count{http_route!~\"/health.*\"}[1m]))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "{{http_route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 3,
"type": "timeseries",
"title": "Доля ошибок 5xx (SLI)",
"description": "Числитель: 5xx; знаменатель: все запросы кроме /health. 4xx (в т.ч. неверный пароль) не считаются отказом сервиса.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 1,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sli:http_error_ratio:1m",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": ""
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 0.05
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 4,
"type": "timeseries",
"title": "Latency p50 / p95 / p99",
"description": "Процентили считаются из суммарной гистограммы всех реплик (sum by le), а не усреднением p95 реплик.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 1,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{http_route!~\"/health.*\"}[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{http_route!~\"/health.*\"}[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{http_route!~\"/health.*\"}[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 5,
"type": "timeseries",
"title": "RPS по статус-кодам",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum by (http_response_status_code) (rate(http_server_request_duration_seconds_count{http_route!~\"/health.*\"}[1m]))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "{{http_response_status_code}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 6,
"type": "timeseries",
"title": "Latency p95 по маршрутам",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 8,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{http_route!~\"/health.*\"}[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "{{http_route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 7,
"type": "timeseries",
"title": "DB pool: занято / простаивает / ожидают",
"description": "Пул соединений PostgreSQL по всем репликам API. Рост waiting — насыщение пула.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 8,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum(db_client_connections_usage{state=\"used\"})",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "used"
},
{
"refId": "B",
"expr": "sum(db_client_connections_usage{state=\"idle\"})",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "idle"
},
{
"refId": "C",
"expr": "sum(db_client_connections_waiting)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "waiting"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 8,
"type": "row",
"title": "Задания (worker) и очередь",
"gridPos": {
"x": 0,
"y": 15,
"w": 24,
"h": 1
},
"collapsed": false,
"panels": []
},
{
"id": 9,
"type": "timeseries",
"title": "Задания по исходам",
"description": "ready — успешно; failed — финальная ошибка; retried — временная ошибка, запланирован повтор; noop — повторная доставка.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "{{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 10,
"type": "timeseries",
"title": "Длительность обработки p50 / p95 (worker)",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 16,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 11,
"type": "timeseries",
"title": "Время до ready p50 / p95",
"description": "От устойчивого приёма загрузки (202) до ready. Включает ожидание в очереди.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 16,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[1m])))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 12,
"type": "timeseries",
"title": "Глубина очереди (queued + processing)",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 23,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_depth)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "jobs"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 13,
"type": "timeseries",
"title": "Возраст старейшей задачи",
"description": "Backlog — не задержка обработки: показывает, как долго ждёт самое старое задание.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 23,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_oldest_job_age_seconds)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "oldest"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
},
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 30
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 14,
"type": "timeseries",
"title": "Worker: занято / ёмкость",
"description": "Насыщение worker: busy == capacity при растущей очереди означает нехватку мощности.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 23,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum(messenger_worker_busy)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "busy"
},
{
"refId": "B",
"expr": "sum(messenger_worker_capacity)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 15,
"type": "row",
"title": "Ресурсы процессов",
"gridPos": {
"x": 0,
"y": 30,
"w": 24,
"h": 1
},
"collapsed": false,
"panels": []
},
{
"id": 16,
"type": "timeseries",
"title": "RSS по сервисам",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 31,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (process_memory_rss_bytes)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "{{service_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 17,
"type": "timeseries",
"title": "CPU по сервисам (ядра)",
"description": "rate накопленного CPU-времени процесса: 1.0 = одно ядро.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 8,
"y": 31,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (rate(process_cpu_time_seconds_total[1m]))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "{{service_name}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 18,
"type": "timeseries",
"title": "Collector: очередь экспорта и отказы",
"description": "Поведение Collector при недоступном backend: ограниченная очередь, отказы, memory_limiter.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 31,
"w": 8,
"h": 7
},
"targets": [
{
"refId": "A",
"expr": "sum by (exporter) (otelcol_exporter_queue_size)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "queue {{exporter}}"
},
{
"refId": "B",
"expr": "sum by (exporter) (rate(otelcol_exporter_send_failed_spans[1m]))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "failed spans {{exporter}}"
},
{
"refId": "C",
"expr": "sum(rate(otelcol_processor_memory_limiter_refused_spans[1m]))",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"legendFormat": "refused (memory_limiter)"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 10
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 19,
"type": "row",
"title": "Логи и алерты",
"gridPos": {
"x": 0,
"y": 38,
"w": 24,
"h": 1
},
"collapsed": false,
"panels": []
},
{
"id": 20,
"type": "logs",
"title": "Структурные логи (API и worker), ошибки и предупреждения",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 39,
"w": 16,
"h": 10
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "loki",
"uid": "loki"
},
"expr": "{service_name=~\"messenger-.*\"} | detected_level=~\"warn|warning|error|ERROR|WARN\""
}
],
"options": {
"showTime": true,
"wrapLogMessage": true,
"enableLogDetails": true,
"sortOrder": "Descending"
}
},
{
"id": 21,
"type": "alertlist",
"title": "Алерты (firing / pending)",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 16,
"y": 39,
"w": 8,
"h": 10
},
"options": {
"alertInstanceLabelFilter": "",
"alertName": "",
"dashboardAlerts": false,
"groupBy": [],
"groupMode": "default",
"maxItems": 20,
"sortOrder": 1,
"stateFilter": {
"firing": true,
"pending": true,
"noData": true,
"normal": false,
"error": true
}
}
},
{
"id": 22,
"type": "traces",
"title": "Последние трассы API (Tempo)",
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"gridPos": {
"x": 0,
"y": 49,
"w": 24,
"h": 8
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"queryType": "traceql",
"query": "{ resource.service.name = \"messenger-api\" }",
"limit": 20
}
]
}
],
"annotations": {
"list": []
},
"templating": {
"list": []
}
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
allowUiUpdates: false
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,41 @@
apiVersion: 1
# Источники данных Grafana: Prometheus (метрики), Loki (логи), Tempo (трассы). Связи: лог -> трасса (derivedFields),
# трасса -> логи (tracesToLogsV2), трасса -> метрики.
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 5s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
derivedFields:
- name: trace_id
matcherType: label
matcherRegex: trace_id
url: "$${__value.raw}"
datasourceUid: tempo
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-1m"
spanEndTimeShift: "1m"
filterByTraceID: true
customQuery: true
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__span.traceId}"'
tracesToMetrics:
datasourceUid: prometheus
serviceMap:
datasourceUid: prometheus
+50
View File
@@ -0,0 +1,50 @@
# Балансировщик lab3: HAProxy 3.0. Единственная публичная точка входа; API-реплики наружу не опубликованы.
global
log stdout format raw local0 notice
maxconn 4096
defaults
mode http
log global
option dontlognull
option forwardfor
# connect короткий: недоступная реплика быстро заменяется другой (redispatch)
timeout connect 1s
timeout client 30s
timeout server 30s
timeout http-request 10s
timeout http-keep-alive 5s
timeout queue 5s
retries 3
option redispatch 1
retry-on conn-failure empty-response response-timeout 0rtt-rejected
# Docker DNS (127.0.0.11): адреса реплик API обновляются без перезапуска LB (scale up/down, пересоздание контейнеров).
resolvers docker
nameserver dns 127.0.0.11:53
accepted_payload_size 8192
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold nx 2s
hold other 2s
hold obsolete 2s
frontend public
bind :8080
default_backend api
# Внутренний healthcheck самого LB (контейнерный HEALTHCHECK); наружу не публикуется.
frontend lb_health
bind :8081
monitor-uri /healthz
backend api
balance roundrobin
# Проверка готовности каждые 1 с; 2 неудачи подряд -> сервер исключён (обнаружение отказа <= ~3 с), 2 успеха -> возвращён.
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none
server-template api 1-8 api:8080
+37
View File
@@ -0,0 +1,37 @@
# Loki: хранилище логов (filesystem, volume lokidata). Принимает OTLP/HTTP от Collector (/otlp/v1/logs).
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
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: 2024-04-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 168h
reject_old_samples: false
volume_enabled: true
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+64
View File
@@ -0,0 +1,64 @@
# Профиль «tail sampling» (трек 1, lab6): SDK отправляет 100 % спанов, Collector оставляет
# - все трассы с ошибками, - все медленные (> 500 мс), - 10 % остальных.
# Метрики и логи без изменений. Подключается через COLLECTOR_CONFIG=/etc/otelcol/collector-tail.yaml.
receivers:
otlp:
protocols:
grpc: {endpoint: 0.0.0.0:4317}
http: {endpoint: 0.0.0.0:4318}
processors:
memory_limiter: {check_interval: 1s, limit_mib: 280, spike_limit_mib: 60}
batch: {send_batch_size: 1024, send_batch_max_size: 2048, timeout: 2s}
attributes/scrub:
actions:
- {key: http.request.header.authorization, action: delete}
- {key: http.request.header.cookie, action: delete}
- {key: db.statement, action: delete}
- {key: url.query, action: delete}
tail_sampling:
decision_wait: 5s
num_traces: 20000
expected_new_traces_per_sec: 500
policies:
- {name: errors, type: status_code, status_code: {status_codes: [ERROR]}}
- {name: slow, type: latency, latency: {threshold_ms: 500}}
- {name: baseline, type: probabilistic, probabilistic: {sampling_percentage: 10}}
exporters:
otlp_grpc/tempo:
endpoint: tempo:4317
tls: {insecure: true}
sending_queue: {enabled: true, num_consumers: 2, queue_size: 500}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
otlp_http/loki:
endpoint: http://loki:3100/otlp
sending_queue: {enabled: true, num_consumers: 2, queue_size: 500}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion: {enabled: true}
metric_expiration: 20s
service:
telemetry:
metrics:
level: normal
readers:
- pull:
exporter:
prometheus: {host: 0.0.0.0, port: 8888}
logs: {level: warn}
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, tail_sampling, batch]
exporters: [otlp_grpc/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlp_http/loki]
+75
View File
@@ -0,0 +1,75 @@
# OpenTelemetry Collector (contrib). Один пайплайн на сигнал, у каждого — реальный backend:
# traces -> Tempo (OTLP/gRPC)
# metrics -> Prometheus (Prometheus-экспортёр: Prometheus сам забирает /metrics у Collector)
# logs -> Loki (OTLP/HTTP, нативный приём Loki)
# Collector — маршрутизатор/обработчик, не долговременное хранилище. Порты 4317/4318 доступны ТОЛЬКО во внутренней сети backend.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
# Защита RAM Collector: при приближении к лимиту новые данные отклоняются (клиент SDK получает ошибку и отбрасывает
# пакет, приложение продолжает работать). limit_mib согласован с mem_limit контейнера.
memory_limiter:
check_interval: 1s
limit_mib: 280
spike_limit_mib: 60
batch:
send_batch_size: 1024
send_batch_max_size: 2048
timeout: 2s
# Гарантированное удаление чувствительных атрибутов, даже если приложение их случайно передаст.
attributes/scrub:
actions:
- {key: http.request.header.authorization, action: delete}
- {key: http.request.header.cookie, action: delete}
- {key: http.request.body, action: delete}
- {key: db.statement, action: delete}
- {key: url.query, action: delete}
- {key: http.target, action: delete}
# Tail-sampling (профиль «tail», см. collector-tail.yaml): здесь не используется.
exporters:
otlp_grpc/tempo:
endpoint: tempo:4317
tls: {insecure: true}
# Ограниченная буферизация при недоступном backend: очередь фиксированного размера, повторы до 30 с, затем отбрасывание
# (потери считаются метрикой otelcol_exporter_send_failed_spans / otelcol_exporter_queue_size).
sending_queue: {enabled: true, num_consumers: 2, queue_size: 500}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
otlp_http/loki:
endpoint: http://loki:3100/otlp
sending_queue: {enabled: true, num_consumers: 2, queue_size: 500}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion: {enabled: true}
metric_expiration: 20s
service:
telemetry:
metrics:
level: normal
readers:
- pull:
exporter:
prometheus: {host: 0.0.0.0, port: 8888}
logs:
level: warn
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlp_grpc/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlp_http/loki]
+20
View File
@@ -0,0 +1,20 @@
# Prometheus: хранилище метрик (retention 7 дней, volume promdata). Забирает метрики приложений через Collector
# (Prometheus-экспортёр :8889) и собственные метрики Collector (:8888): очереди экспортёров, отказы, drop из memory_limiter.
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: otel-collector-app-metrics
honor_labels: true
static_configs:
- targets: ["otel-collector:8889"]
- job_name: otel-collector-internal
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
+77
View File
@@ -0,0 +1,77 @@
# Правила записи (SLI) и алерты. Runbook для каждого алерта — docs/runbooks.md (ссылка в аннотации).
# SLI доступности API: доля бизнес-запросов (без /health) без ответа 5xx. 4xx — ошибка клиента, в SLI не входит.
# SLO: 99.5 % за скользящее окно 30 дней => бюджет ошибок 0.5 %. Для демонстрации окна короткие (локальный стенд).
groups:
- name: messenger-sli
interval: 5s
rules:
- record: sli:http_requests:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{http_route!~"/health.*"}[1m]))
- record: sli:http_errors:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{http_route!~"/health.*",http_response_status_code=~"5.."}[1m]))
- record: sli:http_error_ratio:1m
expr: (sli:http_errors:rate1m / sli:http_requests:rate1m) or vector(0)
- record: sli:http_error_ratio:5m
expr: |
(sum(rate(http_server_request_duration_seconds_count{http_route!~"/health.*",http_response_status_code=~"5.."}[5m]))
/ sum(rate(http_server_request_duration_seconds_count{http_route!~"/health.*"}[5m]))) or vector(0)
- record: sli:http_latency_p95:5m
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{http_route!~"/health.*"}[5m])))
- record: sli:http_latency_p95:1m
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{http_route!~"/health.*"}[1m])))
- record: sli:upload_error_ratio:1m
expr: |
(sum(rate(http_server_request_duration_seconds_count{http_route="/api/v1/chats/{chat_id}/attachments",http_response_status_code=~"5.."}[1m]))
/ sum(rate(http_server_request_duration_seconds_count{http_route="/api/v1/chats/{chat_id}/attachments"}[1m]))) or vector(0)
- record: sli:upload_requests:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{http_route="/api/v1/chats/{chat_id}/attachments"}[1m]))
- record: sli:time_to_ready_p95:5m
expr: histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))
- name: messenger-alerts
rules:
- alert: HighHttpErrorRate
expr: sli:http_error_ratio:1m > 0.05 and sli:http_requests:rate1m > 0.5
for: 20s
labels: {severity: page}
annotations:
summary: "Доля 5xx бизнес-запросов API выше 5 %"
description: "Числитель — ответы 5xx, знаменатель — все запросы кроме /health. Значение: {{ $value | humanizePercentage }}."
runbook: "docs/runbooks.md#higherrorrate"
- alert: HighUploadErrorRate
expr: sli:upload_error_ratio:1m > 0.2 and sli:upload_requests:rate1m > 0.2
for: 15s
labels: {severity: page}
annotations:
summary: "Более 20 % загрузок вложений завершаются 5xx"
description: "Маршрут загрузки критичен, но малообъёмен: общий SLI 5xx его деградацию не заметит, поэтому есть отдельный алерт. Значение: {{ $value | humanizePercentage }}."
runbook: "docs/runbooks.md#higherrorrate"
- alert: HighLatencyP95
expr: sli:http_latency_p95:1m > 0.5 and sli:http_requests:rate1m > 0.5
for: 20s
labels: {severity: ticket}
annotations:
summary: "p95 задержки бизнес-запросов выше 500 мс"
description: "p95 из суммарной гистограммы всех реплик: {{ $value | humanizeDuration }}. Различайте медленную БД (spans db.connection, db_client_connections_waiting) и медленный обработчик."
runbook: "docs/runbooks.md#highlatency"
- alert: QueueLagGrowing
expr: messenger_queue_oldest_job_age_seconds > 30
for: 20s
labels: {severity: ticket}
annotations:
summary: "Самая старая задача в очереди ждёт дольше 30 с"
description: "Возраст старейшего задания: {{ $value }} с. Проверьте worker, брокер, S3."
runbook: "docs/runbooks.md#queuelag"
- alert: WorkerSilent
expr: absent(messenger_worker_capacity)
for: 30s
labels: {severity: ticket}
annotations:
summary: "Worker не присылает метрики"
runbook: "docs/runbooks.md#queuelag"
- alert: TelemetryExportFailing
expr: sum(rate(otelcol_exporter_send_failed_spans[1m])) + sum(rate(otelcol_exporter_send_failed_log_records[1m])) > 0
for: 15s
labels: {severity: ticket}
annotations:
summary: "Collector не может отправить телеметрию в хранилище"
runbook: "docs/runbooks.md#telemetry"
+33
View File
@@ -0,0 +1,33 @@
# Tempo: хранилище трасс (локальный диск, volume tempodata, retention 7 суток). Принимает OTLP/gRPC от Collector.
stream_over_http_enabled: true
server:
http_listen_port: 3200
log_level: warn
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
# Лимиты приёма: значения по умолчанию (10 000 «живых» трасс на тенанта) отбрасывали до 30 % спанов под нагрузкой
# (метрика tempo_discarded_spans_total{reason="live_traces_exceeded"}) — найдено экспериментом «цена наблюдаемости».
overrides:
defaults:
ingestion:
max_traces_per_user: 150000
rate_limit_bytes: 50000000
burst_size_bytes: 100000000
usage_report:
reporting_enabled: false