Implement lab6 observability with OpenTelemetry and Grafana

This commit is contained in:
2026-11-19 16:36:40 +03:00
parent 470d9d6f1e
commit 8c253a0e5a
149 changed files with 11752 additions and 229 deletions
+6 -5
View File
@@ -1,7 +1,8 @@
# Инфраструктура студента
# Инфраструктура lab6
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Автор: Каменский Андрей, БПИ2301.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
compose.yaml включает приложение, PostgreSQL, Redis-сессии, отдельный Streams broker,
MinIO, worker/dispatcher, HAProxy и наблюдаемость. infra/observability содержит
Collector, Prometheus/alerts, Loki, Tempo и импортируемые Grafana datasources/dashboard.
Все настройки воспроизводимы без ручного создания панелей. Данные сохраняются в volumes.
+43
View File
@@ -0,0 +1,43 @@
global
log stdout format raw local0
maxconn 2048
stats socket /tmp/haproxy.sock mode 600 level admin
stats socket ipv4@127.0.0.1:9999 level admin
defaults
log global
mode http
option httplog
timeout connect 1s
timeout client 15s
timeout server 12s
timeout http-request 7s
timeout http-keep-alive 2s
timeout check 1s
# Не повторяем POST автоматически: неизвестный результат повторяет клиент
# с исходным Idempotency-Key. Соединения к недоступному API не ждут долго.
retries 0
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 timeout 1s
hold refused 1s
accepted_payload_size 8192
frontend public
bind :8080
default_backend api_pool
backend api_pool
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 2
server-template api 1-16 api:8080 check resolvers docker resolve-prefer ipv4 init-addr none
+20
View File
@@ -0,0 +1,20 @@
# MinIO community distribution is source-only; pin the reviewed release commit.
FROM golang:1.24.8-alpine3.22 AS build
RUN apk add --no-cache git
WORKDIR /source
RUN git init . \
&& git remote add origin https://github.com/minio/minio.git \
&& git fetch --depth 1 origin 9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a \
&& git checkout --detach FETCH_HEAD
ENV CGO_ENABLED=0 GOMAXPROCS=2
RUN go build -p 2 -trimpath -o /minio .
FROM alpine:3.22.2
RUN apk add --no-cache ca-certificates \
&& addgroup -S minio && adduser -S -G minio minio \
&& mkdir /data && chown minio:minio /data
COPY --from=build /minio /usr/local/bin/minio
USER minio
EXPOSE 9000
ENTRYPOINT ["minio"]
CMD ["server", "/data", "--console-address", ":9001"]
+23
View File
@@ -0,0 +1,23 @@
groups:
- name: lab6
interval: 2s
rules:
- alert: ApiHighErrorRate
expr: |
(sum(increase(http_server_requests_total{route=~"/api/v1/.*",status_class="5xx"}[30s]))
/ clamp_min(sum(increase(http_server_requests_total{route=~"/api/v1/.*"}[30s])), 1) > 0.05)
and sum(increase(http_server_requests_total{route=~"/api/v1/.*"}[30s])) >= 3
for: 5s
labels:
severity: warning
annotations:
summary: "Business API 5xx ratio exceeds 5% over 30 seconds"
description: "Exclude health and client errors. Inspect DB spans, db.error logs and pool waiting. See RUNBOOK.md."
- alert: QueueLagGrowing
expr: max(queue_oldest_age_seconds) > 15 and max(queue_depth) > 0
for: 5s
labels:
severity: warning
annotations:
summary: "Oldest accepted job has waited more than 15 seconds"
description: "Inspect queue depth, worker capacity/busy and job traces. Restore worker and verify lag returns to zero. See RUNBOOK.md."
+67
View File
@@ -0,0 +1,67 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
otlphttp/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 64
retry_on_failure:
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 64
retry_on_failure:
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
@@ -0,0 +1,519 @@
{
"uid": "messenger-lab6",
"title": "Мессенджер · Lab6 · Каменский Андрей",
"schemaVersion": 39,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"tags": [
"lab6",
"messenger"
],
"panels": [
{
"id": 1,
"title": "Business API requests / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(http_server_requests_total{route=~\"/api/v1/.*\"}[1m]))",
"legendFormat": "RPS",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 2,
"title": "Business API 5xx ratio",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(http_server_requests_total{route=~\"/api/v1/.*\",status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(http_server_requests_total{route=~\"/api/v1/.*\"}[1m])), 0.00001)",
"legendFormat": "5xx / all business requests",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 3,
"title": "API latency p50 (histogram, all replicas)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_duration_seconds_bucket{route=~\"/api/v1/.*\"}[1m])))",
"legendFormat": "p50",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 4,
"title": "API latency p95 (histogram, all replicas)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_seconds_bucket{route=~\"/api/v1/.*\"}[1m])))",
"legendFormat": "p95",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 5,
"title": "API latency p99 (histogram, all replicas)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_seconds_bucket{route=~\"/api/v1/.*\"}[1m])))",
"legendFormat": "p99",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 6,
"title": "Jobs per second by outcome",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(outcome)(rate(worker_jobs_total[1m]))",
"legendFormat": "{{outcome}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 7,
"title": "Worker processing p95",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95, sum by(le)(rate(worker_job_duration_seconds_bucket[1m])))",
"legendFormat": "p95",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 8,
"title": "Acceptance to ready p95",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95, sum by(le)(rate(attachment_ready_duration_seconds_bucket[1m])))",
"legendFormat": "p95",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 9,
"title": "Accepted unfinished jobs (includes outbox)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(queue_depth)",
"legendFormat": "jobs",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 10,
"title": "Oldest unfinished job age",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(queue_oldest_age_seconds)",
"legendFormat": "age",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 11,
"title": "DB pool used / waiting",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name)(db_pool_used)",
"legendFormat": "{{service_name}}",
"refId": "A"
},
{
"expr": "sum by(service_name)(db_pool_waiting)",
"legendFormat": "{{service_name}} waiting",
"refId": "B"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 12,
"title": "Worker saturation",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(worker_busy) / clamp_min(sum(worker_capacity),1)",
"legendFormat": "busy / capacity",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 13,
"title": "Process resident memory",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name)(process_memory_rss_bytes)",
"legendFormat": "{{service_name}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
}
},
{
"id": 14,
"title": "Process CPU cores",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name)(rate(process_cpu_time_seconds_total[1m]))",
"legendFormat": "{{service_name}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 15,
"title": "API availability SLI (5m), SLO 99%",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "1 - (sum(increase(http_server_requests_total{route=~\"/api/v1/.*\",status_class=\"5xx\"}[5m])) or vector(0)) / clamp_min(sum(increase(http_server_requests_total{route=~\"/api/v1/.*\"}[5m])),1)",
"legendFormat": "SLI",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 16,
"title": "Collector export failures / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(exporter)(rate(otelcol_exporter_send_failed_spans_total[1m]))",
"legendFormat": "{{exporter}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 17,
"title": "Local firing alerts",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "ALERTS{alertstate=\"firing\"}",
"legendFormat": "{{alertname}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 99,
"title": "Structured API / worker logs — trace_id links to Tempo",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 72,
"w": 24,
"h": 10
},
"targets": [
{
"expr": "{service_name=~\"messenger-(api|worker)\"}",
"refId": "A"
}
]
}
]
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Lab6
type: file
disableDeletion: true
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,34 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 2s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":\s*"([0-9a-f]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: '-1m'
spanEndTimeShift: '1m'
filterByTraceID: false
customQuery: true
query: '{service_name=~"messenger-.*"} | json | trace_id="$${__trace.traceId}"'
+30
View File
@@ -0,0 +1,30 @@
auth_enabled: false
server:
http_listen_port: 3100
common:
path_prefix: /loki
instance_addr: 127.0.0.1
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
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
+12
View File
@@ -0,0 +1,12 @@
global:
scrape_interval: 2s
evaluation_interval: 2s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: messenger
static_configs:
- targets: [otel-collector:8889]
- job_name: collector
static_configs:
- targets: [otel-collector:8888]
+21
View File
@@ -0,0 +1,21 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
ingester:
trace_idle_period: 2s
max_block_duration: 1m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
-7
View File
@@ -1,7 +0,0 @@
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
+29
View File
@@ -0,0 +1,29 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation"
],
"Resource": [
"arn:aws:s3:::${bucket}"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts"
],
"Resource": [
"arn:aws:s3:::${bucket}/originals/*",
"arn:aws:s3:::${bucket}/staging/*",
"arn:aws:s3:::${bucket}/variants/*"
]
}
]
}
+28
View File
@@ -0,0 +1,28 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:GetBucketVersioning"
],
"Resource": [
"arn:aws:s3:::${bucket}"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::${bucket}/originals/*",
"arn:aws:s3:::${bucket}/staging/*",
"arn:aws:s3:::${bucket}/variants/*"
]
}
]
}
+30
View File
@@ -0,0 +1,30 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation"
],
"Resource": [
"arn:aws:s3:::${bucket}"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:AbortMultipartUpload",
"s3:ListMultipartUploadParts",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::${bucket}/originals/*",
"arn:aws:s3:::${bucket}/staging/*",
"arn:aws:s3:::${bucket}/variants/*"
]
}
]
}