forked from mtusi2026/mtusi2026lab6
Реализована лабораторная 6 на оценку 4
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
# Build MinIO from a pinned commit of the official upstream source.
|
||||
FROM golang:1.26.8-alpine3.23@sha256:a8fa79c5bd40d880b52bd3b6d7669ecdcfd00e85facdd427d279efb5ddd79cb1 AS build
|
||||
ADD --checksum=sha256:be6d0bd3696c3a13a35f02d3a0280b64319c67918b4501c5c3d87f96d000085c https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-10-15T17-29-55Z /source.tar.gz
|
||||
WORKDIR /src
|
||||
RUN tar -xzf /source.tar.gz --strip-components=1 -C /src
|
||||
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
|
||||
CGO_ENABLED=0 GOMAXPROCS=2 go build -p 2 -trimpath -buildvcs=false \
|
||||
-ldflags='-s -w -X github.com/minio/minio/cmd.Version=2025-10-15T17:29:55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z -X github.com/minio/minio/cmd.CommitID=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a -X github.com/minio/minio/cmd.CopyrightYear=2025' \
|
||||
-o /minio .
|
||||
|
||||
FROM busybox:1.37.0-musl
|
||||
COPY --from=build /minio /minio
|
||||
COPY --from=build /src/LICENSE /licenses/MinIO-LICENSE
|
||||
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
RUN mkdir -p /data
|
||||
ENTRYPOINT ["/minio"]
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM application AS app_binary
|
||||
FROM python:3.13.7-slim-bookworm
|
||||
RUN pip install --no-cache-dir Pillow==12.0.0
|
||||
COPY --from=app_binary /messenger /messenger
|
||||
COPY worker/process_image.py /opt/process_image.py
|
||||
USER 65532:65532
|
||||
ENTRYPOINT ["/messenger"]
|
||||
CMD ["worker"]
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
upstream=/run/nginx-upstream.conf
|
||||
|
||||
write_servers() {
|
||||
if [ "$1" = 1 ]; then
|
||||
printf '%s\n' 'server api1:8080 resolve max_fails=0;'
|
||||
fi
|
||||
if [ "$2" = 1 ]; then
|
||||
printf '%s\n' 'server api2:8080 resolve max_fails=0;'
|
||||
fi
|
||||
}
|
||||
|
||||
# With no healthy replica, keep both reachable so API can return its normal
|
||||
# 401/503 JSON responses instead of Nginx reporting "no live upstreams".
|
||||
write_servers 1 1 > "$upstream"
|
||||
|
||||
monitor() {
|
||||
sleep 2
|
||||
while :; do
|
||||
ready1=0
|
||||
ready2=0
|
||||
wget -q -T 2 -O /dev/null http://api1:8080/health/ready && ready1=1 || true
|
||||
wget -q -T 2 -O /dev/null http://api2:8080/health/ready && ready2=1 || true
|
||||
if [ "$ready1" = 0 ] && [ "$ready2" = 0 ]; then
|
||||
ready1=1
|
||||
ready2=1
|
||||
fi
|
||||
next=$(mktemp /run/nginx-upstream.XXXXXX)
|
||||
write_servers "$ready1" "$ready2" > "$next"
|
||||
if cmp -s "$next" "$upstream"; then
|
||||
rm -f "$next"
|
||||
else
|
||||
mv "$next" "$upstream"
|
||||
nginx -t >/dev/null 2>&1 && nginx -s reload
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
monitor &
|
||||
exec nginx -g 'daemon off;'
|
||||
@@ -0,0 +1,35 @@
|
||||
events {}
|
||||
|
||||
http {
|
||||
access_log /dev/stdout;
|
||||
error_log /dev/stderr notice;
|
||||
|
||||
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||
|
||||
upstream messenger_api {
|
||||
zone messenger_api 64k;
|
||||
include /run/nginx-upstream.conf;
|
||||
keepalive 16;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
client_max_body_size 0;
|
||||
client_body_timeout 20s;
|
||||
|
||||
location / {
|
||||
proxy_request_buffering off;
|
||||
proxy_buffering off;
|
||||
proxy_pass http://messenger_api;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_connect_timeout 500ms;
|
||||
proxy_send_timeout 65s;
|
||||
proxy_read_timeout 65s;
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
-5
@@ -1,7 +1,12 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
# Наблюдаемость лабораторной 6
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
- `collector.yaml` — OTLP receiver и три pipeline, memory limiter, batch, bounded queues/retry.
|
||||
- `prometheus.yaml`, `alerts.yaml` — scrape, SLI и два локальных alert rules.
|
||||
- `loki.yaml` — OTLP logs с structured metadata и persistent filesystem.
|
||||
- `tempo.yaml` — OTLP traces, WAL и persistent blocks.
|
||||
- `grafana/provisioning` — три datasource и автоматический импорт dashboard.
|
||||
- `grafana/dashboards/messenger.json` — импортируемый dashboard с реальными PromQL-запросами.
|
||||
- [Сигналы и единицы](signals.md).
|
||||
- [Runbook и SLO](runbook.md).
|
||||
|
||||
Добавьте конфигурации 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 запрещён.
|
||||
Запуск и проверки — в корневом REPORT.md. Публикуется только Grafana на localhost; OTLP/Prometheus/Loki/Tempo ports остаются внутри Compose.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
groups:
|
||||
- name: messenger-slo
|
||||
rules:
|
||||
- record: messenger:api_error_ratio:rate1m
|
||||
expr: (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[1m])), 0.001)
|
||||
- record: messenger:api_availability:rate5m
|
||||
expr: 1 - (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[5m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[5m])), 0.001)
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: messenger:api_error_ratio:rate1m > 0.05
|
||||
for: 10s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Business API 5xx ratio exceeds 5% over 1 minute
|
||||
description: Inspect database spans, DB availability and pool panels; see infra/otel/runbook.md.
|
||||
- alert: MessengerQueueLag
|
||||
expr: max(messenger_queue_oldest_age_seconds) > 10 and max(messenger_queue_depth) > 0
|
||||
for: 10s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Oldest queued job exceeds 10 seconds
|
||||
description: Compare worker busy/capacity, job outcomes and queue age; see infra/otel/runbook.md.
|
||||
@@ -0,0 +1,74 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
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: 64
|
||||
send_batch_max_size: 128
|
||||
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: 32
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 2s
|
||||
max_elapsed_time: 5s
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 2s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 32
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 2s
|
||||
max_elapsed_time: 5s
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
service:
|
||||
extensions: [health_check]
|
||||
telemetry:
|
||||
logs:
|
||||
encoding: json
|
||||
metrics:
|
||||
level: detailed
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
@@ -0,0 +1,669 @@
|
||||
{
|
||||
"uid": "mtusi-messenger",
|
||||
"title": "MTUSI Messenger — lab6",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "5s",
|
||||
"tags": [
|
||||
"mtusi",
|
||||
"lab6"
|
||||
],
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API RPS (business routes)",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_instance_id) (rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m]))",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Business API error ratio: 5xx / all",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger:api_error_ratio:rate1m",
|
||||
"legendFormat": "5xx ratio"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API p50 from histogram",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
|
||||
"legendFormat": "p50"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "API p95 from histogram",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
|
||||
"legendFormat": "p95"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "API p99 from histogram",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Worker job outcomes",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Worker p95 processing duration",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
|
||||
"legendFormat": "p95"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "End-to-end p95 time to ready",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))",
|
||||
"legendFormat": "p95"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Queue depth",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_queue_depth)",
|
||||
"legendFormat": "queued"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Oldest queued job age",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_queue_oldest_age_seconds)",
|
||||
"legendFormat": "oldest"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "DB pool used / waiting",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_db_pool_used",
|
||||
"legendFormat": "used {{service_instance_id}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "messenger_db_pool_waiting",
|
||||
"legendFormat": "waiting {{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "DB pool wait rate",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_instance_id) (rate(messenger_db_pool_acquire_wait_total[1m]))",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "Worker saturation: busy / capacity",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_worker_busy / messenger_worker_capacity",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "Worker capacity",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_worker_capacity",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"title": "Container CPU time rate (includes decoder)",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "rate(messenger_container_cpu_seconds_total[1m])",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "cores"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"title": "Container memory",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_container_memory_bytes",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"title": "Database available",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 64,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_db_available",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"title": "SLI availability, rolling 5m (SLO 99%)",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 64,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger:api_availability:rate5m",
|
||||
"legendFormat": "availability"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"title": "Local alert states",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 72,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "ALERTS{alertname=~\"Messenger.*\"}",
|
||||
"legendFormat": "{{alertname}} {{alertstate}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"title": "Collector queued export batches",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 72,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "otelcol_exporter_queue_size",
|
||||
"legendFormat": "{{exporter}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"title": "Collector failed trace exports",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 80,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "otelcol_exporter_send_failed_spans_total",
|
||||
"legendFormat": "{{exporter}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"title": "SDK exporter errors",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 80,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_telemetry_export_errors",
|
||||
"legendFormat": "{{service_instance_id}}"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"title": "Worker heartbeat age (stale if stopped)",
|
||||
"type": "timeseries",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 88,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "time() - messenger_process_last_observed_seconds{service_name=\"messenger-worker\"}",
|
||||
"legendFormat": "worker heartbeat age"
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
}
|
||||
],
|
||||
"annotations": {
|
||||
"list": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Messenger
|
||||
orgId: 1
|
||||
folder: MTUSI
|
||||
type: file
|
||||
disableDeletion: false
|
||||
editable: false
|
||||
updateIntervalSeconds: 10
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,36 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
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
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-1m'
|
||||
spanEndTimeShift: '1m'
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
serviceMap:
|
||||
datasourceUid: prometheus
|
||||
@@ -0,0 +1,30 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
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: 24h
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
@@ -0,0 +1,12 @@
|
||||
global:
|
||||
scrape_interval: 3s
|
||||
evaluation_interval: 5s
|
||||
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]
|
||||
@@ -0,0 +1,42 @@
|
||||
# Локальная диагностика
|
||||
|
||||
Открыть Grafana → MTUSI → **MTUSI Messenger — lab6**. В Explore доступны Prometheus, Loki и Tempo. Пароль admin хранится локально в `secrets/grafana_admin_password`, в Git его нет.
|
||||
|
||||
## MessengerQueueLag
|
||||
|
||||
Условие: oldest queued job > 10 s при depth > 0 в течение 10 s. Интервал оценки — 5 s, scrape — 3 s.
|
||||
|
||||
1. Посмотреть Queue depth и Oldest queued job age: растут ли они вместе.
|
||||
2. Посмотреть Worker heartbeat age и busy/capacity. Старый heartbeat при busy=0 означает отсутствие свежих наблюдений worker, а не доказательство его здоровья.
|
||||
3. Найти `job.published` в Loki и trace upload в Tempo. Если producer есть, а нового consumer нет, искать недоступный worker/доставку. Если consumer есть с error, посмотреть его S3/DB child spans.
|
||||
4. После устранения причины наблюдать jobs outcome=success, снижение depth/age, свежий heartbeat и resolved (alert исчезает из активных).
|
||||
|
||||
Для демонстрации: `docker compose --env-file .env stop worker`, загрузить изображение; восстановить `docker compose --env-file .env start worker`. Проверки автоматизированы в `student-tests/verify_incidents.py`.
|
||||
|
||||
## MessengerHighErrorRate
|
||||
|
||||
Условие: 5xx / все бизнес-запросы > 5% за 1 минуту в течение 10 s. Health исключены. Ошибки клиента 400/401/404 не входят в числитель.
|
||||
|
||||
1. Посмотреть Business API error ratio и API percentiles.
|
||||
2. По `X-Trace-Id` ответа открыть trace в Tempo. В Loki фильтровать `trace_id` или `request_id`.
|
||||
3. Для отказа PostgreSQL видны error spans `db.pool.acquire`/`db.select`, `messenger_db_available=0` и ожидание пула. Длительность HTTP без DB error сама по себе не доказывает отказ БД.
|
||||
4. Восстановить PostgreSQL. Проверить успешные запросы, DB availability=1 и падение error ratio в движущемся окне. Resolved может наступить после обновления окна и нескольких scrape/evaluation.
|
||||
|
||||
## Tempo недоступен
|
||||
|
||||
1. API продолжает записи; проверить бизнес-операцию, а не только `/health/live`.
|
||||
2. В Prometheus посмотреть `otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"}` и `otelcol_exporter_queue_size`.
|
||||
3. Collector queue ограничена 32 batch requests, retry — 5 s; SDK queue — 256 spans/log records, exporter timeout — 2 s. Ожидание backend не переносится в HTTP handler.
|
||||
4. При переполнении/исчерпании retry данные telemetry могут быть потеряны. В JSON-логах Collector финальная потеря содержит `dropped_items`. Счётчик failed sends не следует считать числом уникальных потерянных трасс.
|
||||
5. После восстановления проверить свежий trace. Старые потерянные spans автоматически не восстанавливаются из бизнес-БД.
|
||||
|
||||
## SLI/SLO
|
||||
|
||||
SLI: доля бизнес HTTP-запросов без 5xx за скользящие **5 минут**. SLO: **≥99%**.
|
||||
|
||||
```promql
|
||||
1 - (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[5m])) or vector(0))
|
||||
/ clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[5m])), 0.001)
|
||||
```
|
||||
|
||||
SLO оценивается на окне с реальным трафиком; при отсутствии запросов правило не должно порождать ошибку деления. Alert использует более короткое 1m окно и порог 5% для локальной диагностики. Это не burn-rate исследование оценки 5.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Схема сигналов v1
|
||||
|
||||
SDK: OpenTelemetry Go traces/metrics **1.38.0**, logs **0.14.0**. Resource schema URL — OTel semantic conventions **1.37.0**; прикладные имена и labels ниже зафиксированы собственной схемой `mtusi-messenger/telemetry-v1`.
|
||||
|
||||
Resources: `service.name` = messenger-api / messenger-worker / messenger-dispatcher; `service.version=lab6-v1`, `service.instance.id` = api-1/api-2/worker-1/dispatcher-1, `deployment.environment.name=lab`. Collector превращает resource attrs в Prometheus labels, например service_name.
|
||||
|
||||
| Prometheus metric | Тип, единица | Labels |
|
||||
|---|---|---|
|
||||
| messenger_http_requests_total | counter, requests | method, route template, status_class |
|
||||
| messenger_http_duration_seconds_bucket/count/sum | histogram, seconds | те же |
|
||||
| messenger_jobs_processed_total | counter, attempts | job_type, outcome |
|
||||
| messenger_job_duration_seconds_bucket/count/sum | histogram, seconds | job_type, outcome |
|
||||
| messenger_time_to_ready_seconds_bucket/count/sum | histogram, seconds | job_type |
|
||||
| messenger_queue_depth | gauge, jobs | queue; только dispatcher |
|
||||
| messenger_queue_oldest_age_seconds | gauge, seconds | queue; только dispatcher |
|
||||
| messenger_db_pool_used/idle/waiting/capacity | gauge, connections/acquires | resource instance |
|
||||
| messenger_db_pool_acquire_wait_total | counter, empty pool acquires | resource instance |
|
||||
| messenger_db_pool_acquire_wait_duration_seconds_total | counter, cumulative seconds | resource instance |
|
||||
| messenger_worker_busy/capacity | gauge, attempts/slots | worker instance |
|
||||
| messenger_process_cpu_seconds_total | counter, Go process CPU seconds | instance |
|
||||
| messenger_container_cpu_seconds_total | counter, cgroup CPU seconds including decoder | instance |
|
||||
| messenger_process_memory_bytes | gauge, Go runtime reserved memory (Sys), не RSS | instance |
|
||||
| messenger_container_memory_bytes/limit_bytes | gauge, cgroup bytes | instance |
|
||||
| messenger_process_last_observed_seconds | gauge, Unix timestamp | instance |
|
||||
| messenger_db_available | gauge, 0/1 | dispatcher |
|
||||
| messenger_telemetry_export_errors | gauge, cumulative SDK export errors | instance |
|
||||
|
||||
`waiting` — незавершённые Acquire; EmptyAcquire counter показывает обращения к пустому пулу. Busy/capacity — текущая занятость обработчиков, а не CPU%. E2E время измерено от created_at job в транзакции durable acceptance до COMMIT ready, включает queue wait и retry. Replay использует исходное время принятия.
|
||||
|
||||
Percentiles вычисляются объединением histogram buckets реплик:
|
||||
|
||||
```promql
|
||||
histogram_quantile(0.95,
|
||||
sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name="messenger-api",route!~"/health/.*"}[1m])))
|
||||
```
|
||||
|
||||
p50 и p99 используют 0.50 и 0.99. Единицы всех duration panels — секунды. Суммируются buckets, не percentiles отдельных реплик. Полные исполняемые запросы находятся в `grafana/dashboards/messenger.json`.
|
||||
|
||||
## Логи и трассы
|
||||
|
||||
API log event `http.request`: timestamp, severity, service.name, method, route template, status, duration_ms, request_id, trace_id, span_id. Worker — `job.started`, `job.completed`; dispatcher — `job.published`.
|
||||
|
||||
Технические request_id/job_id допустимы только в логах/трассах для корреляции синтетических работ. В labels метрик они отсутствуют. SQL text/args, URL/query, filename, headers Authorization, пароли, токены, текст сообщения и содержимое файлов не записываются.
|
||||
|
||||
HTTP server span принимает W3C traceparent/tracestate. Upload транзакционно сохраняет их в job. Producer span публикует свой контекст в разрешённых полях JSON брокера; consumer span извлекает его как parent. Повторы образуют новые producer/consumer ветки того же trace. S3, Redis sessions, DB acquire/query/commit и image.process имеют реальные дочерние spans.
|
||||
|
||||
Log body — структурный JSON, дополнительно отправляемый OTLP Log SDK с trace/span context. В Grafana Loki TraceID derived field открывает Tempo; поиск по trace_id показывает связанные события. Заголовок X-Trace-Id добавлен для диагностики; X-Request-Id и бизнес-контракт сохранены.
|
||||
|
||||
## Буферизация
|
||||
|
||||
SDK: batch queue 256, batch 64, export interval 500 ms, exporter timeout 2 s, retry SDK выключен; metrics interval 2 s. Collector: memory limiter 128 MiB со spike 32 MiB, hard limit контейнера 256 MiB; batch size 64/max128; по 32 batches и 2 consumers для traces/logs, неблокирующее переполнение, retry deadline 5 s. Метрики предоставляются ограниченным набором series на pull endpoint Collector; Prometheus хранит историю в volume. Retention storage — 24 h.
|
||||
|
||||
При отказе telemetry допускаются потери signals. Ошибки SDK учитываются отдельно; Collector показывает failed exports/queue, а финальные drops записывает с dropped_items. Business transaction от успешности экспорта не зависит.
|
||||
@@ -0,0 +1,22 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
ingester:
|
||||
max_block_duration: 1m
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 24h
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
Reference in New Issue
Block a user