lab6 done

This commit is contained in:
Khakimov Dmitrij
2026-11-18 21:37:25 +03:00
parent 470d9d6f1e
commit 4ab9b0ef9a
158 changed files with 21115 additions and 52 deletions
+20 -4
View File
@@ -1,7 +1,23 @@
# Инфраструктура студента
# Инфраструктура lab6
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Полная топология находится в [compose.yaml](../compose.yaml). Запуск: `make up` из корня.
Файл compose.example.yaml сохранён как исходный worksheet задания и не используется при запуске.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
| Конфигурация | Назначение |
| --- | --- |
| haproxy.cfg | Балансировка двух API-реплик, DNS Docker, readiness каждой реплики |
| redis.conf | Сессии, Redis Streams и AOF |
| migrate.sh | Goose migrations с credentials из файла секрета |
| minio-entrypoint.sh | Запуск MinIO с root credentials из файлов |
| s3-bootstrap.sh, s3-policy.json | Приватный bucket и пользователь приложения с ограниченной policy |
| otel/collector.yaml | Приём OTLP, memory limiter, batch, экспорт трёх сигналов |
| prometheus/ | Scrape приложения/Collector/backend и локальные alert rules |
| loki.yaml | OTLP logs, filesystem storage, retention |
| tempo.yaml | OTLP traces, WAL/blocks, retention |
| grafana/provisioning/ | Автоматическая регистрация трёх datasources и dashboard provider |
| grafana/dashboards/messenger.json | Импортируемый dashboard с 15 панелями |
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Named volumes сохраняют PostgreSQL, Redis, S3 и историю всех telemetry backend/Grafana.
Bootstrap идемпотентен. Credentials создаёт scripts/bootstrap.sh; они не хранятся в Git.
Сопоставление версий, readiness, volumes, портов и лимитов: [REPORT.md](../REPORT.md).
Диагностика по сохранённым сигналам: [RUNBOOK.md](../RUNBOOK.md).
+519
View File
@@ -0,0 +1,519 @@
{
"uid": "messenger",
"title": "Messenger observability",
"schemaVersion": 41,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "API RPS (business routes)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(messenger_http_requests_total[$__rate_interval])) by (route)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 2,
"title": "API 5xx / all business requests",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[$__rate_interval])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total[$__rate_interval])),0.001)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 3,
"title": "API p50 / p95 / p99 (all replicas, histogram)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "p50",
"refId": "A"
},
{
"expr": "histogram_quantile(0.95,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "p95",
"refId": "B"
},
{
"expr": "histogram_quantile(0.99,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "p99",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 4,
"title": "Worker job outcomes per second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(messenger_jobs_total[$__rate_interval])) by(outcome)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 5,
"title": "Worker job p95 duration",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum(rate(messenger_job_duration_seconds_bucket[$__rate_interval])) by(le,outcome))",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 6,
"title": "Time from durable acceptance to ready p95",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum(rate(messenger_attachment_ready_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 7,
"title": "Authoritative queue depth (max across observers)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_queue_depth)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 8,
"title": "Oldest unfinished job age",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_queue_oldest_age_seconds)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 9,
"title": "DB pool acquired / acquiring / max",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "messenger_db_pool_used",
"legendFormat": "used {{service_name}} {{service_instance_id}}",
"refId": "A"
},
{
"expr": "messenger_db_pool_waiting",
"legendFormat": "waiting {{service_name}} {{service_instance_id}}",
"refId": "B"
},
{
"expr": "messenger_db_pool_max",
"legendFormat": "max {{service_name}} {{service_instance_id}}",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 10,
"title": "Worker saturation busy / capacity",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(messenger_worker_busy{service_name=\"messenger-worker\"}) / clamp_min(sum(messenger_worker_capacity{service_name=\"messenger-worker\"}),1)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 11,
"title": "Go runtime reserved memory (MemStats.Sys)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "messenger_process_memory_bytes",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 12,
"title": "Process CPU seconds / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "rate(messenger_process_cpu_seconds_total[$__rate_interval])",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 13,
"title": "SDK failed telemetry export operations",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "messenger_telemetry_export_errors",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 14,
"title": "Exporter failed spans (attempts, not unique loss)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(otelcol_exporter_send_failed_spans_total) by (exporter)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 99,
"title": "API and worker structured logs; trace ID opens Tempo",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 24,
"h": 10
},
"targets": [
{
"expr": "{service_name=~\"messenger-api|messenger-worker\"} | json",
"refId": "A"
}
]
}
],
"annotations": {
"list": []
}
}
@@ -0,0 +1,6 @@
apiVersion: 1
providers:
- name: Messenger
type: file
options: {path: /var/lib/grafana/dashboards}
updateIntervalSeconds: 10
@@ -0,0 +1,29 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
serviceMap: {datasourceUid: prometheus}
+36
View File
@@ -0,0 +1,36 @@
global
log stdout format raw local0
maxconn 1024
defaults
log global
mode http
timeout connect 1s
timeout client 55s
timeout server 55s
timeout check 1s
retries 0
option http-server-close
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold nx 1s
hold refused 1s
hold timeout 1s
frontend public
bind :8080
default_backend api
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
server-template replica 1-8 api:8080 check resolvers docker init-addr none
+27
View File
@@ -0,0 +1,27 @@
auth_enabled: false
server: {http_listen_port: 3100, grpc_listen_port: 9096}
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem: {chunks_directory: /loki/chunks, rules_directory: /loki/rules}
replication_factor: 1
ring:
kvstore: {store: inmemory}
schema_config:
configs:
- from: '2024-04-01'
store: tsdb
object_store: filesystem
schema: v13
index: {prefix: index_, period: 24h}
limits_config:
allow_structured_metadata: true
retention_period: 168h
ingestion_rate_mb: 4
ingestion_burst_size_mb: 8
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics: {reporting_enabled: false}
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
# Keep the password out of argv and disable automatic dotenv loading.
if [ -n "${POSTGRES_PASSWORD_FILE:-}" ]; then
PGPASSWORD=$(cat "$POSTGRES_PASSWORD_FILE")
export PGPASSWORD
fi
exec goose -env /dev/null -dir /migrations -timeout 30s "$@"
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /run/secrets/s3_root_access_key)"
export MINIO_ROOT_PASSWORD="$(cat /run/secrets/s3_root_secret_key)"
exec minio server /data --address :9000 --console-address 127.0.0.1:9001
+20 -4
View File
@@ -1,7 +1,23 @@
# Конфигурация наблюдаемости — реализовать
# OpenTelemetry Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Конфигурация: [collector.yaml](collector.yaml), образ contrib 0.137.0 закреплён в Compose.
API и worker используют SDK Go и передают три сигнала по OTLP HTTP/protobuf на collector:4318.
GRPC receiver слушает :4317. Оба порта доступны только внутри сети Compose.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
| Pipeline | Processors | Exporter / backend |
| --- | --- | --- |
| metrics | memory_limiter, batch | Prometheus exporter :8889; Prometheus scrape каждые 5s |
| logs | memory_limiter, batch | OTLP HTTP → Loki /otlp |
| traces | memory_limiter, batch | OTLP HTTP → Tempo :4318 |
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Memory limiter:128MiB, spike32MiB, check1s. Batch:256, max512, timeout1s.
Каждый OTLP exporter имеет queue256,2 consumers, timeout2s и retry максимум 20s.
Collector ограничен cgroup192MiB. После исчерпания очереди/таймаутов сигналы могут потеряться.
Очереди находятся в RAM и не переживают аварийный restart. Работа приложения не зависит от успешной записи telemetry.
Метрики самого Collector доступны внутри сети на :8888 и собираются Prometheus.
Данные хранят отдельные Prometheus/Loki/Tempo; Collector не заменяет хранилище.
Grafana provisioning: ../grafana/provisioning, dashboard: ../grafana/dashboards/messenger.json.
Alert rules: ../prometheus/alerts.yaml. Процедуры расследования: ../../RUNBOOK.md.
Доказательства и ограничения: ../../REPORT.md, ../../INCIDENTS.md, ../../RESEARCH.md.
+41
View File
@@ -0,0 +1,41 @@
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: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 512
exporters:
prometheus:
endpoint: 0.0.0.0:8889
metric_expiration: 15s
resource_to_telemetry_conversion: {enabled: true}
otlphttp/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue: {enabled: true, queue_size: 256, num_consumers: 2}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 20s}
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue: {enabled: true, queue_size: 256, num_consumers: 2}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 20s}
service:
telemetry:
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus: {host: 0.0.0.0, port: 8888}
pipelines:
traces: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/tempo]}
metrics: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheus]}
logs: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki]}
+19
View File
@@ -0,0 +1,19 @@
groups:
- name: messenger-slo
rules:
- alert: APIHighErrorRate
expr: sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 0.01) > 0.05
for: 5s
labels: {severity: warning}
annotations:
summary: More than 5 percent API server failures over 1 minute
runbook_url: http://localhost:13000/d/messenger/messenger-observability
description: Excludes health and client 4xx. Inspect PostgreSQL spans and pool; see RUNBOOK.md.
- alert: QueueLagGrowing
expr: max(messenger_queue_oldest_age_seconds) > 10 and max(messenger_queue_depth) > 0
for: 5s
labels: {severity: warning}
annotations:
summary: Oldest unfinished attachment exceeds 10 seconds
runbook_url: http://localhost:13000/d/messenger/messenger-observability
description: Inspect worker capacity, busy, outcomes and dependency spans; see RUNBOOK.md.
+15
View File
@@ -0,0 +1,15 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files: [/etc/prometheus/alerts.yaml]
scrape_configs:
- job_name: messenger
static_configs: [{targets: ['collector:8889']}]
- job_name: collector
static_configs: [{targets: ['collector:8888']}]
- job_name: tempo
static_configs: [{targets: ['tempo:3200']}]
- job_name: loki
static_configs: [{targets: ['loki:3100']}]
- job_name: prometheus
static_configs: [{targets: ['localhost:9090']}]
+9
View File
@@ -0,0 +1,9 @@
bind 0.0.0.0
protected-mode no
port 6379
dir /data
appendonly yes
appendfsync always
save ""
maxmemory 256mb
maxmemory-policy noeviction
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -eu
export MC_CONFIG_DIR=/tmp/mc
mc alias set admin http://minio:9000 "$(cat /run/secrets/s3_root_access_key)" "$(cat /run/secrets/s3_root_secret_key)" >/dev/null
mc ready admin >/dev/null
mc mb --ignore-existing admin/attachments >/dev/null
mc anonymous set none admin/attachments >/dev/null
mc admin policy create admin attachments-api /policy.json >/dev/null
mc admin user add admin "$(cat /run/secrets/s3_access_key)" "$(cat /run/secrets/s3_secret_key)" >/dev/null
mc admin policy attach admin attachments-api --user "$(cat /run/secrets/s3_access_key)" >/dev/null
printf '%s\n' 'PASS: private bucket and restricted API account configured.'
+21
View File
@@ -0,0 +1,21 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::attachments"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::attachments"],
"Condition": {"StringLike": {"s3:prefix": ["original/*", "staging/*"]}}
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::attachments/original/*", "arn:aws:s3:::attachments/staging/*"]
}
]
}
+17
View File
@@ -0,0 +1,17 @@
server: {http_listen_port: 3200}
distributor:
receivers:
otlp:
protocols:
grpc: {endpoint: '0.0.0.0:4317'}
http: {endpoint: '0.0.0.0:4318'}
ingester:
max_block_duration: 1m
compactor:
compaction: {block_retention: 168h}
storage:
trace:
backend: local
wal: {path: /var/tempo/wal}
local: {path: /var/tempo/blocks}
usage_report: {reporting_enabled: false}