Лабораторная работа 6

This commit is contained in:
2026-11-13 01:27:57 +03:00
parent 470d9d6f1e
commit 2dbdcf898c
218 changed files with 22057 additions and 37 deletions
+944
View File
@@ -0,0 +1,944 @@
{
"uid": "messenger-lab6",
"title": "Messenger lab6 — API, worker, очередь",
"tags": [
"lab6",
"messenger"
],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"editable": false,
"refresh": "10s",
"time": {
"from": "now-30m",
"to": "now"
},
"annotations": {
"list": []
},
"templating": {
"list": []
},
"panels": [
{
"type": "row",
"title": "API: RED (бизнес-запросы, health исключены)",
"id": 1,
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 0
}
},
{
"type": "timeseries",
"title": "RPS по маршруту и классу статуса",
"id": 2,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "rate(http_server_request_duration_seconds_count[1m]); класс статуса из http_response_status_code",
"gridPos": {
"h": 8,
"w": 8,
"x": 0,
"y": 1
},
"fieldConfig": {
"defaults": {
"unit": "reqps",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "sum by (http_route, status_class) (label_replace(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[1m]), \"status_class\", \"${1}xx\", \"http_response_status_code\", \"(\\\\d)..\"))",
"legendFormat": "{{http_route}} {{status_class}}",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Доля 5xx (SLI ошибок)",
"id": 3,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "numerator: 5xx; denominator: все бизнес-запросы. Порог алерта 5%",
"gridPos": {
"h": 8,
"w": 8,
"x": 8,
"y": 1
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 0.05
}
]
},
"custom": {
"thresholdsStyle": {
"mode": "line"
}
}
},
"overrides": []
},
"targets": [
{
"expr": "messenger:http_error_ratio:rate1m",
"legendFormat": "5xx / все, окно 1m",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Латентность p50 / p95 / p99 (из histogram)",
"id": 4,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "Квантили из buckets всех реплик (sum by le), не среднее p95 реплик",
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 1
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "p50",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "p95",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "p99",
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "p95 по маршруту",
"id": 5,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 9
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
"legendFormat": "{{http_route}}",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "stat",
"title": "SLO доступности, окно 1 ч (цель 99%)",
"id": 6,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "1 - 5xx/все за 1h",
"gridPos": {
"h": 8,
"w": 6,
"x": 12,
"y": 9
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": null
},
{
"color": "green",
"value": 0.99
}
]
}
},
"overrides": []
},
"targets": [
{
"expr": "messenger:http_availability:ratio1h",
"legendFormat": "availability 1h",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "stat",
"title": "SLO задержки: доля < 0.5 с, 1 ч (цель 95%)",
"id": 7,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 6,
"x": 18,
"y": 9
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "red",
"value": null
},
{
"color": "green",
"value": 0.95
}
]
}
},
"overrides": []
},
"targets": [
{
"expr": "messenger:http_fast_ratio:ratio1h",
"legendFormat": "fast 1h",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "row",
"title": "Worker и очередь attachments.jobs",
"id": 8,
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 17
}
},
{
"type": "timeseries",
"title": "Задания по исходу",
"id": 9,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "succeeded / retry / failed / noop / lease_lost / poison / error",
"gridPos": {
"h": 8,
"w": 8,
"x": 0,
"y": 18
},
"fieldConfig": {
"defaults": {
"unit": "ops",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Длительность задания p50 / p95 / p99",
"id": 10,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 8,
"x": 8,
"y": 18
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p99",
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Время до ready p50 / p95 (end-to-end)",
"id": 11,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "От COMMIT задания (ответ 202) до COMMIT ready",
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 18
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p50",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Глубина очереди",
"id": 12,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "Из PostgreSQL (публикуют API-реплики, max по репликам)",
"gridPos": {
"h": 8,
"w": 8,
"x": 0,
"y": 26
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "max by (state) (messenger_queue_depth{queue=\"attachments.jobs\"})",
"legendFormat": "{{state}}",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "max(messenger_outbox_pending{queue=\"attachments.jobs\"})",
"legendFormat": "outbox (не опубликовано)",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Возраст старейшего задания",
"id": 13,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "Порог алерта QueueLagGrowing: 60 с",
"gridPos": {
"h": 8,
"w": 8,
"x": 8,
"y": 26
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0,
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 60
}
]
},
"custom": {
"thresholdsStyle": {
"mode": "line"
}
}
},
"overrides": []
},
"targets": [
{
"expr": "max(messenger_queue_oldest_age_seconds{queue=\"attachments.jobs\"})",
"legendFormat": "oldest age",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Saturation worker (busy / capacity)",
"id": 14,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 26
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0
},
"overrides": [
{
"matcher": {
"id": "byName",
"options": "capacity (слотов)"
},
"properties": [
{
"id": "unit",
"value": "short"
},
{
"id": "custom.axisPlacement",
"value": "right"
}
]
}
]
},
"targets": [
{
"expr": "sum(messenger_worker_busy) / sum(messenger_worker_capacity)",
"legendFormat": "busy/capacity",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(messenger_worker_capacity)",
"legendFormat": "capacity (слотов)",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "row",
"title": "Ресурсы: DB pool, CPU, RAM",
"id": 15,
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 34
}
},
{
"type": "timeseries",
"title": "DB pool: занято / ожидают / максимум",
"id": 16,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 8,
"x": 0,
"y": 35
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "sum by (job, instance) (messenger_db_pool_connections{state=\"used\"})",
"legendFormat": "{{job}} {{instance}} used",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum by (job, instance) (messenger_db_pool_waiting)",
"legendFormat": "{{job}} {{instance}} waiting",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "max by (job) (messenger_db_pool_max)",
"legendFormat": "{{job}} max",
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "CPU процесса (ядра)",
"id": 17,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 8,
"x": 8,
"y": 35
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "rate(process_cpu_time_seconds_total{job=~\"messenger-.+\"}[1m])",
"legendFormat": "{{job}} {{instance}}",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "RSS процесса",
"id": 18,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 35
},
"fieldConfig": {
"defaults": {
"unit": "bytes",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "process_memory_rss_bytes{job=~\"messenger-.+\"}",
"legendFormat": "{{job}} {{instance}}",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "row",
"title": "Конвейер телеметрии (Collector)",
"id": 19,
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 43
}
},
{
"type": "timeseries",
"title": "Collector: принято / отправлено / потеряно (spans)",
"id": 20,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 44
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "sum(rate(otelcol_receiver_accepted_spans[1m]))",
"legendFormat": "accepted",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(rate(otelcol_exporter_sent_spans[1m]))",
"legendFormat": "sent",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "(sum(rate(otelcol_exporter_send_failed_spans[1m])) or vector(0)) + (sum(rate(otelcol_exporter_enqueue_failed_spans[1m])) or vector(0))",
"legendFormat": "lost",
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(rate(otelcol_receiver_refused_spans[1m]))",
"legendFormat": "refused (memory_limiter)",
"refId": "D",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "timeseries",
"title": "Collector: логи и очередь экспорта",
"id": 21,
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"description": "",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 44
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "sum(rate(otelcol_exporter_sent_log_records[1m]))",
"legendFormat": "logs sent",
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "(sum(rate(otelcol_exporter_send_failed_log_records[1m])) or vector(0)) + (sum(rate(otelcol_exporter_enqueue_failed_log_records[1m])) or vector(0))",
"legendFormat": "logs lost",
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "max by (exporter) (otelcol_exporter_queue_size)",
"legendFormat": "queue {{exporter}}",
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
]
},
{
"type": "row",
"title": "Логи и трассы",
"id": 22,
"collapsed": false,
"gridPos": {
"h": 1,
"w": 24,
"x": 0,
"y": 52
}
},
{
"type": "logs",
"title": "Логи WARNING/ERROR API и worker",
"id": 23,
"datasource": {
"type": "loki",
"uid": "loki"
},
"description": "",
"gridPos": {
"h": 10,
"w": 12,
"x": 0,
"y": 53
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"expr": "{service_name=~\"messenger-.+\"} | severity_text=~\"WARNING|ERROR|CRITICAL\"",
"queryType": "range",
"refId": "A",
"datasource": {
"type": "loki",
"uid": "loki"
}
}
],
"options": {
"showTime": true,
"wrapLogMessage": true,
"enableLogDetails": true,
"sortOrder": "Descending"
}
},
{
"type": "table",
"title": "Трассы обработки заданий (consumer spans)",
"id": 24,
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"description": "",
"gridPos": {
"h": 10,
"w": 12,
"x": 12,
"y": 53
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"query": "{resource.service.name=\"messenger-worker\" && kind=consumer}",
"queryType": "traceql",
"limit": 20,
"tableType": "traces",
"refId": "A",
"datasource": {
"type": "tempo",
"uid": "tempo"
}
}
]
}
]
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: messenger
folder: Messenger
type: file
disableDeletion: true
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,50 @@
# Grafana 11.4.0: источники данных (не хранит сигналы сама — только запросы и UI).
# Фиксированные uid: на них ссылаются dashboard и переходы trace <-> logs.
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:
# trace_id хранится как structured metadata записи -> кнопка перехода в Tempo.
derivedFields:
- name: trace_id
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: "$${__value.raw}"
urlDisplayLabel: "Открыть trace"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-5m"
spanEndTimeShift: "5m"
filterByTraceID: true
filterBySpanID: false
customQuery: true
# Все логи API и worker этой трассы (trace_id — structured metadata, не текст строки).
query: '{service_name=~"messenger-.+"} | trace_id="$${__trace.traceId}"'
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
+104
View File
@@ -0,0 +1,104 @@
# HAProxy 2.8 LTS — единственная публичная точка входа (lab3, дополнено в lab4).
#
# Обнаружение реплик: Docker DNS (127.0.0.11) отдаёт по имени сервиса `api`
# A-записи ВСЕХ запущенных контейнеров сервиса. server-template держит до 6 слотов
# и каждые 2 с синхронизирует их с DNS: новый контейнер (scale / rolling update)
# появляется сам, остановленный исчезает. Перезапуск LB при масштабировании не нужен.
#
# Исключение недоступного backend (активные проверки):
# GET /health/ready каждые inter=1s; после первой неудачи — fastinter=500ms;
# fall=2 неудачи подряд -> DOWN; rise=2 удачи -> UP; timeout check 1500ms.
# Время обнаружения:
# * graceful stop (реплика сразу отвечает 503): <= 1 с + 0.5 с ~ 1.5 с
# * crash / kill (соединение отклонено/сброшено): ~1.5 с
# * зависание без ответа: <= 1 + 1.5 + 0.5 + 1.5 = 4.5 с
# Пока реплика ещё не помечена DOWN, запрос к ней, не сумевший СОЕДИНИТЬСЯ
# (timeout connect 1s), повторяется на другой реплике (retries 2 + redispatch).
# Повторяются только ошибки установления соединения (retry-on conn-failure по
# умолчанию): запрос ещё не был отправлен, поэтому это безопасно и для POST.
# Уже отправленные POST LB не повторяет — это делает клиент с тем же
# Idempotency-Key (контракт запрещает прозрачные повторы POST /users, /chats).
#
# Согласование таймаутов:
# API: пул БД 3 с + statement_timeout 5 с = максимум ~8 с на запрос
# -> timeout server 10s; graceful shutdown API 10 с; drain API 3 с > 1.5 с.
# lab4: загрузка вложения (POST .../attachments) — до UPLOAD_READ_TIMEOUT_SECONDS
# 60 с чтения тела + очередь 5 с + S3 PUT (2 попытки по ~12 с) -> для этого
# пути timeout server 90s (http-request set-timeout), остальные — прежние 10 с.
# Скачивание идёт потоком, timeout server — это пауза между пакетами, не общая длительность.
# Docker stop_grace_period 20 с > drain 3 с + graceful 10 с.
global
log stdout format raw local0 info
maxconn 2000
resolvers docker
nameserver dns1 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 2s
hold nx 2s
hold other 2s
hold refused 2s
hold timeout 2s
# 8 КБ: в ответ DNS помещаются A-записи всех слотов.
accepted_payload_size 8192
defaults
mode http
log global
option httplog
option dontlognull
option redispatch 1
retries 2
timeout connect 1s
timeout client 30s
timeout server 10s
timeout http-request 10s
timeout http-keep-alive 10s
timeout queue 3s
timeout check 1500ms
default-server inter 1s fastinter 500ms downinter 2s fall 2 rise 2
frontend public
bind :8080
# Сквозной идентификатор запроса: HAProxy генерирует X-Request-Id, если клиент
# не прислал свой; API отражает его в ответе и в теле ошибок, LB — в логе.
unique-id-format %{+X}o\ %ci%cp-%fp-%Ts%ms-%rt-%pid
http-request set-header X-Request-Id %[unique-id] unless { req.hdr(X-Request-Id) -m found }
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[capture.req.hdr(0)] inst=%[capture.res.hdr(0)] \"%HM %HPO\""
http-request capture req.hdr(X-Request-Id) len 64
declare capture response len 32
http-response capture res.hdr(X-Instance-Id) id 0
default_backend api
backend api
balance roundrobin
# lab4: только загрузка вложения получает длинный timeout server (см. выше).
acl is_upload method POST
acl is_upload_path path_reg ^/api/v1/chats/[^/]+/attachments$
http-request set-timeout server 90s if is_upload is_upload_path
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host lb
http-check expect status 200
# Ответы, которые формирует сам LB (нет ни одной готовой реплики, таймаут),
# — в общем JSON-формате ошибок контракта, с тем же X-Request-Id.
http-error status 503 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"No API instance is available\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}"
http-error status 504 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API instance timeout\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}"
http-error status 502 content-type application/json hdr X-Request-Id "%[req.hdr(X-Request-Id)]" lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Bad gateway\",\"request_id\":\"%[req.hdr(X-Request-Id)]\"}}"
# До 6 реплик (в т.ч. N+1 во время rolling update). init-addr none: LB стартует,
# даже если реплик ещё нет; слоты без адреса находятся в MAINT.
server-template api 1-6 api:8080 check resolvers docker init-addr none resolve-prefer ipv4
# Внутренняя страница состояния (UP/DOWN по репликам) — только чтение.
# Публикуется на 127.0.0.1:8404 хоста; используется scripts/ops.py.
frontend stats
bind :8404
monitor-uri /lb-health
stats enable
stats uri /stats
stats refresh 2s
stats show-legends
http-request set-log-level silent
+45
View File
@@ -0,0 +1,45 @@
# Loki 3.3.2 (single binary) — хранилище ЛОГОВ. Приём — native OTLP (/otlp) от Collector.
# Resource-атрибуты service.name / service.instance.id становятся index labels
# (service_name, service_instance_id), атрибуты записи (event, request_id, trace_id,
# span_id, severity) — structured metadata (не labels: низкая кардинальность индекса).
auth_enabled: false
server:
http_listen_port: 3100
log_level: warn
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: "2024-01-01"
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 168h
# Защита от взрыва: не больше 2 MiB/s на tenant на учебном стенде.
ingestion_rate_mb: 2
ingestion_burst_size_mb: 4
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+96
View File
@@ -0,0 +1,96 @@
# OpenTelemetry Collector (contrib 0.115.1) — получатель/обработчик/экспортёр, НЕ хранилище.
#
# API/worker --OTLP/HTTP :4318--> receivers.otlp
# traces -> memory_limiter -> batch -> otlp/tempo (Tempo, OTLP gRPC)
# metrics -> memory_limiter -> batch -> prometheus (pull: Prometheus скрейпит :8889)
# logs -> memory_limiter -> batch -> otlphttp/loki (Loki native OTLP /otlp)
#
# Ограничение памяти и буферов (поведение при недоступном backend):
# * memory_limiter: при > limit_mib collector отказывает новым данным (SDK получает
# ошибку и отбрасывает свой батч), принудительный GC; контейнер ограничен 256M.
# * sending_queue: в памяти, не больше queue_size батчей на exporter; при
# переполнении новые батчи отбрасываются (otelcol_exporter_enqueue_failed_*).
# * retry_on_failure: повтор не дольше max_elapsed_time, затем батч отбрасывается
# (otelcol_exporter_send_failed_*). Бесконечного накопления нет.
# Порты наружу не публикуются: 4317/4318/8888/8889 доступны только в сети telemetry.
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: 180
spike_limit_mib: 40
batch:
send_batch_size: 512
send_batch_max_size: 1024
timeout: 2s
exporters:
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 20
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 20
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
prometheus:
endpoint: 0.0.0.0:8889
# job = service.name, instance = service.instance.id; прочие resource-атрибуты — в target_info.
resource_to_telemetry_conversion:
enabled: false
# Серии остановленной реплики исчезают через 5 минут (а не висят вечно).
metric_expiration: 5m
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
logs:
level: info
metrics:
level: normal
address: 0.0.0.0:8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
+24
View File
@@ -0,0 +1,24 @@
# Prometheus v2.55.1 — хранилище МЕТРИК (TSDB на volume promdata, retention 7d)
# и вычислитель alert rules (состояние firing/resolved видно в /alerts и Grafana;
# доставка наружу не настроена — Alertmanager не нужен по заданию).
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
# Метрики приложения, которые Collector получил по OTLP. honor_labels: сохраняем
# job=<service.name> и instance=<service.instance.id>, выставленные exporter'ом.
- job_name: otel-collector-app
honor_labels: true
static_configs:
- targets: ["otel-collector:8889"]
# Собственные метрики Collector: принятые/отброшенные/неотправленные spans, logs, points.
- job_name: otel-collector-self
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
+66
View File
@@ -0,0 +1,66 @@
# SLI/SLO и alert rules lab6. Единицы: доли (0..1), секунды.
#
# SLI доступности API: доля бизнес-запросов (health исключены инструментацией)
# без ответа 5xx. 4xx (неверный пароль, 404, 409) — ошибка клиента, не сервиса.
# SLO: 99% запросов без 5xx в скользящем окне 1 ч (учебный стенд; бюджет 1%).
# SLI задержки: доля запросов быстрее 0.5 с (корзина le="0.5" гистограммы); SLO 95% за 1 ч.
# SLI очереди: возраст старейшего незавершённого задания; цель < 60 с.
groups:
- name: messenger-sli
interval: 10s
rules:
- record: messenger:http_requests:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[1m]))
- record: messenger:http_errors_5xx:rate1m
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code=~"5.."}[1m])) or vector(0)
- record: messenger:http_error_ratio:rate1m
expr: messenger:http_errors_5xx:rate1m / messenger:http_requests:rate1m
- record: messenger:http_availability:ratio1h
expr: |
1 - (
(sum(increase(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code=~"5.."}[1h])) or vector(0))
/ sum(increase(http_server_request_duration_seconds_count{job="messenger-api"}[1h]))
)
- record: messenger:http_fast_ratio:ratio1h
expr: |
sum(increase(http_server_request_duration_seconds_bucket{job="messenger-api",le="0.5"}[1h]))
/ sum(increase(http_server_request_duration_seconds_count{job="messenger-api"}[1h]))
- name: messenger-alerts
rules:
- alert: ApiHighErrorRate
# >5% ответов 5xx за 1 мин при заметном трафике (>= 0.2 RPS), держится 1 мин.
expr: messenger:http_error_ratio:rate1m > 0.05 and messenger:http_requests:rate1m >= 0.2
for: 1m
labels:
severity: page
annotations:
summary: "API: доля 5xx {{ $value | humanizePercentage }} (> 5%)"
description: "Бизнес-запросы messenger-api отвечают 5xx. Окно 1m, порог 5%, for 1m."
runbook: "docs/runbooks.md#apihigherrorrate"
- alert: QueueLagGrowing
# Старейшее незавершённое задание старше 60 с — worker не успевает или стоит.
expr: max(messenger_queue_oldest_age_seconds{queue="attachments.jobs"}) > 60
for: 30s
labels:
severity: page
annotations:
summary: "Очередь attachments.jobs: старейшее задание {{ $value | humanizeDuration }}"
description: "Возраст старейшего queued/processing задания > 60 с в течение 30 с."
runbook: "docs/runbooks.md#queuelaggrowing"
- alert: TelemetryExportFailing
# Collector не может отправить данные в backend (Tempo/Loki недоступны).
# Счётчики появляются лениво (enqueue_failed — после первого отказа): "or vector(0)".
expr: |
(sum(rate(otelcol_exporter_send_failed_spans[1m])) or vector(0))
+ (sum(rate(otelcol_exporter_send_failed_log_records[1m])) or vector(0))
+ (sum(rate(otelcol_exporter_enqueue_failed_spans[1m])) or vector(0))
+ (sum(rate(otelcol_exporter_enqueue_failed_log_records[1m])) or vector(0)) > 0
for: 1m
labels:
severity: ticket
annotations:
summary: "Collector теряет telemetry (backend недоступен)"
runbook: "docs/runbooks.md#telemetryexportfailing"
+32
View File
@@ -0,0 +1,32 @@
# Tempo 2.6.1 (monolithic) — хранилище ТРАСС. Приём OTLP gRPC от Collector.
# Блоки на volume tempodata (local backend), хранение 72 ч.
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: 5m
compactor:
compaction:
block_retention: 72h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false