ЛР 6 — БПИ2302 — Нурлыгаянова — на 3

This commit is contained in:
Nurlygayanova Ekaterina
2026-11-13 11:32:45 +03:00
parent 470d9d6f1e
commit 69a190be0e
164 changed files with 25947 additions and 29 deletions
+225
View File
@@ -0,0 +1,225 @@
{
"uid": "messenger-lab6",
"title": "Messenger — Lab 6",
"schemaVersion": 41,
"version": 2,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "API RPS",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by (method,route) (rate(api_requests_total{route!~\"/health/.*\"}[1m]))",
"refId": "A",
"legendFormat": "{{outcome}} {{method}} {{route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"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(api_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(api_requests_total{route!~\"/health/.*\"}[1m])),0.001)",
"refId": "A",
"legendFormat": "{{outcome}} {{method}} {{route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 3,
"title": "API p95 seconds",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum by (le) (rate(api_duration_seconds_bucket{route!~\"/health/.*\"}[1m])))",
"refId": "B",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 4,
"title": "Worker jobs / sec",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by (outcome) (rate(worker_jobs_total[1m]))",
"refId": "A",
"legendFormat": "{{outcome}} {{method}} {{route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 5,
"title": "Worker p95 seconds",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum by (le) (rate(worker_duration_seconds_bucket[1m])))",
"refId": "A",
"legendFormat": "{{outcome}} {{method}} {{route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 6,
"title": "Worker total attempts",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by (outcome) (worker_jobs_total)",
"refId": "A",
"legendFormat": "{{outcome}} {{method}} {{route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 7,
"title": "API and worker structured logs",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 24,
"h": 10
},
"targets": [
{
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
"refId": "A"
}
]
},
{
"id": 8,
"title": "Real application traces",
"type": "table",
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"gridPos": {
"x": 0,
"y": 34,
"w": 24,
"h": 8
},
"targets": [
{
"queryType": "traceql",
"query": "{resource.service.name =~ \"messenger-api|messenger-worker\"}",
"refId": "A",
"limit": 20
}
]
}
]
}
@@ -0,0 +1,7 @@
apiVersion: 1
providers:
- name: messenger
folder: Lab6
type: file
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,30 @@
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
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
tags: [{key: service.name, value: service_name}]
+54
View File
@@ -0,0 +1,54 @@
global
log stdout format raw local0 info
resolvers docker
nameserver dns 127.0.0.11:53
accepted_payload_size 8192
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 5s
hold obsolete 5s
defaults
mode http
log global
option httplog
option dontlognull
retries 2
retry-on conn-failure
option redispatch 1
timeout connect 500ms
timeout client 30s
timeout server 15s
timeout http-request 10s
timeout http-keep-alive 30s
timeout queue 5s
timeout check 1500ms
# Ответы самого LB в формате контракта: схема Error и X-Request-Id, совпадающий с request_id.
# Контракт разрешает таким ответам не иметь X-Instance-Id. Ответы реплик эти правила не меняют.
http-error status 502 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"%[var(txn.request_id)]"}}'
http-error status 503 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"%[var(txn.request_id)]"}}'
http-error status 504 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"%[var(txn.request_id)]"}}'
frontend public
bind :8080
# Идентификатор для ответов самого LB. У ответов реплик свой X-Request-Id.
http-request set-var(txn.request_id) uuid()
default_backend api
backend api
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
default-server check init-state down inter 1s fall 2 rise 2 observe layer4 error-limit 2 on-error mark-down resolvers docker init-addr none resolve-prefer ipv4
server-template api 1-8 api:8080
frontend stats
bind 127.0.0.1:8404
monitor-uri /health
stats enable
stats uri /stats
+30 -4
View File
@@ -1,7 +1,33 @@
# Конфигурация наблюдаемости — реализовать
# Сигналы lab6 (оценка 3)
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
API Go OTel SDK 1.38.0 (logs 0.14.0) и worker Python OTel SDK 1.38.0
отправляют HTTP/protobuf OTLP в `otel-collector:4318`.
Collector 0.137.0: OTLP receiver → memory_limiter → batch → exporters.
Prometheus опрашивает exporter 8889 каждые 5 секунд и хранит метрики.
Loki принимает структурные логи через native OTLP, Tempo хранит трассы.
Grafana запрашивает эти три хранилища. Persistent volumes сохраняют историю,
retention 72 часа. Очереди и память ограничены; при долгом отказе возможны потери.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Dashboard: `infra/grafana/dashboards/messenger.json`, 8 панелей, автоматический provisioning.
http://localhost:3000/d/messenger-lab6 — RPS, доля 5xx, API p95, jobs и worker p95,
структурные логи и поиск реальных трасс. p95 вычисляется из суммы histogram buckets.
HTTP health исключён из бизнес-панелей; error ratio = 5xx / все бизнес-запросы.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Метрики:
- `api_requests_total{method,route,status_class}` — запросы;
- `api_duration_seconds_bucket` — histogram в секундах;
- `worker_jobs_total{job_type,outcome}` — попытки обработки;
- `worker_duration_seconds_bucket` — длительность попытки в секундах.
Логи содержат timestamp/severity/service.name/event/trace_id/span_id,
API добавляет request_id. Ответ содержит X-Trace-Id и X-Request-Id.
Loki: `{service_name="messenger-api"} | trace_id="ID"`, затем тот же ID в Tempo.
Worker: `{service_name="messenger-worker"} | event="job.success"`.
API SERVER и worker CONSUMER spans окружают реальные операции.
Контекст через очередь поддержан реализацией, но уровни 4/5 не заявлены.
UUID/raw URL/request_id не используются как labels метрик; секреты, тела,
картинки, headers, signed URLs и exception text не экспортируются.
Проверки: `python3 student-tests/observability.py`, `python3 student-tests/incidents.py`.
Вторая временно останавливает worker и S3 своего Compose-проекта и восстанавливает их.
SLO/alert rules и исследовательского эксперимента в варианте на 3 нет.
+55
View File
@@ -0,0 +1,55 @@
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: 2s
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: 3s
sending_queue:
queue_size: 256
retry_on_failure:
max_elapsed_time: 30s
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 3s
sending_queue:
queue_size: 256
retry_on_failure:
max_elapsed_time: 30s
service:
telemetry:
metrics:
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]
+32
View File
@@ -0,0 +1,32 @@
auth_enabled: false
server:
http_listen_port: 3100
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-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 72h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+11
View File
@@ -0,0 +1,11 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
scrape_configs:
- job_name: messenger
static_configs:
- targets: ['otel-collector:8889']
- job_name: collector
static_configs:
- targets: ['otel-collector:8888']
+20
View File
@@ -0,0 +1,20 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 72h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
+37
View File
@@ -0,0 +1,37 @@
# Единственный путь к SeaweedFS из сети стенда: пропускает только порт S3 (9000).
# Нужен потому, что флаг -s3.ip.bind открывает на всех интерфейсах и служебный gRPC-порт шлюза 19000,
# отдельно его не закрыть. Сам SeaweedFS находится во внутренней сети, куда входит только этот шлюз.
# Режим TCP: подпись S3 проверяет сервер, заголовок Host не меняется.
global
log stdout format raw local0 warning
resolvers docker
nameserver dns 127.0.0.11:53
hold valid 2s
hold obsolete 2s
timeout resolve 1s
timeout retry 1s
defaults
log global
timeout connect 1s
# Больше передачи файла в API (60 с).
timeout client 90s
timeout server 90s
frontend s3
mode tcp
bind :9000
default_backend storage
backend storage
mode tcp
# Имя s3-storage существует только во внутренней сети. После перезапуска адрес определяется заново.
default-server check inter 1s fall 2 rise 1 init-addr none resolvers docker resolve-prefer ipv4
server s3 s3-storage:9000
frontend health
mode http
bind 127.0.0.1:8405
monitor-uri /health
+4
View File
@@ -0,0 +1,4 @@
# Allocate one volume at a time for this single-node teaching setup.
# The default batch of seven quickly exhausts volume slots across buckets.
[master.volume_growth]
copy_1 = 1