Files
mtusi2026lab7/infra/grafana/build_dashboard.py
T

211 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Генератор infra/grafana/dashboards/messenger.json (импортируется provisioning-ом).
JSON в Git — результат этого скрипта; правьте скрипт и пересоберите: python3 infra/grafana/build_dashboard.py
Каждая панель: запрос PromQL/LogQL/TraceQL и единица измерения (fieldConfig.unit). Квантили — histogram_quantile
по сумме buckets всех реплик (sum by le), не среднее и не усреднение p99 реплик."""
import json
from pathlib import Path
PROM = {'type': 'prometheus', 'uid': 'prometheus'}
LOKI = {'type': 'loki', 'uid': 'loki'}
TEMPO = {'type': 'tempo', 'uid': 'tempo'}
RATE = '$__rate_interval'
panels, y = [], 0
def row(title):
global y
panels.append({'type': 'row', 'title': title, 'collapsed': False, 'panels': [],
'gridPos': {'x': 0, 'y': y, 'w': 24, 'h': 1}, 'id': len(panels) + 1})
y += 1
def place(items, h=8):
"""Панели одной строки делят ширину 24 поровну."""
global y
w = 24 // len(items)
for i, p in enumerate(items):
p['gridPos'] = {'x': i * w, 'y': y, 'w': w, 'h': h}
p['id'] = len(panels) + 1
panels.append(p)
y += h
def ts(title, unit, targets, desc='', thresholds=None, stack=False, minimum=None):
defaults = {'unit': unit, 'custom': {'lineWidth': 1, 'fillOpacity': 10, 'showPoints': 'never',
'stacking': {'mode': 'normal' if stack else 'none'}}}
if minimum is not None:
defaults['min'] = minimum
if thresholds:
defaults['thresholds'] = {'mode': 'absolute', 'steps': [{'color': 'green', 'value': None}] +
[{'color': 'red', 'value': thresholds}]}
defaults['custom']['thresholdsStyle'] = {'mode': 'line+area'}
return {'type': 'timeseries', 'title': title, 'description': desc, 'datasource': PROM,
'fieldConfig': {'defaults': defaults, 'overrides': []},
'options': {'legend': {'displayMode': 'list', 'placement': 'bottom'}, 'tooltip': {'mode': 'multi', 'sort': 'desc'}},
'targets': [{'refId': chr(65 + i), 'datasource': PROM, 'expr': e, 'legendFormat': l} for i, (e, l) in enumerate(targets)]}
def stat(title, unit, expr, desc='', red_below=None, red_above=None, decimals=None):
steps = [{'color': 'green', 'value': None}]
if red_below is not None:
steps = [{'color': 'red', 'value': None}, {'color': 'green', 'value': red_below}]
if red_above is not None:
steps.append({'color': 'red', 'value': red_above})
defaults = {'unit': unit, 'thresholds': {'mode': 'absolute', 'steps': steps}}
if decimals is not None:
defaults['decimals'] = decimals
return {'type': 'stat', 'title': title, 'description': desc, 'datasource': PROM,
'fieldConfig': {'defaults': defaults, 'overrides': []},
'options': {'reduceOptions': {'calcs': ['lastNotNull'], 'fields': '', 'values': False},
'colorMode': 'background', 'graphMode': 'area', 'textMode': 'value'},
'targets': [{'refId': 'A', 'datasource': PROM, 'expr': expr, 'instant': False}]}
def quantiles(metric, selector, by=''):
grp = f'le{", " + by if by else ""}'
return [(f'histogram_quantile({q}, sum by ({grp}) (rate({metric}_bucket{{{selector}}}[{RATE}])))',
f'p{int(q * 100)}{" {{" + by + "}}" if by else ""}') for q in (0.5, 0.95, 0.99)]
API = 'job="messenger-api"'
row('SLO и alerts (трек 2)')
place([
stat('Доступность API у клиентов, 1 ч', 'percentunit', '1 - slo:api_error_ratio:rate1h',
'SLI = 1 − 5xx/все ответы HAProxy (frontend public) за 1 ч: включает 503/504 самого LB, которых не видит API. '
'SLO 99.5 % за 30 дней.', red_below=0.995, decimals=2),
stat('Остаток бюджета API (30 д)', 'percentunit', '1 - slo:api_error_ratio:rate30d / 0.005',
'Доля неизрасходованного бюджета ошибок 0.5 % за 30 дней (на стенде — за доступную историю).', red_below=0, decimals=1),
stat('Ready ≤ 30 с, 1 ч', 'percentunit', '1 - slo:ready_bad_ratio:rate1h',
'SLI time-to-ready: доля вложений, ставших ready не позже 30 с от приёма. SLO 99 %.', red_below=0.99, decimals=2),
stat('Остаток бюджета time-to-ready (30 д)', 'percentunit', '1 - slo:ready_bad_ratio:rate30d / 0.01',
'Бюджет 1 % «медленных» или failed вложений за 30 дней.', red_below=0, decimals=1),
stat('Alerts firing', 'none', 'count(ALERTS{alertstate="firing"}) or vector(0)', 'Сейчас активных alerts.', red_above=1),
], h=5)
place([
ts('Burn rate API (×бюджет)', 'none', [
('slo:api_error_ratio:rate5m / 0.005', '5m'), ('slo:api_error_ratio:rate30m / 0.005', '30m'),
('slo:api_error_ratio:rate1h / 0.005', '1h'), ('slo:api_error_ratio:rate6h / 0.005', '6h')],
'Расход бюджета относительно равномерного. Fast burn: 1h и 5m > 14.4; slow burn: 6h и 30m > 6.', thresholds=6),
ts('Burn rate time-to-ready (×бюджет)', 'none', [
('slo:ready_bad_ratio:rate5m / 0.01', '5m'), ('slo:ready_bad_ratio:rate30m / 0.01', '30m'),
('slo:ready_bad_ratio:rate1h / 0.01', '1h'), ('slo:ready_bad_ratio:rate6h / 0.01', '6h')],
'Fast burn: 1h и 5m > 14.4; slow burn: 6h и 30m > 6.', thresholds=6),
{'type': 'state-timeline', 'title': 'Alerts (pending / firing)', 'datasource': PROM,
'description': 'Серия ALERTS: состояние правил Prometheus. Отсутствие полосы — alert неактивен (resolved).',
'fieldConfig': {'defaults': {'color': {'mode': 'thresholds'}, 'thresholds': {'mode': 'absolute', 'steps': [
{'color': 'transparent', 'value': None}, {'color': 'orange', 'value': 1}, {'color': 'red', 'value': 2}]}},
'overrides': []},
'options': {'showValue': 'never', 'mergeValues': True, 'rowHeight': 0.8, 'legend': {'showLegend': False}},
'targets': [{'refId': 'A', 'datasource': PROM, 'legendFormat': '{{alertname}}',
'expr': 'max by (alertname) ((ALERTS{alertstate="pending"} * 1) or (ALERTS{alertstate="firing"} * 2))'}]},
])
row('API: запросы, ошибки, задержка')
place([
ts('RPS по маршрутам', 'reqps', [(f'sum by (http_route, http_request_method) (rate(http_server_request_duration_seconds_count{{{API}}}[{RATE}]))',
'{{http_request_method}} {{http_route}}')],
'http.server.request.duration (_count) — счётчик запросов; label http_route — шаблон маршрута.', stack=True),
ts('RPS по классу статуса', 'reqps', [(
f'sum by (status_class) (label_replace(rate(http_server_request_duration_seconds_count{{{API}}}[{RATE}]), '
'"status_class", "${1}xx", "http_response_status_code", "([0-9]).."))', '{{status_class}}')], stack=True),
ts('Доля 5xx', 'percentunit', [
(f'(sum(rate(http_server_request_duration_seconds_count{{{API},http_response_status_code=~"5.."}}[{RATE}])) or vector(0))'
f' / sum(rate(http_server_request_duration_seconds_count{{{API}}}[{RATE}]))', 'в метриках API'),
('slo:api_error_ratio:rate5m', 'у клиентов (HAProxy), 5m — SLI, alert > 5 %')],
'5xx / все ответы; 4xx — не ошибка сервиса. Линия API ниже линии HAProxy, когда LB отвечает сам: 503 без готовых '
'реплик (БД недоступна → readiness), 504 по таймауту.', thresholds=0.05, minimum=0),
])
place([
ts('Задержка API p50/p95/p99', 's', quantiles('http_server_request_duration_seconds', API),
'Квантили из buckets histogram всех реплик (sum by le).'),
ts('p99 по маршрутам', 's', [(f'histogram_quantile(0.99, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{{{API}}}[{RATE}])))',
'{{http_route}}')]),
ts('p99 запросов к PostgreSQL', 's', [(f'histogram_quantile(0.99, sum by (le, job) (rate(db_client_operation_duration_seconds_bucket[{RATE}])))', '{{job}}')],
'db.client.operation.duration (instrumentation-pg). Медленная БД — растёт здесь; медленный handler — нет.'),
])
row('Worker и задания')
place([
ts('Jobs/с по исходу', 'ops', [(f'sum by (outcome) (rate(messenger_job_duration_seconds_count[{RATE}]))', '{{outcome}}')],
'done — ready; retry — временная ошибка, повтор; failed — терминально; noop/discarded — дубль/потерянная аренда.', stack=True),
ts('Длительность обработки job (done) p50/p95/p99', 's', quantiles('messenger_job_duration_seconds', 'outcome="done"')),
ts('Время до ready p50/p95/p99', 's', quantiles('messenger_attachment_time_to_ready_seconds', 'outcome="ready"'),
'От durable acceptance (COMMIT задания) до публикации ready. Порог SLO — 30 с.', thresholds=30),
])
place([
ts('Насыщение worker (busy / capacity)', 'percentunit', [
('sum(messenger_worker_busy) / sum(messenger_worker_capacity)', 'все worker'),
('messenger_worker_busy / messenger_worker_capacity', '{{instance}}')], minimum=0),
ts('Очередь: backlog', 'none', [
('max by (state) (messenger_jobs_backlog)', 'jobs {{state}} (БД)'),
('max(messenger_outbox_pending)', 'outbox без confirm'),
('sum(rabbitmq_detailed_queue_messages_ready{queue="attachments.process"})', 'RabbitMQ ready'),
('sum(rabbitmq_detailed_queue_messages_unacked{queue="attachments.process"})', 'RabbitMQ unacked')],
'Количество работы (backlog). БД — источник истины; одинаково видна со всех реплик API, берётся max.'),
ts('Возраст старейшего задания', 's', [('max by (queue) (messenger_jobs_oldest_age_seconds)', '{{queue}}'),
('sum(rabbitmq_detailed_queue_consumers{queue="attachments.process"})', 'consumers')],
'Секунды с приёма старейшего незавершённого задания (lag). Alert JobQueueLagGrowing — > 60 с в течение 1 мин.', thresholds=60),
])
row('Насыщение: пул БД, CPU, память, event loop')
place([
ts('Пул соединений PostgreSQL', 'none', [
('sum by (job, db_client_connection_state) (db_client_connection_count)', '{{job}} {{db_client_connection_state}}'),
('sum by (job) (db_client_connection_pending_requests)', '{{job}} ждут соединения'),
('sum by (job) (db_client_connection_max)', '{{job}} max')]),
ts('CPU процессов (доля ядра)', 'percentunit', [(f'sum by (job, instance) (rate(process_cpu_time_seconds_total[{RATE}]))', '{{job}} {{instance}}')],
'process.cpu.time; 100 % = одно ядро. Лимит контейнера api/worker — 1 CPU.'),
ts('Память процессов (RSS)', 'bytes', [('process_memory_usage_bytes', '{{job}} {{instance}}'),
('otelcol_process_memory_rss', 'collector')]),
ts('Event loop: задержка p99', 's', [('nodejs_eventloop_delay_p99_seconds', '{{job}} {{instance}}')],
'Блокировка event loop Node.js (CPU-bound handler) — растёт здесь, а не в p99 PostgreSQL.'),
])
row('Telemetry pipeline (OpenTelemetry Collector)')
place([
ts('Принято / отправлено (элементов/с)', 'ops', [
(f'sum(rate(otelcol_receiver_accepted_spans_total[{RATE}]))', 'spans принято'),
(f'sum(rate(otelcol_exporter_sent_spans_total[{RATE}]))', 'spans отправлено'),
(f'sum(rate(otelcol_receiver_accepted_log_records_total[{RATE}]))', 'logs принято'),
(f'sum(rate(otelcol_exporter_sent_log_records_total[{RATE}]))', 'logs отправлено'),
(f'sum(rate(otelcol_receiver_accepted_metric_points_total[{RATE}]))', 'metric points принято'),
(f'sum(rate(otelcol_exporter_sent_metric_points_total[{RATE}]))', 'metric points отправлено')]),
ts('Потери telemetry (элементов/с)', 'ops', [
(f'sum by (exporter) (rate(otelcol_exporter_send_failed_spans_total[{RATE}]))', 'send failed spans {{exporter}}'),
(f'sum by (exporter) (rate(otelcol_exporter_send_failed_log_records_total[{RATE}]))', 'send failed logs {{exporter}}'),
(f'sum by (exporter) (rate(otelcol_exporter_enqueue_failed_spans_total[{RATE}]))', 'очередь полна, spans {{exporter}}'),
(f'sum by (exporter) (rate(otelcol_exporter_enqueue_failed_log_records_total[{RATE}]))', 'очередь полна, logs {{exporter}}'),
(f'sum(rate(otelcol_receiver_refused_spans_total[{RATE}]))', 'отказ приёма spans (memory_limiter)')],
'Отброшенное Collector-ом: после 60 с повторов (send failed) или при полной очереди (enqueue failed).'),
ts('Очередь экспортёров', 'none', [('otelcol_exporter_queue_size', '{{exporter}}'),
('max(otelcol_exporter_queue_capacity)', 'ёмкость')],
'Ограниченная очередь в памяти: при недоступном backend растёт до ёмкости, не дальше.'),
])
row('Логи и трассы')
place([
{'type': 'logs', 'title': 'Ошибки и предупреждения (Loki)', 'datasource': LOKI,
'description': 'Структурные логи api и worker; поле trace_id ведёт в Tempo.',
'options': {'showTime': True, 'wrapLogMessage': True, 'sortOrder': 'Descending', 'enableLogDetails': True},
'targets': [{'refId': 'A', 'datasource': LOKI,
'expr': '{service_name=~"messenger-.+"} | severity_text=~"ERROR|WARN"'}]},
{'type': 'table', 'title': 'Трассы с ошибками (Tempo)', 'datasource': TEMPO,
'description': 'TraceQL { status = error }: ошибки HTTP 5xx, повторы и отказы обработки заданий.',
'targets': [{'refId': 'A', 'datasource': TEMPO, 'queryType': 'traceql', 'query': '{ status = error }',
'limit': 20, 'tableType': 'traces'}]},
], h=10)
dashboard = {
'uid': 'messenger-lab6', 'title': 'Messenger lab6', 'tags': ['messenger', 'lab6', 'slo'],
'description': 'API, worker, очередь, насыщение, SLO/burn rate, telemetry pipeline. Морару С. С., БПИ2303.',
'timezone': 'browser', 'refresh': '10s', 'schemaVersion': 41, 'version': 1, 'editable': False,
'time': {'from': 'now-1h', 'to': 'now'}, 'templating': {'list': []}, 'annotations': {'list': []},
'panels': panels,
}
out = Path(__file__).with_name('dashboards') / 'messenger.json'
out.write_text(json.dumps(dashboard, ensure_ascii=False, indent=2) + '\n')
print(f'{out}: {sum(p["type"] != "row" for p in panels)} panels')