ЛР 6 — БПИ2303 — Лазарев — на 4

Перенесена реализация lab5 (API x2 за HAProxy, PostgreSQL, SeaweedFS S3,
RabbitMQ, relay outbox, worker x2, janitor) без изменения бизнес-API.

Наблюдаемость:
- OpenTelemetry SDK в API, relay, worker, janitor: traces, metrics, logs
  по OTLP/HTTP; структурные JSON-логи с trace_id/span_id
- OTel Collector (memory_limiter, batch, ограниченные очереди и retry),
  Prometheus (метрики, alert rules), Loki (логи), Tempo (трассы),
  Grafana с provisioning datasources и dashboard
- W3C trace context API -> outbox -> RabbitMQ -> worker (parent-child,
  включая retry); метрики очереди, пула БД, загрузки worker, CPU/RAM
- SLI/SLO, 10 alert rules с unit-тестами promtool и runbooks
- инциденты: остановка worker, блокировка БД, отказ telemetry backend;
  по наблюдениям исправлен простой worker в цикле AMQP (разбор x2.4)
This commit is contained in:
2026-11-17 10:59:41 +03:00
parent 470d9d6f1e
commit c199f6632a
116 changed files with 22733 additions and 39 deletions
+323
View File
@@ -0,0 +1,323 @@
#!/usr/bin/env python3
"""Генератор импортируемого dashboard Grafana: infra/grafana/dashboards/messenger.json.
JSON лежит в Git и подхватывается provisioning-ом; этот скрипт — воспроизводимый способ его
изменить (python3 scripts/build_dashboard.py). Только стандартная библиотека.
Все запросы ссылаются на реальные имена метрик (см. REPORT.md «Схема сигналов»).
Перцентили — histogram_quantile по sum by (le) buckets всех реплик, не среднее p95.
"""
import json
from pathlib import Path
OUT = Path(__file__).resolve().parents[1] / "infra/grafana/dashboards/messenger.json"
PROM = {"type": "prometheus", "uid": "prometheus"}
LOKI = {"type": "loki", "uid": "loki"}
TEMPO = {"type": "tempo", "uid": "tempo"}
API = 'job="messenger-api", instance=~"$instance"'
BUSINESS = API + ', http_route!~"/health/.*|unmatched"'
_panels = []
_id = [0]
_pos = {"x": 0, "y": 0, "h": 0}
def _next_id():
_id[0] += 1
return _id[0]
def place(w, h):
if _pos["x"] + w > 24:
_pos["x"] = 0
_pos["y"] += _pos["h"]
_pos["h"] = 0
g = {"x": _pos["x"], "y": _pos["y"], "w": w, "h": h}
_pos["x"] += w
_pos["h"] = max(_pos["h"], h)
return g
def row(title):
_pos["x"] = 0
_pos["y"] += _pos["h"]
_pos["h"] = 0
_panels.append({"type": "row", "id": _next_id(), "title": title, "collapsed": False,
"gridPos": {"x": 0, "y": _pos["y"], "w": 24, "h": 1}, "panels": []})
_pos["y"] += 1
def target(expr, legend="", ref="A", exemplar=False, instant=False):
t = {"datasource": PROM, "expr": expr, "legendFormat": legend or "__auto", "refId": ref,
"range": not instant, "instant": instant}
if exemplar:
t["exemplar"] = True
return t
def ts(title, targets, unit="short", w=8, h=8, description="", stack=False, min0=True, thresholds=None):
refs = "ABCDEFGHIJ"
tg = [target(*t[:2], ref=refs[i], exemplar=(len(t) > 2 and t[2])) for i, t in enumerate(targets)]
p = {"type": "timeseries", "id": _next_id(), "title": title, "description": description,
"datasource": PROM, "gridPos": place(w, h), "targets": tg,
"fieldConfig": {"defaults": {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10,
"showPoints": "never",
"stacking": {"mode": "normal" if stack else "none"}},
**({"min": 0} if min0 else {})},
"overrides": []},
"options": {"legend": {"displayMode": "table", "placement": "bottom", "calcs": ["lastNotNull", "max"]},
"tooltip": {"mode": "multi", "sort": "desc"}}}
if thresholds:
p["fieldConfig"]["defaults"]["thresholds"] = {"mode": "absolute", "steps": thresholds}
p["fieldConfig"]["defaults"]["custom"]["thresholdsStyle"] = {"mode": "line+area"}
_panels.append(p)
def stat(title, expr, unit="short", w=3, h=4, steps=None, description="", decimals=None):
p = {"type": "stat", "id": _next_id(), "title": title, "description": description, "datasource": PROM,
"gridPos": place(w, h), "targets": [target(expr, "", instant=True)],
"fieldConfig": {"defaults": {"unit": unit, "thresholds": {"mode": "absolute", "steps": steps or [
{"color": "green", "value": None}]}}, "overrides": []},
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False},
"colorMode": "background", "graphMode": "area", "textMode": "value"}}
if decimals is not None:
p["fieldConfig"]["defaults"]["decimals"] = decimals
_panels.append(p)
def build():
# ------------------------------------------------------------------ обзор
row("Обзор и SLO")
stat("RPS бизнес-запросов", "messenger:http_requests:rate2m", "reqps",
description="sum(rate(http_server_request_duration_seconds_count{job=messenger-api, без /health}[2m]))")
stat("5xx, доля (2m)", "messenger:http_error_ratio:rate2m", "percentunit", decimals=2,
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 0.01}, {"color": "red", "value": 0.05}],
description="Числитель: 5xx бизнес-запросов; знаменатель: все бизнес-запросы (без /health, unmatched).")
stat("p95 API (5m)", "messenger:http_latency_seconds:p95_5m", "s", decimals=3,
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 0.5}, {"color": "red", "value": 1}])
stat("SLO доступности, 7d", "messenger:slo_availability:ratio_7d", "percentunit", decimals=3,
steps=[{"color": "red", "value": None}, {"color": "green", "value": 0.995}],
description="SLO: 99.5 % бизнес-запросов без 5xx за скользящие 7 дней.")
stat("Остаток error budget, 7d", "messenger:slo_availability:error_budget_remaining_7d", "percentunit",
decimals=1, steps=[{"color": "red", "value": None}, {"color": "orange", "value": 0.25},
{"color": "green", "value": 0.5}])
stat("Time to ready p95", "messenger:time_to_ready_seconds:p95_5m", "s", decimals=2,
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 10}, {"color": "red", "value": 30}],
description="От durable acceptance (COMMIT enqueue) до COMMIT ready. SLO: 99 % не дольше 30 с.")
stat("Ready lag очереди", "max(messenger_jobs_ready_lag_seconds) or vector(0)", "s", decimals=0,
steps=[{"color": "green", "value": None}, {"color": "orange", "value": 10}, {"color": "red", "value": 30}],
description="Сколько ждёт worker самое старое созревшее задание (PostgreSQL jobs).")
stat("Alerts firing", 'count(ALERTS{alertstate="firing"}) or vector(0)', "short",
steps=[{"color": "green", "value": None}, {"color": "red", "value": 1}])
_panels.append({
"type": "state-timeline", "id": _next_id(), "title": "История alerts (pending/firing -> resolved)",
"datasource": PROM, "gridPos": place(24, 6),
"targets": [target('max by (alertname, source, alertstate) (ALERTS)', "{{alertname}} {{source}} {{alertstate}}")],
"fieldConfig": {"defaults": {"color": {"mode": "thresholds"},
"thresholds": {"mode": "absolute", "steps": [
{"color": "transparent", "value": None}, {"color": "red", "value": 1}]}},
"overrides": []},
"options": {"showValue": "never", "mergeValues": True, "rowHeight": 0.8,
"legend": {"showLegend": False}}})
# ------------------------------------------------------------------ API
row("API: трафик, ошибки, задержка")
ts("RPS по маршруту", [("sum by (http_route) (rate(http_server_request_duration_seconds_count{%s}[1m]))" % API,
"{{http_route}}")], "reqps", stack=True)
ts("Ответы по классу статуса", [(
"sum by (http_response_status_class) (rate(http_server_request_duration_seconds_count{%s}[1m]))" % BUSINESS,
"{{http_response_status_class}}")], "reqps", stack=True)
ts("Доля 5xx: API и LB", [
("messenger:http_error_ratio:rate2m", "API (без /health)"),
("messenger:lb_error_ratio:rate2m", "HAProxy fe_api")], "percentunit",
thresholds=[{"color": "transparent", "value": None}, {"color": "red", "value": 0.05}],
description="Если БД недоступна, реплики не ready и 503 отдаёт LB: эти запросы видны только в метрике LB.")
ts("Задержка API p50/p95/p99 (из histogram)", [
("histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{%s}[1m])))" % BUSINESS, "p50", True),
("histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{%s}[1m])))" % BUSINESS, "p95", True),
("histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{%s}[1m])))" % BUSINESS, "p99", True)],
"s", w=12, description="Точки-exemplars ведут в трассу Tempo конкретного запроса.")
ts("p95 по маршруту", [(
"histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{%s}[5m])))" % BUSINESS,
"{{http_route}}")], "s", w=12)
ts("5xx по причине (error.type)", [(
'sum by (error_type, http_route) (rate(http_server_request_duration_seconds_count{%s, http_response_status_class="5xx"}[1m]))' % API,
"{{error_type}} {{http_route}}")], "reqps", stack=True)
ts("Запросы в обработке (saturation API)", [
("sum by (instance) (http_server_active_requests{%s})" % API, "{{instance}}")], "short")
ts("HAProxy: UP-реплики и очередь LB", [
('haproxy_backend_active_servers{proxy="be_api"}', "UP реплик"),
('haproxy_backend_current_queue{proxy="be_api"}', "очередь LB")], "short")
# ------------------------------------------------------------------ worker
row("Worker и очередь заданий")
ts("Задания по исходу (в минуту)", [(
"sum by (messenger_job_outcome) (increase(messenger_jobs_processed_total[1m]))", "{{messenger_job_outcome}}")],
"short", stack=True, description="ready / retry / failed / duplicate / lease_lost / rejected / requeued")
ts("Длительность обработки job p50/p95/p99", [
('histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket{messenger_job_outcome="ready"}[5m])))', "p50", True),
('histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{messenger_job_outcome="ready"}[5m])))', "p95", True),
('histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{messenger_job_outcome="ready"}[5m])))', "p99", True)],
"s")
ts("Time to ready p50/p95/p99", [
('histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))', "p50", True),
('histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))', "p95", True),
('histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{outcome="ready"}[5m])))', "p99", True)],
"s", description="Backlog-ожидание + обработка: время от 202 (COMMIT) до ready.")
ts("Глубина очереди: PostgreSQL и RabbitMQ", [
('max by (messenger_job_status) (messenger_jobs_count{messenger_job_status=~"queued|processing"})', "jobs {{messenger_job_status}} (БД)"),
('max(messenger_outbox_pending)', "outbox не опубликовано"),
('sum(rabbitmq_detailed_queue_messages_ready{queue="attachments.process.v1"})', "RabbitMQ ready"),
('sum(rabbitmq_detailed_queue_messages_unacked{queue="attachments.process.v1"})', "RabbitMQ unacked"),
('sum(rabbitmq_detailed_queue_messages{queue="attachments.dlq"})', "DLQ")], "short")
ts("Возраст старейшего задания и lag", [
('max by (messenger_job_status) (messenger_jobs_oldest_age_seconds)', "oldest {{messenger_job_status}}"),
("max(messenger_jobs_ready_lag_seconds)", "ready lag"),
("max(messenger_outbox_oldest_age_seconds)", "outbox oldest")], "s",
thresholds=[{"color": "transparent", "value": None}, {"color": "red", "value": 30}])
ts("Ожидание в очереди p95 (до claim)", [
("histogram_quantile(0.95, sum by (le) (rate(messenger_job_queue_wait_seconds_bucket[5m])))", "p95 queue wait"),
("histogram_quantile(0.95, sum by (le) (rate(messenger_outbox_publish_delay_seconds_bucket[5m])))", "p95 outbox -> broker")],
"s", description="Backlog (сколько ждут) отдельно от processing latency (сколько обрабатываются).")
ts("Saturation worker: занятость потребителей", [
("sum(rate(messenger_worker_busy_time_seconds_total[1m])) / sum(last_over_time(messenger_worker_capacity[30s]))", "utilization (busy_time/capacity)"),
("sum(messenger_worker_busy) / sum(last_over_time(messenger_worker_capacity[30s]))", "busy/capacity (мгновенно)")],
"percentunit", description="1.0 = все WORKER_CONCURRENCY потоков всех реплик заняты; очередь растёт быстрее обработки.")
ts("Relay: публикации outbox", [
("sum by (outcome) (rate(messenger_outbox_published_total[1m]))", "{{outcome}}")], "short")
# ------------------------------------------------------------------ DB / S3
row("PostgreSQL и S3")
ts("Пул соединений API: used / idle / max", [
('sum by (instance, db_client_connection_state) (db_client_connection_count{%s})' % API,
"{{instance}} {{db_client_connection_state}}"),
('max(db_client_connection_max{%s})' % API, "max на реплику")], "short")
ts("Ожидающие соединение и таймауты пула", [
('sum by (instance) (db_client_connection_pending_requests{%s})' % API, "pending {{instance}}"),
('sum by (instance) (increase(db_client_connection_timeouts_total{%s}[1m]))' % API, "timeouts/мин {{instance}}")],
"short")
ts("Ожидание соединения пула p95", [
('histogram_quantile(0.95, sum by (le) (rate(db_client_connection_wait_time_seconds_bucket{%s}[1m])))' % API, "p95 wait")],
"s")
ts("Операции БД p95 по операции (API)", [
('histogram_quantile(0.95, sum by (le, db_operation_name) (rate(db_client_operation_duration_seconds_bucket{%s}[1m])))' % API,
"{{db_operation_name}}")], "s", w=12)
ts("Операции БД worker/relay p95", [
('histogram_quantile(0.95, sum by (le, db_operation_name) (rate(db_client_operation_duration_seconds_bucket{job=~"messenger-worker|messenger-relay"}[5m])))',
"{{db_operation_name}}")], "s", w=12)
ts("Ошибки операций БД", [
('sum by (job, db_operation_name, error_type) (rate(db_client_operation_duration_seconds_count{error_type!=""}[1m]))',
"{{job}} {{db_operation_name}} {{error_type}}")], "short")
ts("S3 p95 по операции", [
('histogram_quantile(0.95, sum by (le, messenger_s3_operation) (rate(messenger_s3_operation_duration_seconds_bucket[5m])))',
"{{messenger_s3_operation}}")], "s")
ts("S3 ошибки", [
('sum by (job, messenger_s3_operation, outcome) (rate(messenger_s3_operation_duration_seconds_count{outcome!="ok"}[1m]))',
"{{job}} {{messenger_s3_operation}} {{outcome}}")], "short")
# ------------------------------------------------------------------ ресурсы
row("Ресурсы контейнеров (CPU/RAM)")
ts("CPU, ядер (cgroup контейнера)", [
("sum by (job, instance) (rate(container_cpu_time_seconds_total[1m]))", "{{job}} {{instance}}")], "short", w=12)
ts("CPU saturation: доля лимита", [
("rate(container_cpu_time_seconds_total[1m]) / on(job, instance) container_cpu_limit", "{{job}} {{instance}}")],
"percentunit", w=12)
ts("Память контейнеров приложений", [
("container_memory_usage_bytes", "{{job}} {{instance}}")], "bytes", w=12)
ts("Память: доля лимита", [
("container_memory_usage_bytes / on(job, instance) container_memory_limit_bytes", "{{job}} {{instance}}")],
"percentunit", w=12)
ts("Память telemetry-стека (RSS)", [
('process_resident_memory_bytes{job=~"prometheus|loki|tempo"}', "{{job}}"),
('{__name__=~"otelcol_process_memory_rss(_bytes)?"}', "otel-collector RSS (вкл. страницы бинарника)"),
('otelcol_process_runtime_heap_alloc_bytes', "otel-collector Go heap"),
('rabbitmq_process_resident_memory_bytes', "rabbitmq")], "bytes", w=12)
ts("CPU telemetry-стека", [
('rate(process_cpu_seconds_total{job=~"prometheus|loki|tempo"}[1m])', "{{job}}"),
('rate({__name__=~"otelcol_process_cpu_seconds(_total)?"}[1m])', "otel-collector")], "short", w=12)
# ------------------------------------------------------------------ telemetry
row("Конвейер телеметрии (потери)")
ts("Collector: принято / отправлено / потеряно (spans)", [
('sum(rate({__name__=~"otelcol_receiver_accepted_spans(_total)?"}[1m]))', "принято"),
('sum(rate({__name__=~"otelcol_exporter_sent_spans(_total)?"}[1m]))', "отправлено в Tempo"),
('sum(rate({__name__=~"otelcol_exporter_send_failed_spans(_total)?"}[1m]))', "ошибка отправки"),
('sum(rate({__name__=~"otelcol_exporter_enqueue_failed_spans(_total)?"}[1m]))', "очередь полна (потеря)"),
('sum(rate({__name__=~"otelcol_receiver_refused_spans(_total)?"}[1m]))', "отказ приёма (memory_limiter)")], "short")
ts("Collector: логи", [
('sum(rate({__name__=~"otelcol_receiver_accepted_log_records(_total)?"}[1m]))', "принято"),
('sum(rate({__name__=~"otelcol_exporter_sent_log_records(_total)?"}[1m]))', "отправлено в Loki"),
('sum(rate({__name__=~"otelcol_exporter_send_failed_log_records(_total)?"}[1m]))', "ошибка отправки"),
('sum(rate({__name__=~"otelcol_exporter_enqueue_failed_log_records(_total)?"}[1m]))', "очередь полна (потеря)")], "short")
ts("Collector: очередь экспортёров", [
("max by (exporter) (otelcol_exporter_queue_size)", "size {{exporter}}"),
("max by (exporter) (otelcol_exporter_queue_capacity)", "capacity {{exporter}}")], "short")
ts("SDK приложений: потери на стороне процесса", [
('sum by (job, error_type) (rate(otel_sdk_processor_span_processed_total{error_type!=""}[1m]))', "spans dropped {{job}} {{error_type}}"),
('sum by (job, error_type) (rate(otel_sdk_processor_log_processed_total{error_type!=""}[1m]))', "logs dropped {{job}} {{error_type}}"),
('sum by (job, error_type) (rate(otel_sdk_exporter_span_exported_total{error_type!=""}[1m]))', "span export failed {{job}} {{error_type}}")],
"short", w=12)
ts("SDK: заполнение очереди BatchSpanProcessor", [
("max by (job, instance) (otel_sdk_processor_span_queue_size)", "{{job}} {{instance}}"),
("max(otel_sdk_processor_span_queue_capacity)", "capacity")], "short", w=12)
# ------------------------------------------------------------------ logs / traces
row("Логи и трассы")
_panels.append({
"type": "logs", "id": _next_id(), "title": "Логи WARN/ERROR приложений (Loki)", "datasource": LOKI,
"gridPos": place(24, 10),
"targets": [{"datasource": LOKI, "refId": "A", "queryType": "range",
"expr": '{service_name=~"messenger-.+"} | severity_text=~"WARN.*|ERROR.*|CRITICAL"'}],
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending",
"dedupStrategy": "none", "prettifyLogMessage": False}})
_panels.append({
"type": "logs", "id": _next_id(), "title": "HTTP 5xx (event=http.request)", "datasource": LOKI,
"gridPos": place(12, 10),
"targets": [{"datasource": LOKI, "refId": "A", "queryType": "range",
"expr": '{service_name="messenger-api"} | event="http.request" | http_response_status_code >= 500'}],
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending"}})
_panels.append({
"type": "table", "id": _next_id(), "title": "Последние трассы обработки заданий (Tempo)", "datasource": TEMPO,
"gridPos": place(12, 10),
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20, "tableType": "traces",
"query": '{ resource.service.name = "messenger-worker" && name = "attachments.process.v1 process" }'}]})
_panels.append({
"type": "table", "id": _next_id(), "title": "Медленные запросы API > 1 s (Tempo)", "datasource": TEMPO,
"gridPos": place(12, 10),
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20, "tableType": "traces",
"query": '{ resource.service.name = "messenger-api" && kind = server && duration > 1s }'}]})
_panels.append({
"type": "table", "id": _next_id(), "title": "Трассы с ошибкой (Tempo)", "datasource": TEMPO,
"gridPos": place(12, 10),
"targets": [{"datasource": TEMPO, "refId": "A", "queryType": "traceql", "limit": 20, "tableType": "traces",
"query": '{ status = error }'}]})
return {
"uid": "messenger-overview",
"title": "Messenger — наблюдаемость (lab6)",
"description": "API, worker, очередь, PostgreSQL, S3, ресурсы, конвейер телеметрии. Provisioning из Git.",
"tags": ["messenger", "lab6", "otel"],
"timezone": "browser",
"editable": False,
"graphTooltip": 1,
"refresh": "10s",
"schemaVersion": 39,
"version": 1,
"time": {"from": "now-30m", "to": "now"},
"templating": {"list": [{
"name": "instance", "label": "API-реплика", "type": "query", "datasource": PROM,
"query": {"query": 'label_values(http_server_request_duration_seconds_count{job="messenger-api"}, instance)',
"refId": "PrometheusVariableQueryEditor-VariableQuery"},
"definition": 'label_values(http_server_request_duration_seconds_count{job="messenger-api"}, instance)',
"includeAll": True, "multi": True, "allValue": ".*", "current": {"text": "All", "value": "$__all"},
"refresh": 2, "sort": 1}]},
"annotations": {"list": [{
"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"}, "enable": True, "hide": True,
"iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts", "type": "dashboard"}]},
"panels": _panels,
}
if __name__ == "__main__":
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(build(), ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
print("written %s (%d panels)" % (OUT.relative_to(OUT.parents[3]), len(_panels)))
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
# Офлайн-проверка конфигураций телеметрии теми же образами, что и стенд (сеть не нужна):
# promtool check config + check rules + unit-тесты alert rules,
# otelcol-contrib validate, loki -verify-config.
# Использование: scripts/check_rules.sh (код возврата 0 — всё валидно)
set -eu
cd "$(dirname "$0")/.."
img() { grep -E "^\s+image: $1" compose.yaml | head -1 | awk '{print $2}'; }
PROM=$(img prom/prometheus)
OTEL=$(img otel/opentelemetry-collector-contrib)
LOKI=$(img grafana/loki)
echo "== promtool check config ($PROM)"
docker run --rm -v "$PWD/infra/prometheus:/etc/prometheus:ro" --entrypoint promtool "$PROM" check config /etc/prometheus/prometheus.yml
echo "== promtool test rules"
docker run --rm -v "$PWD/infra/prometheus:/w:ro" -w /w/tests --entrypoint promtool "$PROM" test rules messenger.test.yml
echo "== otelcol validate ($OTEL)"
docker run --rm -v "$PWD/infra/otel/collector.yaml:/c.yaml:ro" "$OTEL" validate --config=/c.yaml && echo "collector config OK"
echo "== loki -verify-config ($LOKI)"
docker run --rm -v "$PWD/infra/loki/loki.yaml:/c.yaml:ro" "$LOKI" -config.file=/c.yaml -verify-config && echo "loki config OK"
echo "== dashboard JSON is up to date with scripts/build_dashboard.py"
tmp=$(mktemp)
cp infra/grafana/dashboards/messenger.json "$tmp"
python3 scripts/build_dashboard.py >/dev/null
cmp -s "$tmp" infra/grafana/dashboards/messenger.json && echo "dashboard OK" || { echo "dashboard JSON differs from generator" >&2; exit 1; }
+50
View File
@@ -0,0 +1,50 @@
#!/bin/sh
# Уровень 4: ПОСЛЕДОВАТЕЛЬНО останавливает КАЖДУЮ API-реплику под нагрузкой,
# восстанавливая предыдущую перед следующей. Режимы:
# stop — docker stop (SIGTERM -> graceful drain), штатная остановка/деплой;
# kill — docker kill (SIGKILL), внезапное падение процесса без drain.
# Результаты: evidence/failover-<mode>-<container>.json (+ .action.log).
# Использование: scripts/failover-each.sh [stop|kill] ... (по умолчанию: stop kill)
set -eu
cd "$(dirname "$0")/.."
MODES=${*:-stop kill}
CONCURRENCY=${CONCURRENCY:-8}
DURATION=${DURATION:-40}
mkdir -p evidence
wait_all_up() {
# API-контейнеры healthy и HAProxy видит их все UP (rise 2 * inter 1s).
./scripts/start-all.sh >/dev/null
n=$(docker compose ps -q api | wc -l | tr -d ' ')
for _ in $(seq 1 60); do
up=$(curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' ')
[ "$up" -ge "$n" ] && return 0
sleep 1
done
echo "HAProxy did not mark all $n api servers UP" >&2; return 1
}
wait_all_up
# Список фиксируется один раз: остановленная реплика пропала бы из `docker compose ps`.
NAMES=$(docker compose ps --format '{{.Name}}' api | sort)
for mode in $MODES; do
for name in $NAMES; do
wait_all_up
cid=$(docker inspect -f '{{.Id}}' "$name"); short=$(echo "$cid" | cut -c1-12)
case $mode in
stop) action="docker stop -t 20 $cid" ;;
kill) action="docker kill $cid" ;;
*) echo "unknown mode $mode" >&2; exit 2 ;;
esac
echo "== $mode $name ($short) $(date -u +%FT%TZ)"
out=evidence/failover-$mode-$name.json
python3 student-tests/failover_bench.py --label "$mode $name" \
--concurrency "$CONCURRENCY" --duration "$DURATION" --action-at 10 \
--action "$action" --target-instance "$short" \
--action-log "${out%.json}.action.log" --output "$out" \
| python3 -c 'import json,sys; t=sys.stdin.read(); s=json.loads(t[:t.rindex("}")+1]); print(json.dumps({k:s[k] for k in ("baseline_ok_rps","post_action_ok_rps","capacity_ratio","errors_total","errors_by_kind","error_window_s","recovery_s","target_last_seen_s","lb_events","lost_confirmed","duplicate_texts","pass")},ensure_ascii=False)); sys.exit(0 if s["pass"] else 1)'
echo "-- state after action:"; docker compose ps -a --format '{{.Name}} {{.Status}}' api
done
done
wait_all_up
echo "== restored: $(docker compose ps --format '{{.Name}} {{.Status}}' api | tr '\n' ';')"
+114
View File
@@ -0,0 +1,114 @@
#!/bin/sh
# Создаёт локальные секреты и .env для учебного стенда (lab6). Повторный запуск ничего не перезаписывает.
# Значения секретов не печатаются.
#
# S3 (SeaweedFS) — РАЗНЫЕ ключи с разными правами (secrets/s3_identities.json):
# admin — Admin/Read/Write/List: только job s3-init (создание bucket);
# api — Read+Write на bucket: staging PUT и выдача байтов, без List и без управления bucket;
# worker — Read+Write на bucket: чтение staging, запись результатов, удаление staging;
# janitor — List+Write на bucket: обход и удаление, без чтения содержимого.
# RabbitMQ — пользователи с минимальными правами в vhost messenger (secrets/rabbitmq_definitions.json):
# relay — только publish в exchange attachments;
# worker — только consume из attachments.process.v1;
# ops — consume из DLQ и publish в attachments (replay/учебные проверки).
# Ни у кого из них нет права configure: топология создаётся из definitions при старте брокера.
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets
chmod 700 secrets
gen() { # gen <file> <bytes>
if [ ! -s "secrets/$1" ]; then
python3 -c "import secrets,sys; print(secrets.token_urlsafe(int(sys.argv[1])))" "$2" > "secrets/$1"
echo "created secrets/$1"
fi
}
gen postgres_password 24
# Lab6: пароль администратора Grafana (GF_SECURITY_ADMIN_PASSWORD__FILE).
gen grafana_admin_password 18
for who in admin api worker janitor; do
if [ ! -s "secrets/s3_${who}_access_key" ]; then
python3 -c "import secrets; print('MTUSI' + secrets.token_hex(8).upper())" > "secrets/s3_${who}_access_key"
echo "created secrets/s3_${who}_access_key"
fi
gen "s3_${who}_secret_key" 30
done
for who in relay worker ops; do
gen "broker_${who}_password" 24
done
BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | cut -d= -f2 || true)
BUCKET=${BUCKET:-messenger-attachments}
# Производные файлы пересобираются из базовых секретов (детерминированно, кроме соли хеша).
python3 - "$BUCKET" <<'PY'
import base64, hashlib, json, os, sys
b = sys.argv[1]
def read(name):
return open("secrets/" + name).read().strip()
def ident(name, actions):
return {"name": name, "credentials": [{"accessKey": read("s3_%s_access_key" % name),
"secretKey": read("s3_%s_secret_key" % name)}], "actions": actions}
cfg = {"identities": [
ident("admin", ["Admin", "Read", "List", "Tagging", "Write"]),
ident("api", ["Read:" + b, "Write:" + b]),
ident("worker", ["Read:" + b, "Write:" + b]),
ident("janitor", ["List:" + b, "Write:" + b]),
]}
with open("secrets/s3_identities.json", "w") as f:
json.dump(cfg, f, indent=1)
# RabbitMQ: rabbit_password_hashing_sha256 = base64(salt4 + sha256(salt4 + password)).
def rmq_hash(password):
salt = os.urandom(4)
return base64.b64encode(salt + hashlib.sha256(salt + password.encode()).digest()).decode()
vhost = "messenger"
users, perms = [], []
rights = {
"relay": {"configure": "^$", "write": "^attachments$", "read": "^$"},
"worker": {"configure": "^$", "write": "^$", "read": r"^attachments\.process\.v1$"},
"ops": {"configure": "^$", "write": "^attachments$", "read": r"^attachments\.dlq$"},
}
for user, r in rights.items():
password = read("broker_%s_password" % user)
users.append({"name": user, "password_hash": rmq_hash(password),
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []})
perms.append(dict(user=user, vhost=vhost, **r))
with open("secrets/broker_%s_url" % user, "w") as f:
f.write("amqp://%s:%s@broker:5672/%s\n" % (user, password, vhost))
x = lambda name, kind: {"name": name, "vhost": vhost, "type": kind, "durable": True, "auto_delete": False,
"internal": False, "arguments": {}}
definitions = {
"users": users,
"vhosts": [{"name": vhost}],
"permissions": perms,
"exchanges": [x("attachments", "direct"), x("attachments.dlx", "fanout")],
"queues": [
# Quorum-очередь: durable, сообщения пишутся на диск (Raft-журнал) до publisher confirm.
# delivery-limit: сообщение, которое 10 раз вернулось без ack (crash-loop worker),
# уходит в DLQ. at-least-once dead-lettering требует overflow=reject-publish.
{"name": "attachments.process.v1", "vhost": vhost, "durable": True, "auto_delete": False,
"arguments": {"x-queue-type": "quorum", "x-delivery-limit": 10,
"x-dead-letter-exchange": "attachments.dlx",
"x-dead-letter-strategy": "at-least-once", "x-overflow": "reject-publish",
"x-max-length": 100000}},
{"name": "attachments.dlq", "vhost": vhost, "durable": True, "auto_delete": False,
"arguments": {"x-queue-type": "quorum"}},
],
"bindings": [
{"source": "attachments", "vhost": vhost, "destination": "attachments.process.v1",
"destination_type": "queue", "routing_key": "attachment.process.v1", "arguments": {}},
{"source": "attachments.dlx", "vhost": vhost, "destination": "attachments.dlq",
"destination_type": "queue", "routing_key": "", "arguments": {}},
],
}
if not os.path.exists("secrets/rabbitmq_definitions.json"):
with open("secrets/rabbitmq_definitions.json", "w") as f:
json.dump(definitions, f, indent=1)
print("created secrets/rabbitmq_definitions.json")
PY
# Файлы монтируются в контейнеры (uid 70 postgres, uid 10001 app, uid 100 rabbitmq, root в seaweedfs) —
# нужны на чтение; от других пользователей хоста их закрывает каталог secrets/ с правами 700.
chmod 644 secrets/*
if [ ! -f .env ]; then
cp .env.example .env
echo "created .env from .env.example"
fi
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
# Перезапуск ВСЕХ хранилищ — данных (PostgreSQL, SeaweedFS S3, RabbitMQ) и, с lab6, телеметрии
# (Prometheus, Loki, Tempo) — и всех процессов (API-реплики, relay, worker, janitor, LB,
# OTel Collector, Grafana) с сохранением volumes pgdata, s3data, brokerdata, promdata, lokidata,
# tempodata, grafanadata. Не выполняет down -v, не пересоздаёт БД/bucket/очереди и не повторяет seed.
set -eu
cd "$(dirname "$0")/.."
docker compose restart db s3 broker prometheus loki tempo
# Потребители стартуют, когда хранилища действительно готовы (healthcheck s3 проверяет запись,
# healthcheck broker — запущенный узел и объявленную очередь, prometheus — /-/ready).
docker compose up -d --no-deps --no-recreate --wait db s3 broker prometheus
docker compose restart otel-collector api relay worker janitor lb grafana
+69
View File
@@ -0,0 +1,69 @@
#!/bin/sh
# Поочерёдная замена API-реплик на новую версию образа без остановки сервиса.
# scripts/rolling-update.sh <APP_VERSION>
# Порядок (expand -> replace):
# 1. собрать новый образ (тот же тег mtusi-messenger:lab6, build-arg APP_VERSION). Секция build
# есть только у сервиса migrate (аудит F10: `build api` молча ничего не собирал), поэтому
# собираем migrate и проверяем, что в образе действительно новая версия;
# 2. ОДИН раз применить миграции (job migrate). Допускаются только обратно совместимые
# (expand-only) миграции: старые реплики продолжают работать на новой схеме;
# 3. для каждой старой реплики: поднять +1 новую -> дождаться healthy и UP в HAProxy ->
# штатно остановить (SIGTERM, drain) и удалить старую. Число обслуживающих реплик
# не опускается ниже исходного.
# 4. записать APP_VERSION в .env, чтобы следующий `docker compose up` не пересоздал всё разом.
set -eu
cd "$(dirname "$0")/.."
VERSION=${1:?usage: rolling-update.sh <APP_VERSION>}
export APP_VERSION="$VERSION"
ts() { date -u +%FT%TZ; }
lb_up_count() {
curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1=="be_api" && $18=="UP"' | wc -l | tr -d ' '
}
# UP ли в HAProxy слот с адресом конкретного контейнера. Проверяем именно адрес, а не число
# UP-серверов: новый контейнер может получить IP только что удалённого, и счётчик обманет.
lb_has_up() {
curl -s 'http://127.0.0.1:8404/stats;csv' | awk -F, -v a="$1:8080" '$1=="be_api" && $18=="UP" && $74==a' | grep -q .
}
echo "$(ts) build version $VERSION"
docker compose --env-file .env build migrate >/dev/null
built=$(docker run --rm --entrypoint printenv mtusi-messenger:lab6 APP_VERSION)
[ "$built" = "$VERSION" ] || { echo "image has APP_VERSION=$built, expected $VERSION" >&2; exit 1; }
echo "$(ts) migrate (once)"
docker compose --env-file .env run --rm --no-deps migrate
OLD=$(docker compose ps -q api)
N=$(echo "$OLD" | wc -l | tr -d ' ')
echo "$(ts) replacing $N replicas"
for old in $OLD; do
before=$(docker compose ps -q api | sort)
docker compose --env-file .env up -d --no-deps --no-recreate --scale api=$((N + 1)) api >/dev/null 2>&1
new=$(docker compose ps -q api | sort | grep -v -F "$before" | head -1)
[ -n "$new" ] || { echo "new replica was not created" >&2; exit 1; }
for _ in $(seq 1 60); do
[ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ] && break; sleep 1
done
[ "$(docker inspect -f '{{.State.Health.Status}}' "$new")" = healthy ] || { echo "new replica not healthy" >&2; exit 1; }
ip=$(docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' "$new")
for _ in $(seq 1 30); do lb_has_up "$ip" && break; sleep 0.5; done
lb_has_up "$ip" || { echo "HAProxy did not mark new replica $ip UP" >&2; exit 1; }
got=$(docker exec "$new" printenv APP_VERSION)
[ "$got" = "$VERSION" ] || { echo "new replica runs APP_VERSION=$got, expected $VERSION" >&2; exit 1; }
echo "$(ts) up $(docker inspect -f '{{.Name}}' "$new" | tr -d /) version=$got ip=$ip UP in LB (UP slots: $(lb_up_count))"
name=$(docker inspect -f '{{.Name}}' "$old" | tr -d /)
docker stop -t 20 "$old" >/dev/null && docker rm "$old" >/dev/null
echo "$(ts) gone $name (graceful SIGTERM)"
done
if grep -q '^APP_VERSION=' .env; then
sed -i.bak "s/^APP_VERSION=.*/APP_VERSION=$VERSION/" .env && rm -f .env.bak
else
echo "APP_VERSION=$VERSION" >> .env
fi
echo "$(ts) done: $(docker compose ps --format '{{.Name}}' api | tr '\n' ' ')"
# Проверка через LB: все ответы — от новой версии.
for _ in $(seq 1 10); do
v=$(curl -s -D - -o /dev/null http://127.0.0.1:${LB_PORT:-8080}/health/ready | tr -d '\r' | awk -F': ' 'tolower($1)=="x-app-version"{print $2}')
[ "$v" = "$VERSION" ] || { echo "LB served X-App-Version=$v, expected $VERSION" >&2; exit 1; }
done
echo "$(ts) verified: 10/10 responses via LB have X-App-Version=$VERSION"
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Проверка перед commit: значения из secrets/ (пароли, ключи S3, URL брокера) не встречаются
ни в одном файле репозитория вне secrets/ и .env. Значения не печатаются — только имена файлов.
python3 scripts/scan_secrets.py (код 0 — чисто)"""
import json
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SKIP_DIRS = {".git", "secrets", ".venv", "__pycache__", "node_modules"}
values = set()
for f in (ROOT / "secrets").glob("*"):
text = f.read_text(encoding="utf-8", errors="replace").strip()
if f.suffix == ".json":
def walk(x):
if isinstance(x, dict):
for k, v in x.items():
if k in ("accessKey", "secretKey", "password_hash"):
values.add(str(v))
walk(v)
elif isinstance(x, list):
for v in x:
walk(v)
walk(json.loads(text))
elif len(text) >= 8:
values.add(text)
if "://" in text and "@" in text: # пароль из URL брокера
values.add(text.split("://", 1)[1].split("@", 1)[0].split(":", 1)[-1])
hits = []
for p in ROOT.rglob("*"):
if p.is_dir() or set(p.relative_to(ROOT).parts) & SKIP_DIRS or p.name == ".env":
continue
try:
data = p.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
if any(v in data for v in values):
hits.append(str(p.relative_to(ROOT)))
print("checked %d secret values; files with leaks: %s" % (len(values), hits or "none"))
sys.exit(1 if hits else 0)
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Восстанавливает остановленные API-реплики и worker (после stop-one.sh / stop-worker.sh) и ждёт готовности.
# --no-deps: хранилища и job-ы не трогаются; --no-recreate: те же контейнеры (тот же образ).
set -eu
cd "$(dirname "$0")/.."
docker compose up -d --no-deps --no-recreate --wait api worker
docker compose ps --format '{{.Name}} {{.Status}}' api worker
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# Запустить worker после stop-worker.sh (те же контейнеры) и дождаться готовности.
set -eu
cd "$(dirname "$0")/.."
docker compose up -d --no-deps --no-recreate --wait worker
docker compose ps --format '{{.Name}} {{.Status}}' worker
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Останавливает ОДНУ API-реплику, обслужившую тест, и оставляет её остановленной.
# TARGET_INSTANCE_ID = X-Instance-Id = hostname контейнера = короткий ID контейнера.
# DB, LB и volumes не трогаются. Восстановление: scripts/start-all.sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!0-9a-f]*|'') echo "unexpected instance id format" >&2; exit 2 ;;
esac
# Проверяем, что это действительно запущенный контейнер сервиса api ЭТОГО compose-проекта.
# Список берём у самого compose: работает и при другом имени проекта (-p / COMPOSE_PROJECT_NAME).
cid=$(docker compose ps -q --status running api | grep "^${TARGET_INSTANCE_ID}" || true)
[ -n "$cid" ] || { echo "no running api container for $TARGET_INSTANCE_ID" >&2; exit 3; }
name=$(docker inspect -f '{{.Name}}' "$cid")
echo "$(date -u +%FT%TZ) stopping api container ${name#/} (${TARGET_INSTANCE_ID})" >&2
# SIGTERM -> graceful shutdown приложения (drain 3 с + дообслуживание), затем выход.
docker stop -t 20 "$cid" >/dev/null
echo "$(date -u +%FT%TZ) stopped ${name#/}" >&2
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# Сценарий защиты: остановить ВСЕ worker (SIGTERM, текущие задания дорабатываются).
# API, relay и брокер продолжают работать: upload -> 202, задания копятся в очереди.
set -eu
cd "$(dirname "$0")/.."
docker compose stop worker
docker compose ps --format '{{.Name}} {{.State}}' worker