Files
mtusi2026lab6/scripts/lab6/gen_dashboards.py
T

239 lines
16 KiB
Python
Executable File
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
"""Generates the two provisioned Grafana dashboards (stdlib only).
Output: infra/grafana/dashboards/messenger-overview.json and
messenger-telemetry.json. Metric names were verified against the live
Prometheus (verify.py inventory). Percentiles are computed from summed buckets,
never averaged across replicas; queue/outbox snapshots use max() because every
API replica publishes the same PostgreSQL snapshot.
"""
import json
from pathlib import Path
OUT = Path(__file__).resolve().parents[2] / 'infra/grafana/dashboards'
PROM = {'type': 'prometheus', 'uid': 'prometheus'}
LOKI = {'type': 'loki', 'uid': 'loki'}
BIZ = 'job="messenger-api",http_route!~"/health.*|/internal/.*"'
class Board:
def __init__(self, uid, title):
self.uid, self.title = uid, title
self.panels = []
self.y = 0
self.x = 0
self.row_h = 0
self.next_id = 1
def row(self, title):
if self.x:
self.y += self.row_h
self.x = 0
self.panels.append({'type': 'row', 'title': title, 'collapsed': False,
'id': self._id(), 'panels': [],
'gridPos': {'h': 1, 'w': 24, 'x': 0, 'y': self.y}})
self.y += 1
self.row_h = 0
def _id(self):
self.next_id += 1
return self.next_id - 1
def _place(self, w, h):
if self.x + w > 24:
self.y += self.row_h
self.x, self.row_h = 0, 0
pos = {'h': h, 'w': w, 'x': self.x, 'y': self.y}
self.x += w
self.row_h = max(self.row_h, h)
return pos
def ts(self, title, queries, unit, description, w=12, h=8, vmin=None, vmax=None):
self.panels.append({
'type': 'timeseries', 'title': title, 'id': self._id(),
'description': description, 'datasource': PROM,
'gridPos': self._place(w, h),
'fieldConfig': {'defaults': {**{'unit': unit, 'custom': {
'lineWidth': 1, 'fillOpacity': 8, 'showPoints': 'never'}},
**({'min': vmin} if vmin is not None else {}),
**({'max': vmax} if vmax is not None else {})},
'overrides': []},
'options': {'legend': {'displayMode': 'list', 'placement': 'bottom'},
'tooltip': {'mode': 'multi'}},
'targets': [{'refId': chr(65 + i), 'datasource': PROM, 'expr': expr,
'legendFormat': legend}
for i, (expr, legend) in enumerate(queries)]})
def stat(self, title, expr, unit, description, w=6, h=4, legend=''):
self.panels.append({
'type': 'stat', 'title': title, 'id': self._id(),
'description': description, 'datasource': PROM,
'gridPos': self._place(w, h),
'fieldConfig': {'defaults': {'unit': unit}, 'overrides': []},
'options': {'reduceOptions': {'calcs': ['lastNotNull']},
'colorMode': 'value'},
'targets': [{'refId': 'A', 'datasource': PROM, 'expr': expr,
'legendFormat': legend}]})
def table(self, title, expr, description, w=12, h=8):
self.panels.append({
'type': 'table', 'title': title, 'id': self._id(),
'description': description, 'datasource': PROM,
'gridPos': self._place(w, h),
'fieldConfig': {'defaults': {'unit': 'short'}, 'overrides': []},
'options': {'showHeader': True},
'targets': [{'refId': 'A', 'datasource': PROM, 'expr': expr,
'instant': True, 'format': 'table'}],
'transformations': [{'id': 'organize', 'options': {
'excludeByName': {'Time': True, '__name__': True,
'job': True, 'Value': True}}}]})
def logs(self, title, expr, description, w=12, h=10):
self.panels.append({
'type': 'logs', 'title': title, 'id': self._id(),
'description': description, 'datasource': LOKI,
'gridPos': self._place(w, h),
'options': {'showTime': True, 'wrapLogMessage': True,
'sortOrder': 'Descending', 'enableLogDetails': True},
'targets': [{'refId': 'A', 'datasource': LOKI, 'expr': expr,
'queryType': 'range'}]})
def render(self):
return {
'uid': self.uid, 'title': self.title, 'schemaVersion': 39,
'version': 1, 'editable': False, 'refresh': '10s',
'time': {'from': 'now-15m', 'to': 'now'}, 'timezone': 'utc',
'tags': ['messenger', 'lab6'], 'templating': {'list': []},
'annotations': {'list': []}, 'panels': self.panels}
def quantiles(metric, by='', selector='', window='1m'):
group = 'le' + (',' + by if by else '')
legend = ' {{' + by + '}}' if by else ''
return [('histogram_quantile(%s, sum by(%s)(rate(%s_bucket%s[%s])))'
% (q, group, metric, selector, window), 'p%d%s' % (round(q * 100), legend))
for q in (0.5, 0.95, 0.99)]
def overview():
b = Board('messenger-overview', 'Messenger: API и worker')
b.row('API (бизнес-запросы; /health* и /internal/* исключены)')
b.ts('RPS по маршруту и классу статуса', [(
'sum by (http_route, status_class)(label_replace(rate(http_server_request_duration_seconds_count{%s}[1m]), "status_class", "${1}xx", "http_response_status_code", "(.).."))' % BIZ,
'{{http_route}} {{status_class}}')], 'reqps',
'rate(http_server_request_duration_seconds_count[1m]) по http_route и классу кода; число запросов — _count гистограммы.')
b.ts('Доля 5xx (1m)', [('messenger:api_errors:rate1m / messenger:api_requests:rate1m', '5xx / бизнес-запросы')],
'percentunit', 'Recording rules: 5xx rate / все бизнес-запросы за 1m; 4xx — не ошибка сервиса. Пусто без трафика (N/A).', vmin=0, vmax=1)
b.stat('Availability (5m), цель ≥ 99.5%', 'messenger:api_availability:ratio5m',
'percentunit', '1 - 5xx/все бизнес-запросы за 5m (recording rule messenger:api_availability:ratio5m). N/A без трафика.')
b.stat('Свежие реплики API', 'count((time() - timestamp(target_info{job="messenger-api"})) < 30) or vector(0)',
'short', 'Число API-реплик, чей target_info обновлялся за последние 30 с (OTLP-метрики).')
b.stat('HAProxy 5xx, rps', 'sum(rate(haproxy_backend_http_responses_total{proxy="api",code="5xx"}[1m])) or vector(0)',
'reqps', 'HAProxy backend api: ответы 5xx (включая 503 балансировщика, когда нет готовых узлов).')
b.stat('HAProxy: активные серверы', 'haproxy_backend_active_servers{proxy="api"}', 'short',
'Активные серверы backend api по данным HAProxy PROMEX.')
b.ts('Задержка HTTP: общая p50/p95/p99', quantiles('http_server_request_duration_seconds', selector='{%s}' % BIZ),
's', 'histogram_quantile по суммированным бакетам всех реплик; перцентили реплик не усредняются.')
b.ts('Задержка HTTP по маршруту p50/p95/p99', quantiles('http_server_request_duration_seconds', by='http_route', selector='{%s}' % BIZ),
's', 'То же, с разбивкой по route template.')
b.row('Worker и задачи')
b.ts('Задачи по outcome', [('sum by (outcome)(rate(messenger_jobs_processed_total[1m]))', '{{outcome}}')], 'ops',
'messenger_jobs_processed_total по фактическому outcome (succeeded, retry, failed, ...), задач/с.')
b.ts('Длительность попытки задачи p50/p95/p99', quantiles('messenger_job_duration_seconds'), 's',
'От claim до commit одной попытки; не включает ожидание в очереди.')
b.ts('Time-to-ready p50/p95/p99', quantiles('messenger_attachment_time_to_ready_seconds'), 's',
'От durable acceptance (created_at задачи) до commit ready; включает очередь, ретраи и backoff. Измеряется на commit, до ACK и cleanup.')
b.ts('Worker: занято / ёмкость', [('sum(messenger_worker_jobs_active)', 'active'),
('max(messenger_worker_jobs_capacity)', 'capacity (WORKER_CONCURRENCY)')],
'short', 'Задач в работе против WORKER_CONCURRENCY; показатели не суммируются.')
b.row('Очередь и outbox (snapshot PostgreSQL, max по репликам)')
b.ts('Глубина очереди по состоянию', [('max by (state)(messenger_jobs_queue_depth)', '{{state}}')], 'short',
'Незавершённые задачи по state; обе реплики публикуют одно значение, поэтому max, а не sum.')
b.ts('Возраст самой старой задачи', [('max(messenger_jobs_queue_oldest_age_seconds)', 'oldest job age')], 's',
'Возраст ожидания backlog (alert MessengerJobsQueueLagGrowing: > 30 с), не время обработки.')
b.ts('Outbox: ожидающие и возраст', [('max(messenger_outbox_pending)', 'pending (шт.)'),
('max(messenger_outbox_oldest_age_seconds)', 'oldest age (с)')],
'short', 'Неопубликованные записи outbox (доступные к публикации) и возраст старейшей.')
b.ts('RabbitMQ: ready / unacked', [('sum(rabbitmq_queue_messages_ready)', 'ready'),
('sum(rabbitmq_queue_messages_unacked)', 'unacked')], 'short',
'Агрегат по очередям, rabbitmq_prometheus (порт 15692, внутри сети).')
b.row('PostgreSQL и процессы')
b.ts('Пул БД: used / idle / max', [
('sum by (db_client_connection_state, instance)(db_client_connection_count{job=~"messenger-.*",db_client_connection_pool_name="main"})', '{{db_client_connection_state}} {{instance}}'),
('max by (instance)(db_client_connection_max{job=~"messenger-.*",db_client_connection_pool_name="main"})', 'max {{instance}}')],
'short', 'Соединения основного пула по репликам.')
b.ts('Пул БД: ожидающие запросы и wait p95', [
('sum by (instance)(db_client_connection_pending_requests{job=~"messenger-.*"})', 'pending {{instance}}'),
('histogram_quantile(0.95, sum by (le)(rate(db_client_connection_wait_time_seconds_bucket{job=~"messenger-.*"}[1m])))', 'wait p95 (с)')],
'short', 'Очередь на получение соединения и p95 ожидания (секунды).')
b.ts('Операция БД p95 по db_operation_name', [(
'histogram_quantile(0.95, sum by (le, db_operation_name)(rate(db_client_operation_duration_seconds_bucket{job=~"messenger-.*"}[1m])))',
'{{db_operation_name}}')], 's', 'p95 длительности операций БД по типу операции.')
b.ts('CPU процессов (ядра)', [('sum by (job, instance)(rate(process_cpu_time_seconds_total{job=~"messenger-.*"}[1m]))', '{{job}} {{instance}}')],
'short', 'rate(process_cpu_time_seconds_total): 1.0 = одно логическое ядро.')
b.ts('RAM процессов', [('process_memory_usage_bytes{job=~"messenger-.*"}', '{{job}} {{instance}}'),
('v8js_memory_heap_used_bytes{job=~"messenger-.*"}', 'heap {{job}} {{instance}}')],
'bytes', 'Resident memory процесса и использованная куча V8.')
b.ts('Event loop delay p99', [('nodejs_eventloop_delay_p99_seconds{job=~"messenger-.*"}', '{{job}} {{instance}}')], 's',
'Задержка event loop (p99 окна, секунды).')
b.row('Логи (переход в трассу по TraceID)')
b.logs('Логи API', '{service_name="messenger-api"}', 'Структурные логи; trace_id — structured metadata, поле TraceID ведёт в Tempo.')
b.logs('Логи worker', '{service_name="messenger-worker"}', 'Структурные логи worker; trace_id ведёт в Tempo.')
return b.render()
def telemetry():
b = Board('messenger-telemetry', 'Messenger: telemetry pipeline')
b.row('Collector')
b.ts('Collector: принято', [
('sum(rate(otelcol_receiver_accepted_spans[1m]))', 'spans'),
('sum(rate(otelcol_receiver_accepted_log_records[1m]))', 'log records'),
('sum(rate(otelcol_receiver_accepted_metric_points[1m]))', 'metric points')],
'suffix:items/s', 'Элементов, принятых OTLP-receiver, в секунду (не байты).')
b.ts('Collector: отправлено', [
('sum(rate(otelcol_exporter_sent_spans[1m]))', 'spans'),
('sum(rate(otelcol_exporter_sent_log_records[1m]))', 'log records'),
('sum(rate(otelcol_exporter_sent_metric_points[1m]))', 'metric points')],
'suffix:items/s', 'Элементов, успешно отправленных exporter-ами в backend.')
b.ts('Collector: ошибки отправки и постановки в очередь', [
('sum by (exporter)(rate(otelcol_exporter_send_failed_spans[1m]))', 'send_failed spans {{exporter}}'),
('sum by (exporter)(rate(otelcol_exporter_send_failed_log_records[1m]))', 'send_failed logs {{exporter}}'),
('sum by (exporter)(rate(otelcol_exporter_send_failed_metric_points[1m]))', 'send_failed metrics {{exporter}}'),
('sum by (exporter)(rate(otelcol_exporter_enqueue_failed_spans[1m]))', 'enqueue_failed spans {{exporter}}'),
('sum by (exporter)(rate(otelcol_exporter_enqueue_failed_log_records[1m]))', 'enqueue_failed logs {{exporter}}'),
('sum by (exporter)(rate(otelcol_exporter_enqueue_failed_metric_points[1m]))', 'enqueue_failed metrics {{exporter}}')],
'suffix:items/s', 'Потери на выходе Collector. Нулевые серии могут отсутствовать до первой ошибки.')
b.ts('Collector: очередь / ёмкость', [
('max by (exporter)(otelcol_exporter_queue_size)', 'size {{exporter}}'),
('max by (exporter)(otelcol_exporter_queue_capacity)', 'capacity {{exporter}}')],
'short', 'Очередь sending_queue в запросах (batch), не в spans.')
b.ts('Collector: RSS', [('otelcol_process_memory_rss', 'RSS')], 'bytes',
'Resident set size процесса Collector; лимит контейнера 256 MiB, memory_limiter 204 MiB.')
b.ts('Приложение: экспорт телеметрии (items)', [
('sum by (signal, outcome)(rate(messenger_telemetry_export_items_total[1m]))', '{{signal}} {{outcome}}')],
'suffix:items/s', 'Элементов, дошедших до OTLP-exporter приложения (traces/logs). Не учёт метрик и не все pre-export drops.')
b.row('Backend-хранилища')
b.ts('Loki / Tempo: up', [('up{job=~"loki|tempo"}', '{{job}}')], 'short', '1 — scrape успешен.')
b.ts('Loki / Tempo: ingest', [('sum(rate(loki_distributor_bytes_received_total[1m]))', 'loki'),
('sum(rate(tempo_distributor_bytes_received_total[1m]))', 'tempo')],
'Bps', 'Байт, принятых distributor-ами, в секунду.')
b.ts('Prometheus: размер TSDB', [('prometheus_tsdb_storage_blocks_bytes', 'blocks'),
('prometheus_tsdb_wal_storage_size_bytes', 'wal')], 'bytes',
'Блоки и WAL локального TSDB (retention 7d).')
b.table('Состояние правил (ALERTS)', 'ALERTS{alertname=~"Messenger.*"}',
'Pending/firing alerts из метрики ALERTS. Отсутствие строк означает, что нет pending/firing при загруженных rules (правила проверяются через /api/v1/rules).')
return b.render()
def main():
OUT.mkdir(parents=True, exist_ok=True)
for name, board in (('messenger-overview', overview()),
('messenger-telemetry', telemetry())):
(OUT / (name + '.json')).write_text(
json.dumps(board, indent=2, ensure_ascii=False) + '\n')
print('wrote', OUT / (name + '.json'))
if __name__ == '__main__':
main()