forked from mtusi2026/mtusi2026lab6
Compare commits
9
Commits
0bae96f24f
...
dc6a7210e4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc6a7210e4 | ||
|
|
72a84fcb0c | ||
|
|
2538f8a914 | ||
|
|
59279649f4 | ||
|
|
d29163bed4 | ||
|
|
468913998e | ||
|
|
03a4146a62 | ||
|
|
42ecae645b | ||
|
|
b91dcff42a |
@@ -46,6 +46,9 @@ JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
# Worker must set a distinct service.name.
|
||||
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
GRAFANA_ADMIN_PASSWORD=admin
|
||||
+153
-35
@@ -1,9 +1,14 @@
|
||||
x-lab-number: 4
|
||||
x-lab-number: 6
|
||||
x-required-roles:
|
||||
- api
|
||||
- postgres
|
||||
- load_balancer
|
||||
- s3
|
||||
- broker
|
||||
- worker
|
||||
- otel_collector
|
||||
- telemetry_storage
|
||||
- grafana
|
||||
|
||||
services:
|
||||
postgres:
|
||||
@@ -70,8 +75,6 @@ services:
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
# Консоль администратора НЕ публикуется наружу; доступ только из сети compose.
|
||||
# Порт 9000 (S3 API) тоже внутренний — публичного доступа нет.
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
@@ -92,12 +95,8 @@ services:
|
||||
- |
|
||||
set -eu
|
||||
mc alias set local http://minio:9000 "$${MINIO_ROOT_USER}" "$${MINIO_ROOT_PASSWORD}"
|
||||
# Приватный bucket; idempotent.
|
||||
mc mb --ignore-existing local/"$${S3_BUCKET}"
|
||||
# Политика: bucket не публичный. Явно none.
|
||||
mc anonymous set none local/"$${S3_BUCKET}" || true
|
||||
# Прикладные S3-credentials с ограниченными правами на префикс приложения.
|
||||
# Политика выдаётся через `mc admin policy`; создаём отдельного пользователя.
|
||||
if ! mc admin user info local "$${S3_APP_KEY_ID}" >/dev/null 2>&1; then
|
||||
mc admin user add local "$${S3_APP_KEY_ID}" "$${S3_APP_SECRET_KEY}"
|
||||
fi
|
||||
@@ -105,28 +104,15 @@ services:
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::${S3_BUCKET}"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject", "s3:PutObject", "s3:DeleteObject",
|
||||
"s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"
|
||||
],
|
||||
"Resource": ["arn:aws:s3:::${S3_BUCKET}/*"]
|
||||
}
|
||||
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"], "Resource": ["arn:aws:s3:::${S3_BUCKET}"]},
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"], "Resource": ["arn:aws:s3:::${S3_BUCKET}/*"]}
|
||||
]
|
||||
}
|
||||
POLICY
|
||||
# Подставляем имя bucket в политику
|
||||
sed -i "s/\$${S3_BUCKET}/$${S3_BUCKET}/g" /tmp/app-policy.json || true
|
||||
mc admin policy create local messenger-app /tmp/app-policy.json 2>/dev/null || true
|
||||
mc admin policy attach local messenger-app --user "$${S3_APP_KEY_ID}" || true
|
||||
echo "minio-init done"
|
||||
# Административные credentials нужны только здесь и в minio.
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin}
|
||||
@@ -142,9 +128,8 @@ services:
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.storage.db"]
|
||||
# Явный whitelist переменных: без MINIO_ROOT_USER/PASSWORD.
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
@@ -191,7 +176,7 @@ services:
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.worker"]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
@@ -202,6 +187,10 @@ services:
|
||||
S3_APP_KEY_ID: ${S3_APP_KEY_ID}
|
||||
S3_APP_SECRET_KEY: ${S3_APP_SECRET_KEY}
|
||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
@@ -209,6 +198,8 @@ services:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
@@ -221,17 +212,23 @@ services:
|
||||
|
||||
outbox:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.outbox_worker"]
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||
OTEL_SERVICE_NAME: messenger-outbox
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
@@ -241,10 +238,7 @@ services:
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
# Явный whitelist переменных: приложение не получает административные
|
||||
# credentials MinIO (MINIO_ROOT_USER/PASSWORD). Для S3 — только
|
||||
# прикладные S3_APP_KEY_ID/S3_APP_SECRET_KEY с ограниченной политикой.
|
||||
image: mtuci-messenger:lab6
|
||||
environment:
|
||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||
APP_PORT: ${APP_PORT:-8080}
|
||||
@@ -263,6 +257,10 @@ services:
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-300}
|
||||
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-3600}
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
@@ -272,6 +270,8 @@ services:
|
||||
condition: service_healthy
|
||||
minio-init:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready').read()"]
|
||||
interval: 5s
|
||||
@@ -289,13 +289,10 @@ services:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
# Уровень 4: фоновая сверка S3↔БД (orphan-объекты и missing).
|
||||
# Запускается как долгоживущий сервис, спит CLEANUP_INTERVAL_SECONDS.
|
||||
s3_cleanup:
|
||||
build: .
|
||||
image: mtuci-messenger:lab5
|
||||
image: mtuci-messenger:lab6
|
||||
command: ["python", "-m", "app.storage.s3_cleanup"]
|
||||
# Явный whitelist переменных: без административных кредов MinIO.
|
||||
environment:
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
@@ -341,6 +338,119 @@ services:
|
||||
cpus: "0.1"
|
||||
memory: 32M
|
||||
|
||||
# ---------- Observability: lab6 ----------
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.108.0
|
||||
container_name: mtuci-otel-collector
|
||||
command: ["--config=/etc/otel/collector.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
|
||||
depends_on:
|
||||
- tempo
|
||||
- loki
|
||||
- prometheus
|
||||
# Порты OTLP наружу не публикуем: API/worker/outbox в той же сети.
|
||||
# health-порт тоже внутри compose-сети.
|
||||
healthcheck:
|
||||
test: ["CMD", "/otelcol-contrib", "--version"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 256M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 64M
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.54.1
|
||||
container_name: mtuci-prometheus
|
||||
command:
|
||||
- "--config.file=/etc/prometheus/prometheus.yaml"
|
||||
- "--storage.tsdb.path=/prometheus"
|
||||
- "--storage.tsdb.retention.time=15d"
|
||||
- "--web.listen-address=0.0.0.0:9090"
|
||||
volumes:
|
||||
- ./infra/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- ./infra/prometheus/rules:/etc/prometheus/rules:ro
|
||||
- prometheus-data:/prometheus
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.1.1
|
||||
container_name: mtuci-loki
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
volumes:
|
||||
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- loki-data:/loki
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.5.0
|
||||
container_name: mtuci-tempo
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
volumes:
|
||||
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempo-data:/var/tempo
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
reservations:
|
||||
cpus: "0.1"
|
||||
memory: 128M
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.2.0
|
||||
container_name: mtuci-grafana
|
||||
environment:
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "true"
|
||||
GF_AUTH_ANONYMOUS_ORG_ROLE: "Admin"
|
||||
GF_AUTH_DISABLE_LOGIN_FORM: "true"
|
||||
GF_FEATURE_TOGGLES_ENABLE: "traceqlEditor"
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin}
|
||||
volumes:
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- grafana-data:/var/lib/grafana
|
||||
ports:
|
||||
- "127.0.0.1:3000:3000"
|
||||
depends_on:
|
||||
- prometheus
|
||||
- loki
|
||||
- tempo
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.3"
|
||||
memory: 256M
|
||||
reservations:
|
||||
cpus: "0.05"
|
||||
memory: 64M
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
name: mtuci2026lab5_postgres-data
|
||||
@@ -350,7 +460,15 @@ volumes:
|
||||
name: mtuci2026lab5_minio-data
|
||||
rabbitmq-data:
|
||||
name: mtuci2026lab5_rabbitmq-data
|
||||
prometheus-data:
|
||||
name: mtuci2026lab6_prometheus-data
|
||||
loki-data:
|
||||
name: mtuci2026lab6_loki-data
|
||||
tempo-data:
|
||||
name: mtuci2026lab6_tempo-data
|
||||
grafana-data:
|
||||
name: mtuci2026lab6_grafana-data
|
||||
|
||||
networks:
|
||||
default:
|
||||
name: mtuci2026lab5_default
|
||||
name: mtuci2026lab6_default
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — lab6 observability",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"editable": true,
|
||||
"timezone": "browser",
|
||||
"time": {"from": "now-30m", "to": "now"},
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"name": "service",
|
||||
"type": "query",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"query": "label_values(up, job)",
|
||||
"current": {"text": "otel-collector", "value": "otel-collector"}
|
||||
}
|
||||
]
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "timeseries",
|
||||
"title": "API RPS (total)",
|
||||
"gridPos": {"x": 0, "y": 0, "w": 8, "h": 8},
|
||||
"targets": [
|
||||
{"expr": "sum(rate(http_requests_total[1m]))", "legendFormat": "rps"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "API error ratio (5xx / total)",
|
||||
"gridPos": {"x": 8, "y": 0, "w": 8, "h": 8},
|
||||
"targets": [
|
||||
{"expr": "sum(rate(http_requests_total{http_status_class=\"5xx\"}[5m])) / clamp_min(sum(rate(http_requests_total[5m])), 1e-9)", "legendFormat": "ratio"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "HTTP latency p50/p95/p99 (s)",
|
||||
"gridPos": {"x": 16, "y": 0, "w": 8, "h": 8},
|
||||
"targets": [
|
||||
{"expr": "histogram_quantile(0.50, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p50"},
|
||||
{"expr": "histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p95"},
|
||||
{"expr": "histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p99"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Jobs processed by outcome",
|
||||
"gridPos": {"x": 0, "y": 8, "w": 12, "h": 8},
|
||||
"targets": [
|
||||
{"expr": "sum by (outcome) (rate(jobs_processed_total[1m]))", "legendFormat": "{{outcome}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Job duration p95 (s) by outcome",
|
||||
"gridPos": {"x": 12, "y": 8, "w": 12, "h": 8},
|
||||
"targets": [
|
||||
{"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(job_processing_duration_seconds_bucket[5m])))", "legendFormat": "{{outcome}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "logs",
|
||||
"title": "API + worker logs",
|
||||
"gridPos": {"x": 0, "y": 16, "w": 24, "h": 10},
|
||||
"datasource": {"type": "loki", "uid": "loki"},
|
||||
"targets": [
|
||||
{"expr": "{service_name=~\"messenger-api|messenger-worker|messenger-outbox\"}"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
folder: Messenger
|
||||
type: file
|
||||
options:
|
||||
path: /etc/grafana/provisioning/dashboards/json
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,35 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
|
||||
- name: Loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherRegex: 'trace_id=([a-f0-9]+)'
|
||||
datasourceUid: tempo
|
||||
url: "$${__value.raw}"
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
tags:
|
||||
- key: service.name
|
||||
value: service_name
|
||||
filterByTraceID: true
|
||||
@@ -0,0 +1,42 @@
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
replication_factor: 1
|
||||
ring:
|
||||
instance_addr: 127.0.0.1
|
||||
kvstore:
|
||||
store: inmemory
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
retention_period: 168h
|
||||
reject_old_samples: true
|
||||
reject_old_samples_max_age: 168h
|
||||
allow_structured_metadata: true
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
delete_request_store: filesystem
|
||||
retention_enabled: true
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,60 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
|
||||
processors:
|
||||
# Level-4: ограничение RAM и batch, чтобы не расти бесконечно при
|
||||
# недоступном backend и уменьшить объём записи.
|
||||
memory_limiter:
|
||||
check_interval: 2s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 64
|
||||
batch:
|
||||
timeout: 5s
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
resource:
|
||||
attributes:
|
||||
- key: deployment.environment.name
|
||||
value: lab
|
||||
action: upsert
|
||||
|
||||
exporters:
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
tls:
|
||||
insecure: true
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
tls:
|
||||
insecure: true
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
send_timestamps: true
|
||||
metric_expiration: 5m
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: warn
|
||||
metrics:
|
||||
address: 0.0.0.0:8888
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,12 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yaml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
scrape_interval: 5s
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
@@ -0,0 +1,44 @@
|
||||
groups:
|
||||
- name: messenger-alerts
|
||||
interval: 30s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: |
|
||||
sum(rate(http_requests_total{http_status_class="5xx"}[5m]))
|
||||
/
|
||||
sum(rate(http_requests_total[5m]))
|
||||
> 0.05
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "API error rate > 5% over 5m"
|
||||
description: "5xx ratio exceeds SLO 5% for 2 minutes."
|
||||
runbook: "infra/runbooks/high-error-rate.md"
|
||||
|
||||
- alert: MessengerJobsBacklogGrowing
|
||||
expr: |
|
||||
sum(increase(jobs_processed_total{outcome="retry"}[10m]))
|
||||
>
|
||||
sum(increase(jobs_processed_total{outcome="success"}[10m]))
|
||||
+ 5
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Retries outpace successes"
|
||||
description: "Worker retry count exceeds successes for 5m."
|
||||
runbook: "infra/runbooks/queue-lag.md"
|
||||
|
||||
- alert: MessengerUploadLatencyHigh
|
||||
expr: |
|
||||
histogram_quantile(0.95,
|
||||
sum by (le, http_route)
|
||||
(rate(http_request_duration_seconds_bucket{http_route=~"/api/v1/chats/.*/attachments"}[5m]))
|
||||
) > 2
|
||||
for: 3m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "p95 upload latency > 2s"
|
||||
runbook: "infra/runbooks/slow-upload.md"
|
||||
@@ -0,0 +1,19 @@
|
||||
# Alert: MessengerHighErrorRate
|
||||
|
||||
## Симптомы
|
||||
- 5xx rate > 5% в течение 2 минут.
|
||||
- Панель «API error ratio» в Grafana.
|
||||
|
||||
## Диагностика (по шагам)
|
||||
1. Открыть Grafana → Dashboard «Messenger» → p95 latency.
|
||||
2. Открыть Explore → Loki: `{service_name="messenger-api"} |= "event=unhandled_exception"`.
|
||||
3. Найти в логах `request_id`, затем в Tempo trace с этим span или по
|
||||
trace_id из поля `trace_id`.
|
||||
4. Смотрим какие зависимость отвечает: postgres/redis/s3. Соответствующие
|
||||
ошибки пишутся как `event=db_unavailable`, `event=redis_unavailable`,
|
||||
`event=s3_unavailable`.
|
||||
|
||||
## Действие
|
||||
- Если виноват backend — перезапустить (`docker compose restart <service>`).
|
||||
- Если ошибка идёт от кода — rollback через `docker compose up -d --build`
|
||||
предыдущего тега.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Alert: MessengerJobsBacklogGrowing
|
||||
|
||||
## Симптомы
|
||||
- `jobs_processed_total{outcome="retry"}` > `success` + 5 за 10 минут.
|
||||
|
||||
## Диагностика
|
||||
1. Проверить `docker compose ps worker` — процесс жив?
|
||||
2. `docker compose exec rabbitmq rabbitmqctl list_queues name messages consumers`
|
||||
3. Открыть Grafana → «Jobs processed by outcome» и «Job duration p95».
|
||||
4. Открыть Tempo, найти span `job.consume` с ошибкой (status=ERROR).
|
||||
|
||||
## Действие
|
||||
- Если worker упал — `docker compose restart worker`.
|
||||
- Если очередь переполнена по `retry_exhausted` — проверить S3 (`minio`
|
||||
контейнер healthy), затем `docker compose restart s3_cleanup`.
|
||||
- При долгом backlog включить alert `for: 10m` и снизить `MAX_ATTEMPTS` в `.env`
|
||||
для быстрого drain.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Alert: MessengerUploadLatencyHigh
|
||||
|
||||
## Симптомы
|
||||
- p95 длительности POST `/api/v1/chats/{id}/attachments` > 2s.
|
||||
|
||||
## Диагностика
|
||||
1. Grafana: p95 по route `/api/v1/chats/{id}/attachments`.
|
||||
2. Tempo: trace `POST /api/v1/chats/{id}/attachments` — найти самый долгий
|
||||
child span (`put_object` в S3 или `INSERT` в postgres).
|
||||
3. Loki: `{service_name="messenger-api"} |= "event=http" |~ "attachments"`.
|
||||
|
||||
## Действие
|
||||
- Если виноват S3 — проверить `docker compose ps minio`.
|
||||
- Если БД — увеличить `max_size` пула или `statement_timeout`.
|
||||
- Если телеметрия — переключить sampling (см. TRACK1).
|
||||
@@ -0,0 +1,34 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
grpc_listen_port: 9095
|
||||
log_level: warn
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
|
||||
ingester:
|
||||
trace_idle_period: 10s
|
||||
max_block_bytes: 1048576
|
||||
max_block_duration: 5m
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 24h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
local:
|
||||
path: /var/tempo/traces
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
|
||||
metrics_generator:
|
||||
storage:
|
||||
path: /var/tempo/generator/wal
|
||||
+6
-2
@@ -3,7 +3,11 @@ uvicorn[standard]==0.32.0
|
||||
psycopg[binary]==3.2.3
|
||||
psycopg_pool==3.2.3
|
||||
redis==5.2.0
|
||||
openapi-spec-validator==0.7.2
|
||||
boto3==1.35.74
|
||||
Pillow==11.0.0
|
||||
pika==1.3.2
|
||||
pika==1.3.2
|
||||
opentelemetry-api==1.28.2
|
||||
opentelemetry-sdk==1.28.2
|
||||
opentelemetry-exporter-otlp-proto-http==1.28.2
|
||||
opentelemetry-instrumentation-fastapi==0.49b2
|
||||
opentelemetry-instrumentation-requests==0.49b2
|
||||
@@ -1,4 +1,8 @@
|
||||
"""Вложения (lab5): upload → 202 queued, async worker, download вариантов."""
|
||||
"""Вложения (lab5/lab6): upload → 202 queued, async worker, download вариантов.
|
||||
|
||||
lab6: при создании outbox-строки кладём в payload W3C traceparent/tracestate
|
||||
текущего HTTP-запроса. Ошибка инжекта не должна блокировать upload.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
@@ -12,6 +16,7 @@ from fastapi.responses import Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from botocore.exceptions import ClientError
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from ..models.schemas import Attachment, User
|
||||
from ..storage import s3
|
||||
@@ -24,6 +29,7 @@ router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
PIPELINE_VERSION = 1
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
def _require_member(chat_id: UUID, user_id: UUID):
|
||||
@@ -140,6 +146,14 @@ async def upload_attachment(
|
||||
)
|
||||
|
||||
job_id = uuid4()
|
||||
|
||||
# lab6: снимок W3C trace context активного HTTP span.
|
||||
trace_carrier: dict[str, str] = {}
|
||||
try:
|
||||
_propagator.inject(trace_carrier)
|
||||
except Exception:
|
||||
trace_carrier = {}
|
||||
|
||||
outbox_payload = {
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
@@ -147,6 +161,10 @@ async def upload_attachment(
|
||||
"pipeline_version": PIPELINE_VERSION,
|
||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
if trace_carrier.get("traceparent"):
|
||||
outbox_payload["traceparent"] = trace_carrier["traceparent"]
|
||||
if trace_carrier.get("tracestate"):
|
||||
outbox_payload["tracestate"] = trace_carrier["tracestate"]
|
||||
|
||||
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
||||
# При сбое — компенсация: удаляем staging.
|
||||
|
||||
+88
-36
@@ -12,26 +12,21 @@ from fastapi.responses import JSONResponse
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
import psycopg
|
||||
import uvicorn
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
from .api import attachments, auth, chats, health, messages, users
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||
|
||||
|
||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
# Базовый логгер: реальный формат выставит telemetry.install_log_format()
|
||||
# при вызове init_telemetry(). Здесь — минимальный fallback для импорта.
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
logger = logging.getLogger("app")
|
||||
|
||||
# X-Instance-Id: стабильный в пределах жизни процесса. Значение приходит
|
||||
# из env INSTANCE_ID (задаётся Dockerfile/Compose) либо генерируется один раз.
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
init_pool() # пул соединений PostgreSQL с таймаутами
|
||||
init_pool()
|
||||
logger.info(
|
||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||
os.environ.get("APP_ENV", "lab"),
|
||||
@@ -44,12 +39,37 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger — lab5",
|
||||
version="1.5.0",
|
||||
title="MTUCI Messenger — lab6",
|
||||
version="1.6.0",
|
||||
lifespan=lifespan,
|
||||
swagger_ui_parameters={"persistAuthorization": True},
|
||||
)
|
||||
|
||||
# OTel инициализация и FastAPI auto-instrumentation.
|
||||
init_telemetry("messenger-api", "1.6.0")
|
||||
FastAPIInstrumentor.instrument_app(app)
|
||||
|
||||
|
||||
# --- Метрики HTTP ---
|
||||
_http_counter = meter("messenger").create_counter(
|
||||
"http_requests_total",
|
||||
description="HTTP requests count",
|
||||
unit="1",
|
||||
)
|
||||
_http_hist = meter("messenger").create_histogram(
|
||||
"http_request_duration_seconds",
|
||||
description="HTTP request duration",
|
||||
unit="s",
|
||||
)
|
||||
|
||||
# Хелпер: убираем реальные UUID из маршрута → route template.
|
||||
import re as _re
|
||||
_ROUTE_UUID_RE = _re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||
|
||||
|
||||
def _route_template(path: str) -> str:
|
||||
return _ROUTE_UUID_RE.sub("{id}", path)
|
||||
|
||||
|
||||
def custom_openapi():
|
||||
if app.openapi_schema:
|
||||
@@ -61,27 +81,66 @@ def custom_openapi():
|
||||
|
||||
app.openapi = custom_openapi
|
||||
|
||||
# Отдельный tracer для собственного span в middleware. Появляется как
|
||||
# child к server span FastAPI (он активен во время обработки запроса).
|
||||
_http_tracer = tracer("app.http")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observability_middleware(request: Request, call_next):
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог."""
|
||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог + метрики.
|
||||
|
||||
Лог event=http пишется ВНУТРИ активного span (`http.request`), иначе
|
||||
после await call_next() span FastAPI уже закрыт, и в лог попадёт
|
||||
trace_id=000… (это ломало корреляцию лог↔trace в Loki).
|
||||
"""
|
||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||
request.state.request_id = request_id
|
||||
started = time.monotonic()
|
||||
response = await call_next(request)
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
||||
path = request.url.path
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
||||
request.method, path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
route = _route_template(request.url.path)
|
||||
|
||||
# Свой span, дочерний к FastAPI server span. Внутри него — вся обработка
|
||||
# запроса и запись структурированного лога с настоящим trace_id.
|
||||
with _http_tracer.start_as_current_span(
|
||||
"http.request",
|
||||
attributes={
|
||||
"http.method": request.method,
|
||||
"http.route": route,
|
||||
},
|
||||
) as span:
|
||||
response = await call_next(request)
|
||||
duration_s = time.monotonic() - started
|
||||
duration_ms = round(duration_s * 1000, 2)
|
||||
status_class = "%dxx" % (response.status_code // 100)
|
||||
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
|
||||
_http_counter.add(
|
||||
1,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
_http_hist.record(
|
||||
duration_s,
|
||||
{"http.method": request.method, "http.route": route,
|
||||
"http.status_class": status_class},
|
||||
)
|
||||
span.set_attribute("http.status_class", status_class)
|
||||
span.set_attribute("http.status_code", response.status_code)
|
||||
|
||||
# Лог ВНУТРИ span → record.trace_id валидный, Loki получает
|
||||
# корреляцию с Tempo.
|
||||
logger.info(
|
||||
"event=http method=%s path=%s status=%s duration_ms=%s "
|
||||
"request_id=%s instance_id=%s",
|
||||
request.method, request.url.path, response.status_code,
|
||||
duration_ms, request_id, INSTANCE_ID,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
# Словарь HTTP-кодов → кодов ошибок из контракта
|
||||
# --- Обработчики ошибок (без изменений с lab5) ---
|
||||
_ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
@@ -96,22 +155,17 @@ _ERROR_CODES = {
|
||||
|
||||
|
||||
def _unauthorized_challenge(path: str) -> str:
|
||||
"""Basic — только для POST /api/v1/auth/sessions; остальное — Bearer."""
|
||||
if path == "/api/v1/auth/sessions":
|
||||
return 'Basic realm="messenger", charset="UTF-8"'
|
||||
return 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def _error_response(
|
||||
status_code: int, message: str, request_id: str, path: str = ""
|
||||
) -> JSONResponse:
|
||||
def _error_response(status_code: int, message: str, request_id: str,
|
||||
path: str = "") -> JSONResponse:
|
||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||
headers = {}
|
||||
if status_code == 401:
|
||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||
# Контракт: X-Request-Id и X-Instance-Id обязательны во ВСЕХ ответах,
|
||||
# включая 500, которые формируются в обход middleware (exception handlers
|
||||
# срабатывают ПОСЛЕ call_next). Проставляем их здесь явно.
|
||||
headers["X-Request-Id"] = request_id
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return JSONResponse(
|
||||
@@ -136,7 +190,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
||||
|
||||
@app.exception_handler(psycopg.OperationalError)
|
||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||
type(exc).__name__, request_id)
|
||||
@@ -179,12 +232,11 @@ if __name__ == "__main__":
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8080,
|
||||
log_level="info"
|
||||
log_level="info",
|
||||
)
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn."""
|
||||
logger.info("event=sigterm_received signal=%s", signum)
|
||||
server.should_exit = True
|
||||
|
||||
|
||||
+68
-15
@@ -1,8 +1,11 @@
|
||||
"""Outbox worker lab5 level 4: publish неопубликованных job в RabbitMQ.
|
||||
"""Outbox worker lab5/lab6: publish неопубликованных job в RabbitMQ с трейсингом.
|
||||
|
||||
Закрывает разрыв COMMIT → publish: если API упал после COMMIT, outbox
|
||||
осталась в БД; этот процесс опубликует её после рестарта. Publisher
|
||||
confirm гарантирует приём брокером перед mark published.
|
||||
lab6: payload строки outbox содержит traceparent/tracestate, снятые в момент
|
||||
upload-запроса API. Восстанавливаем контекст, создаём span job.publish как
|
||||
child upload-span и инжектим обновлённый traceparent в headers сообщения.
|
||||
|
||||
Лог event=outbox_published пишется ВНУТРИ span job.publish, чтобы в Loki
|
||||
попадал настоящий trace_id (корреляция лог↔trace).
|
||||
"""
|
||||
import logging
|
||||
import signal
|
||||
@@ -10,18 +13,23 @@ import sys
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from opentelemetry import context as otel_context, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from .storage.db import init_pool, close_pool
|
||||
from .storage.postgres import storage
|
||||
from .storage.rabbit import publish_job
|
||||
from .storage.rabbit import QUEUE, publish_job
|
||||
from .telemetry import init_telemetry
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
log = logging.getLogger("outbox")
|
||||
|
||||
_stop = False
|
||||
_tracer = trace.get_tracer("outbox")
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
init_telemetry("messenger-outbox", "1.6.0")
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
@@ -30,6 +38,55 @@ def _handle_sigterm(signum, frame):
|
||||
_stop = True
|
||||
|
||||
|
||||
def _extract_parent(payload: dict) -> otel_context.Context:
|
||||
carrier: dict[str, str] = {}
|
||||
if payload.get("traceparent"):
|
||||
carrier["traceparent"] = str(payload["traceparent"])
|
||||
if payload.get("tracestate"):
|
||||
carrier["tracestate"] = str(payload["tracestate"])
|
||||
if not carrier:
|
||||
return otel_context.Context()
|
||||
try:
|
||||
return _propagator.extract(carrier=carrier)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=trace_parent_parse_failed type=%s", type(exc).__name__)
|
||||
return otel_context.Context()
|
||||
|
||||
|
||||
def _publish_with_trace(payload: dict, outbox_id: int) -> None:
|
||||
"""Публикует payload; mark_published и лог — внутри span."""
|
||||
parent_ctx = _extract_parent(payload)
|
||||
carrier: dict[str, str] = {}
|
||||
with _tracer.start_as_current_span(
|
||||
"job.publish",
|
||||
context=parent_ctx,
|
||||
kind=SpanKind.PRODUCER,
|
||||
attributes={
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE,
|
||||
"job.id": str(payload.get("job_id", "")),
|
||||
"job.type": str(payload.get("type", "unknown")),
|
||||
"outbox.id": int(outbox_id),
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
try:
|
||||
_propagator.inject(carrier)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=trace_inject_failed type=%s", type(exc).__name__)
|
||||
carrier = {}
|
||||
publish_job(payload, extra_headers=carrier)
|
||||
storage.mark_outbox_published(outbox_id)
|
||||
# Лог внутри span → record.trace_id валидный.
|
||||
log.info("event=outbox_published id=%s job_id=%s",
|
||||
outbox_id, payload.get("job_id"))
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception as exc:
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
raise
|
||||
|
||||
|
||||
def main() -> None:
|
||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||
init_pool()
|
||||
@@ -48,16 +105,12 @@ def main() -> None:
|
||||
if _stop:
|
||||
break
|
||||
try:
|
||||
publish_job(payload)
|
||||
storage.mark_outbox_published(outbox_id)
|
||||
log.info("event=outbox_published id=%s job_id=%s",
|
||||
outbox_id, payload.get("job_id"))
|
||||
_publish_with_trace(payload, outbox_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning(
|
||||
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
||||
outbox_id, type(exc).__name__, str(exc)[:300],
|
||||
)
|
||||
# не выходим, попробуем в следующем цикле
|
||||
time.sleep(2)
|
||||
break
|
||||
|
||||
|
||||
@@ -4,10 +4,7 @@
|
||||
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||
- DLQ: финальные ошибки и исчерпанные retry.
|
||||
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||
|
||||
ВАЖНО: setup_topology вызывается в worker при старте и в outbox
|
||||
однократно при первом publish. Не декларируем топологию на каждый
|
||||
publish — иначе гонка с параллельными декларациями.
|
||||
- lab6: extra_headers для traceparent/tracestate.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
@@ -88,14 +85,15 @@ def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> N
|
||||
_topology_ready = True
|
||||
|
||||
|
||||
def publish_job(payload: dict) -> None:
|
||||
"""Публикация job с publisher confirm. Бросает при неудаче."""
|
||||
def publish_job(payload: dict, extra_headers: Optional[dict] = None) -> None:
|
||||
"""Публикация job с publisher confirm. extra_headers — traceparent."""
|
||||
conn = connect()
|
||||
try:
|
||||
ch = conn.channel()
|
||||
ch.confirm_delivery()
|
||||
_ensure_topology(ch)
|
||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||
headers = dict(extra_headers or {})
|
||||
ch.basic_publish(
|
||||
exchange=EXCHANGE,
|
||||
routing_key=QUEUE,
|
||||
@@ -103,6 +101,7 @@ def publish_job(payload: dict) -> None:
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
headers=headers or None,
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Единая точка инициализации OpenTelemetry для API и worker.
|
||||
|
||||
- OTLP/HTTP → Collector (otel-collector:4318).
|
||||
- resource: service.name/version/instance.id/deployment.environment.name=lab.
|
||||
- LoggingFilter подставляет trace_id/span_id в каждую запись, чтобы они
|
||||
попадали и в stdout (видно глазами), и в Loki (в тексте строки) — это
|
||||
требование lab6 level4 (связь лога и trace).
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
|
||||
|
||||
_INITIALIZED = False
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||
|
||||
|
||||
def _endpoint() -> str:
|
||||
return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||
|
||||
|
||||
def _resource(service_name: str, service_version: str) -> Resource:
|
||||
return Resource.create(
|
||||
{
|
||||
"service.name": service_name,
|
||||
"service.version": service_version,
|
||||
"service.instance.id": INSTANCE_ID,
|
||||
"deployment.environment.name": os.environ.get("APP_ENV", "lab"),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _build_trace_provider(resource: Resource) -> TracerProvider:
|
||||
provider = TracerProvider(resource=resource)
|
||||
exporter = OTLPSpanExporter(endpoint=_endpoint() + "/v1/traces", timeout=5)
|
||||
provider.add_span_processor(
|
||||
BatchSpanProcessor(exporter, max_queue_size=2048,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=2000)
|
||||
)
|
||||
return provider
|
||||
|
||||
|
||||
def _build_meter_provider(resource: Resource) -> MeterProvider:
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=_endpoint() + "/v1/metrics", timeout=5),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
return MeterProvider(resource=resource, metric_readers=[reader])
|
||||
|
||||
|
||||
def _build_logger_provider(resource: Resource) -> LoggerProvider:
|
||||
provider = LoggerProvider(resource=resource)
|
||||
provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=_endpoint() + "/v1/logs", timeout=5),
|
||||
max_queue_size=2048,
|
||||
max_export_batch_size=512,
|
||||
schedule_delay_millis=2000,
|
||||
)
|
||||
)
|
||||
return provider
|
||||
|
||||
|
||||
class TraceContextFilter(logging.Filter):
|
||||
"""Подставляет record.trace_id / record.span_id из активного span.
|
||||
|
||||
Если активного span нет — пишет "0"*32 и "0"*16, чтобы лог-формат
|
||||
оставался валидным (не падал с KeyError). Так же OTel сам поступает.
|
||||
"""
|
||||
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
span = trace.get_current_span()
|
||||
span_ctx = span.get_span_context() if span else None
|
||||
if span_ctx is not None and span_ctx.is_valid:
|
||||
record.trace_id = format(span_ctx.trace_id, "032x")
|
||||
record.span_id = format(span_ctx.span_id, "016x")
|
||||
else:
|
||||
record.trace_id = "0" * 32
|
||||
record.span_id = "0" * 16
|
||||
return True
|
||||
|
||||
|
||||
_LOG_FORMAT = (
|
||||
"%(asctime)s %(levelname)s %(name)s "
|
||||
"trace_id=%(trace_id)s span_id=%(span_id)s %(message)s"
|
||||
)
|
||||
|
||||
|
||||
def install_log_format() -> None:
|
||||
"""Единый формат логов API/worker/outbox.
|
||||
|
||||
Поля trace_id/span_id гарантированно существуют благодаря
|
||||
TraceContextFilter. Их наличие обеспечивает уровень 4 (корреляция
|
||||
логов и trace) и делает Loki-запросы `|= "trace_id="` рабочими.
|
||||
"""
|
||||
handler = logging.StreamHandler()
|
||||
handler.addFilter(TraceContextFilter())
|
||||
handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||
root = logging.getLogger()
|
||||
root.handlers = [handler]
|
||||
root.setLevel(logging.INFO)
|
||||
|
||||
|
||||
def init_telemetry(service_name: str, service_version: str = "1.6.0") -> None:
|
||||
"""Идемпотентная инициализация OTel для процесса."""
|
||||
global _INITIALIZED
|
||||
if _INITIALIZED:
|
||||
return
|
||||
|
||||
# Сначала — единый формат логов и фильтр trace_id.
|
||||
install_log_format()
|
||||
|
||||
resource = _resource(service_name, service_version)
|
||||
trace.set_tracer_provider(_build_trace_provider(resource))
|
||||
metrics.set_meter_provider(_build_meter_provider(resource))
|
||||
logger_provider = _build_logger_provider(resource)
|
||||
set_logger_provider(logger_provider)
|
||||
|
||||
# OTel handler шлёт те же записи в Collector → Loki. Он тоже видит
|
||||
# trace_id из record, потому что span-контекст един.
|
||||
#
|
||||
# ВАЖНО: LoggingHandler.emit() формирует тело через self.format(record),
|
||||
# где self.formatter наследуется от logging.Handler. Без явного
|
||||
# formatter'а тело будет голым сообщением (msg % args) — без
|
||||
# trace_id=/span_id=. Это ломало поиск в Loki `|= "trace_id="`.
|
||||
# Поэтому задаём тот же формат и навешиваем TraceContextFilter
|
||||
# непосредственно на OTel-хэндлер: фильтр должен отработать ДО emit,
|
||||
# чтобы record.trace_id существовал на момент форматирования.
|
||||
otel_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
otel_handler.addFilter(TraceContextFilter())
|
||||
otel_handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||
logging.getLogger().addHandler(otel_handler)
|
||||
|
||||
_INITIALIZED = True
|
||||
logging.getLogger("telemetry").info(
|
||||
"event=otel_init service=%s instance_id=%s endpoint=%s",
|
||||
service_name, INSTANCE_ID, _endpoint(),
|
||||
)
|
||||
|
||||
|
||||
def tracer(name: str = "app"):
|
||||
return trace.get_tracer(name)
|
||||
|
||||
|
||||
def meter(name: str = "app"):
|
||||
return metrics.get_meter(name)
|
||||
+107
-86
@@ -1,10 +1,9 @@
|
||||
"""Worker lab5: обработка вложений из RabbitMQ.
|
||||
"""Worker lab5/lab6: обработка вложений из RabbitMQ с трейсингом.
|
||||
|
||||
- at-least-once: manual ack после durable эффекта.
|
||||
- идемпотентность: ключ (attachment_id, pipeline_version, variant).
|
||||
- retry с backoff через TTL retry-очереди, затем DLQ.
|
||||
- lease: processing_until, зависшие возвращаются в queued.
|
||||
- thumbnail 256×256 (JPEG), crop 128×128 (JPEG), optimized WebP 1280×1280.
|
||||
- at-least-once, идемпотентно, retry через TTL-очереди, DLQ.
|
||||
- OTel: consumer span на каждый job, извлечение trace context из заголовков
|
||||
сообщения (W3C traceparent/tracestate).
|
||||
- Метрики: jobs_processed_total{outcome}, job_processing_duration_seconds.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
@@ -13,10 +12,12 @@ import os
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pika
|
||||
from PIL import Image, ImageOps
|
||||
from opentelemetry import context as otel_context, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
from .storage import s3
|
||||
from .storage.db import init_pool, close_pool
|
||||
@@ -25,12 +26,11 @@ from .storage.rabbit import (
|
||||
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
||||
publish_retry, publish_dlq,
|
||||
)
|
||||
from .telemetry import init_telemetry, meter
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
# Базовый логгер настраивается в telemetry.install_log_format() при старте
|
||||
# init_telemetry: trace_id/span_id подставляются фильтром.
|
||||
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||
log = logging.getLogger("worker")
|
||||
|
||||
PIPELINE_VERSION = 1
|
||||
@@ -41,6 +41,19 @@ OPT_SIZE = (1280, 1280)
|
||||
OPT_QUALITY = 82
|
||||
|
||||
_stop = False
|
||||
_propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
# OTel инициализация — до первого сообщения.
|
||||
init_telemetry("messenger-worker", "1.6.0")
|
||||
_tracer = trace.get_tracer("worker")
|
||||
_meter = meter("messenger-worker")
|
||||
_jobs_counter = _meter.create_counter(
|
||||
"jobs_processed_total", description="Jobs processed by outcome", unit="1",
|
||||
)
|
||||
_jobs_hist = _meter.create_histogram(
|
||||
"job_processing_duration_seconds", description="Job processing duration", unit="s",
|
||||
)
|
||||
|
||||
|
||||
def _handle_sigterm(signum, frame):
|
||||
@@ -50,11 +63,11 @@ def _handle_sigterm(signum, frame):
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
from datetime import datetime, timezone
|
||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||
"""Alpha компонуется на белый; EXIF orientation применяется."""
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA", "P"):
|
||||
img = img.convert("RGBA")
|
||||
@@ -67,7 +80,6 @@ def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||
|
||||
|
||||
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""Вписать в 256×256 без увеличения. Округление вниз, минимум 1 px."""
|
||||
w, h = img.size
|
||||
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
@@ -79,7 +91,6 @@ def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
|
||||
|
||||
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""Центрированный квадрат 128×128 (маленькие допускают увеличение)."""
|
||||
w, h = img.size
|
||||
side = min(w, h)
|
||||
left = (w - side) // 2
|
||||
@@ -92,7 +103,6 @@ def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
|
||||
|
||||
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||
"""WebP, вписан в 1280×1280 без увеличения, EXIF удалён."""
|
||||
w, h = img.size
|
||||
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
||||
nw = max(1, int(w * scale))
|
||||
@@ -109,7 +119,7 @@ def _sha256(data: bytes) -> str:
|
||||
|
||||
|
||||
def process_job(payload: dict) -> None:
|
||||
"""Обработка одного job. Идемпотентна: finalize_ready использует ON CONFLICT."""
|
||||
"""Обработка одного job. Идемпотентна через finalize_ready."""
|
||||
attachment_id = payload["attachment_id"]
|
||||
pipeline_version = payload.get("pipeline_version", 1)
|
||||
job_id = payload["job_id"]
|
||||
@@ -117,12 +127,10 @@ def process_job(payload: dict) -> None:
|
||||
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
||||
job_id, attachment_id, payload.get("attempt", 1))
|
||||
|
||||
# 1) Захватить lease. Если уже ready/failed — no-op (дубль).
|
||||
if not storage.claim_processing(attachment_id, LEASE_SECONDS):
|
||||
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
# 2) Получить staging key и метаданные.
|
||||
pair = storage.get_attachment_with_key(attachment_id)
|
||||
if pair is None:
|
||||
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
||||
@@ -132,14 +140,11 @@ def process_job(payload: dict) -> None:
|
||||
log.info("event=already_ready attachment_id=%s", attachment_id)
|
||||
return
|
||||
|
||||
# 3) Скачать staging из S3.
|
||||
try:
|
||||
raw, ctype = s3.get_object(staging_key)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
# Временная ошибка S3 — retry.
|
||||
raise RuntimeError("staging_unavailable") from exc
|
||||
|
||||
# 4) Проверить, что файл всё ещё валиден (worker defense-in-depth).
|
||||
try:
|
||||
img = Image.open(io.BytesIO(raw))
|
||||
img.load()
|
||||
@@ -150,8 +155,6 @@ def process_job(payload: dict) -> None:
|
||||
return
|
||||
|
||||
img_rgb = _to_rgb_white(img)
|
||||
|
||||
# 5) Записать финальный оригинал.
|
||||
final_key = s3.original_key(att.chat_id, att.id)
|
||||
s3.put_bytes(final_key, raw, att.content_type)
|
||||
|
||||
@@ -165,55 +168,38 @@ def process_job(payload: dict) -> None:
|
||||
"sha256": _sha256(raw),
|
||||
}]
|
||||
|
||||
# 6) Thumbnail (обязателен).
|
||||
_, thumb_bytes = _make_thumbnail(img_rgb)
|
||||
thumb_key = s3.variant_key(att.chat_id, att.id, "thumbnail")
|
||||
s3.put_bytes(thumb_key, thumb_bytes, "image/jpeg")
|
||||
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
||||
variants.append({
|
||||
"name": "thumbnail",
|
||||
"object_key": thumb_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(thumb_bytes),
|
||||
"width": tw,
|
||||
"height": th,
|
||||
"sha256": _sha256(thumb_bytes),
|
||||
"name": "thumbnail", "object_key": thumb_key,
|
||||
"content_type": "image/jpeg", "size_bytes": len(thumb_bytes),
|
||||
"width": tw, "height": th, "sha256": _sha256(thumb_bytes),
|
||||
})
|
||||
|
||||
# 7) Crop (level 4).
|
||||
_, crop_bytes = _make_crop(img_rgb)
|
||||
crop_key = s3.variant_key(att.chat_id, att.id, "crop")
|
||||
s3.put_bytes(crop_key, crop_bytes, "image/jpeg")
|
||||
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
||||
variants.append({
|
||||
"name": "crop",
|
||||
"object_key": crop_key,
|
||||
"content_type": "image/jpeg",
|
||||
"size_bytes": len(crop_bytes),
|
||||
"width": cw,
|
||||
"height": ch,
|
||||
"sha256": _sha256(crop_bytes),
|
||||
"name": "crop", "object_key": crop_key,
|
||||
"content_type": "image/jpeg", "size_bytes": len(crop_bytes),
|
||||
"width": cw, "height": ch, "sha256": _sha256(crop_bytes),
|
||||
})
|
||||
|
||||
# 8) Optimized WebP (level 4).
|
||||
_, opt_bytes = _make_optimized(img_rgb)
|
||||
opt_key = s3.variant_key(att.chat_id, att.id, "optimized")
|
||||
s3.put_bytes(opt_key, opt_bytes, "image/webp")
|
||||
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
||||
variants.append({
|
||||
"name": "optimized",
|
||||
"object_key": opt_key,
|
||||
"content_type": "image/webp",
|
||||
"size_bytes": len(opt_bytes),
|
||||
"width": ow,
|
||||
"height": oh,
|
||||
"sha256": _sha256(opt_bytes),
|
||||
"name": "optimized", "object_key": opt_key,
|
||||
"content_type": "image/webp", "size_bytes": len(opt_bytes),
|
||||
"width": ow, "height": oh, "sha256": _sha256(opt_bytes),
|
||||
})
|
||||
|
||||
# 9) Атомарно: variants + status=ready.
|
||||
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
||||
|
||||
# 10) Удалить staging после безопасной фиксации.
|
||||
try:
|
||||
s3.delete_object(staging_key)
|
||||
except Exception:
|
||||
@@ -223,46 +209,81 @@ def process_job(payload: dict) -> None:
|
||||
attachment_id, job_id, len(variants))
|
||||
|
||||
|
||||
def _on_message(ch, method, properties, body):
|
||||
"""Callback consumer. ack/nack — явно."""
|
||||
def _extract_trace_context(properties) -> otel_context.Context:
|
||||
"""Извлекаем W3C traceparent/tracestate из headers. Ошибки → пустой контекст."""
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
except Exception:
|
||||
# Битый JSON — постоянная ошибка.
|
||||
log.error("event=invalid_job_json")
|
||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
headers = dict(properties.headers or {})
|
||||
retry_count = int(headers.get("x-retry-count", 0))
|
||||
payload["attempt"] = retry_count + 1
|
||||
payload["_headers"] = headers
|
||||
|
||||
try:
|
||||
process_job(payload)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
headers = dict(properties.headers or {})
|
||||
carrier = {
|
||||
k.lower(): str(v)
|
||||
for k, v in headers.items()
|
||||
if k.lower() in ("traceparent", "tracestate")
|
||||
}
|
||||
if not carrier:
|
||||
return otel_context.Context()
|
||||
return _propagator.extract(carrier=carrier)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||
# Исчерпаны попытки — failed + DLQ.
|
||||
try:
|
||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||
except Exception:
|
||||
pass
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return
|
||||
# Retry через TTL-очередь, затем ack текущей.
|
||||
log.warning("event=trace_extract_failed type=%s", type(exc).__name__)
|
||||
return otel_context.Context()
|
||||
|
||||
|
||||
def _on_message(ch, method, properties, body):
|
||||
"""Callback consumer. ack/nack — явно. Обёрнуто в consumer span."""
|
||||
parent_ctx = _extract_trace_context(properties)
|
||||
started = time.monotonic()
|
||||
with _tracer.start_as_current_span(
|
||||
"job.consume", context=parent_ctx, kind=SpanKind.CONSUMER,
|
||||
attributes={"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE},
|
||||
) as span:
|
||||
try:
|
||||
publish_retry(payload, retry_count + 1)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
payload = json.loads(body)
|
||||
except Exception:
|
||||
# Не смогли опубликовать retry — вернуть в очередь.
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
log.error("event=invalid_job_json")
|
||||
_jobs_counter.add(1, {"job.type": "unknown", "outcome": "invalid"})
|
||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||
return
|
||||
|
||||
headers = dict(properties.headers or {})
|
||||
retry_count = int(headers.get("x-retry-count", 0))
|
||||
payload["attempt"] = retry_count + 1
|
||||
payload["_headers"] = headers
|
||||
span.set_attribute("job.id", str(payload.get("job_id", "")))
|
||||
span.set_attribute("job.type", str(payload.get("type", "unknown")))
|
||||
span.set_attribute("job.attempt", retry_count + 1)
|
||||
|
||||
try:
|
||||
process_job(payload)
|
||||
duration = time.monotonic() - started
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
duration = time.monotonic() - started
|
||||
span.record_exception(exc)
|
||||
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||
try:
|
||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||
except Exception:
|
||||
pass
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
return
|
||||
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||
try:
|
||||
publish_retry(payload, retry_count + 1)
|
||||
ch.basic_ack(method.delivery_tag)
|
||||
except Exception:
|
||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
@@ -0,0 +1,537 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4 для lab6: сквозной trace API→broker→worker, метрики, логи, dashboard,
|
||||
alert rules, поведение при отказе telemetry-backend.
|
||||
|
||||
Запуск:
|
||||
$env:PYTHONUTF8="1"
|
||||
python student-tests/lab6_test_level4.py --base-url http://localhost:8080
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SAMPLE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
GRAFANA_URL = os.environ.get("GRAFANA_URL", "http://localhost:3000")
|
||||
GRAFANA_ADMIN_USER = os.environ.get("GRAFANA_ADMIN_USER", "admin")
|
||||
GRAFANA_ADMIN_PASSWORD = os.environ.get("GRAFANA_ADMIN_PASSWORD", "admin")
|
||||
|
||||
READY_TIMEOUT = int(os.environ.get("READY_TIMEOUT", "180"))
|
||||
|
||||
|
||||
def _compose_exec(service: str, *args: str, timeout: int = 30):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "exec", "-T", service, *args],
|
||||
cwd=str(ROOT), capture_output=True, text=True, timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def _compose(action: str, service: str, timeout: int = 90):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", action, service],
|
||||
cwd=str(ROOT), capture_output=True, text=True, timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def _compose_logs(service: str, tail: int = 20) -> str:
|
||||
r = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "logs", "--no-color",
|
||||
"--tail=%d" % tail, service],
|
||||
cwd=str(ROOT), capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
return (r.stdout or "") + (r.stderr or "")
|
||||
|
||||
|
||||
def _http_get(url: str, timeout: float = 10.0, basic_auth: tuple | None = None):
|
||||
headers = {"Accept": "application/json"}
|
||||
if basic_auth is not None:
|
||||
token = base64.b64encode(("%s:%s" % basic_auth).encode()).decode()
|
||||
headers["Authorization"] = "Basic " + token
|
||||
req = urllib.request.Request(url, headers=headers, method="GET")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
return resp.status, resp.read().decode("utf-8", "replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode("utf-8", "replace")
|
||||
except (urllib.error.URLError, OSError) as e:
|
||||
return 0, "%s: %s" % (type(e).__name__, e)
|
||||
|
||||
|
||||
def _prom_query(query: str) -> dict:
|
||||
qs = "query=" + urllib.parse.quote(query, safe="")
|
||||
r = _compose_exec(
|
||||
"prometheus", "sh", "-c",
|
||||
"wget -qO- 'http://localhost:9090/api/v1/query?%s'" % qs,
|
||||
)
|
||||
if r.returncode != 0 or not r.stdout.strip():
|
||||
raise Failure("prometheus query failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||
try:
|
||||
return json.loads(r.stdout)
|
||||
except Exception:
|
||||
raise Failure("prometheus non-JSON: %s" % r.stdout[:300])
|
||||
|
||||
|
||||
def _tempo_search(query: str, since_seconds: int = 300, limit: int = 20) -> list[dict]:
|
||||
now = int(time.time())
|
||||
start = now - since_seconds
|
||||
qs = "q=%s&start=%d&end=%d&limit=%d" % (
|
||||
urllib.parse.quote(query, safe=""), start, now, limit,
|
||||
)
|
||||
r = _compose_exec(
|
||||
"tempo", "sh", "-c",
|
||||
"wget -qO- 'http://localhost:3200/api/search?%s'" % qs,
|
||||
)
|
||||
if r.returncode != 0 or not r.stdout.strip():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(r.stdout)
|
||||
except Exception:
|
||||
return []
|
||||
return data.get("traces", []) or []
|
||||
|
||||
|
||||
def _tempo_get_trace(trace_id: str) -> dict:
|
||||
r = _compose_exec(
|
||||
"tempo", "sh", "-c",
|
||||
"wget -qO- 'http://localhost:3200/api/traces/%s'" % trace_id,
|
||||
)
|
||||
if r.returncode != 0 or not r.stdout.strip():
|
||||
raise Failure("tempo trace fetch failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def _tempo_span_names(trace: dict) -> set[str]:
|
||||
names: set[str] = set()
|
||||
for batch in trace.get("batches", []):
|
||||
scopes = batch.get("scopeSpans") or batch.get("instrumentationLibrarySpans") or []
|
||||
for scope in scopes:
|
||||
for span in scope.get("spans", []) or []:
|
||||
names.add(span.get("name", ""))
|
||||
return names
|
||||
|
||||
|
||||
def _loki_query(query: str, since_seconds: int = 300, limit: int = 200) -> dict:
|
||||
end = int(time.time() * 1e9)
|
||||
start = end - since_seconds * 1_000_000_000
|
||||
qs = "query=%s&start=%d&end=%d&limit=%d" % (
|
||||
urllib.parse.quote(query, safe=""), start, end, limit,
|
||||
)
|
||||
r = _compose_exec(
|
||||
"loki", "sh", "-c",
|
||||
"wget -qO- 'http://localhost:3100/loki/api/v1/query_range?%s'" % qs,
|
||||
)
|
||||
if r.returncode != 0 or not r.stdout.strip():
|
||||
raise Failure("loki query failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||
try:
|
||||
return json.loads(r.stdout)
|
||||
except Exception:
|
||||
raise Failure("loki returned non-JSON: %s" % r.stdout[:300])
|
||||
|
||||
|
||||
def _raw_upload(c: Client, actor, chat_id: str, filename: str,
|
||||
data: bytes, ctype: str):
|
||||
qs = urllib.parse.urlencode({"filename": filename}, quote_via=urllib.parse.quote)
|
||||
url = c.base + "/api/v1/chats/" + chat_id + "/attachments?" + qs
|
||||
req = urllib.request.Request(
|
||||
url, data=data, method="POST",
|
||||
headers={
|
||||
"Authorization": "Bearer " + actor["token"],
|
||||
"Content-Type": ctype,
|
||||
},
|
||||
)
|
||||
try:
|
||||
with c.opener.open(req, timeout=30) as resp:
|
||||
return resp.code, json.loads(resp.read()), resp.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read()
|
||||
try:
|
||||
return e.code, json.loads(body), e.headers
|
||||
except Exception:
|
||||
return e.code, None, e.headers
|
||||
|
||||
|
||||
def _wait_ready(c, actor, att, timeout: int) -> dict:
|
||||
"""Обёртка с диагностикой: если долго не ready — показываем статус и логи."""
|
||||
deadline = time.monotonic() + timeout
|
||||
last_status = None
|
||||
while time.monotonic() < deadline:
|
||||
a = c.call("GET", "/api/v1/attachments/" + att["id"], actor=actor,
|
||||
schema="Attachment")["json"]
|
||||
last_status = a.get("status")
|
||||
if last_status == "ready":
|
||||
return a
|
||||
if last_status == "failed":
|
||||
raise Failure("attachment failed: error_code=%r" % a.get("error_code"))
|
||||
time.sleep(0.5)
|
||||
diag = (
|
||||
"\nlast_status=%r (waited %ss)\n--- outbox logs ---\n%s\n--- worker logs ---\n%s"
|
||||
% (last_status, timeout, _compose_logs("outbox", 20),
|
||||
_compose_logs("worker", 20))
|
||||
)
|
||||
raise Failure("attachment did not become ready" + diag)
|
||||
|
||||
|
||||
def _wait_trace_with_spans(since_seconds: int, need_substrings: list[str],
|
||||
timeout: float = 180.0) -> dict:
|
||||
deadline = time.monotonic() + timeout
|
||||
last_seen: list[dict] = []
|
||||
while time.monotonic() < deadline:
|
||||
for svc in ("messenger-api", "messenger-worker", "messenger-outbox"):
|
||||
candidates = _tempo_search(
|
||||
'{resource.service.name = "%s"}' % svc,
|
||||
since_seconds=since_seconds,
|
||||
)
|
||||
for t in candidates:
|
||||
trace_id = t.get("traceID")
|
||||
if not trace_id:
|
||||
continue
|
||||
try:
|
||||
full = _tempo_get_trace(trace_id)
|
||||
except Failure:
|
||||
continue
|
||||
names = _tempo_span_names(full)
|
||||
last_seen.append({"trace_id": trace_id, "names": sorted(names)})
|
||||
if all(any(s in n for n in names) for s in need_substrings):
|
||||
return {"trace_id": trace_id, "names": sorted(names)}
|
||||
time.sleep(3)
|
||||
tail = "; ".join(
|
||||
"%s -> %s" % (x["trace_id"][:8], x["names"][:6]) for x in last_seen[:5]
|
||||
)
|
||||
raise Failure(
|
||||
"не дождались trace со span-names, содержащими %s за %ss; последние trace: %s"
|
||||
% (need_substrings, timeout, tail or "нет")
|
||||
)
|
||||
|
||||
|
||||
def test_trace_api_to_worker(c):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = SAMPLE.read_bytes()
|
||||
started = int(time.time())
|
||||
|
||||
status, att, _ = _raw_upload(c, alice, chat["id"], "sample.png", data, "image/png")
|
||||
check(status == 202, "upload must be 202, got %s" % status)
|
||||
check(att["status"] == "queued", "upload status must be queued")
|
||||
|
||||
ready = _wait_ready(c, alice, att, timeout=READY_TIMEOUT)
|
||||
check(ready["status"] == "ready", "attachment must become ready")
|
||||
|
||||
since = max(60, int(time.time()) - started + 180)
|
||||
trace = _wait_trace_with_spans(
|
||||
since_seconds=since,
|
||||
need_substrings=[
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
"job.publish",
|
||||
"job.consume",
|
||||
],
|
||||
timeout=180,
|
||||
)
|
||||
print(" trace_id:", trace["trace_id"])
|
||||
print(" spans:", ", ".join(trace["names"]))
|
||||
|
||||
|
||||
def test_metrics_in_prometheus(c):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
c.message(alice, chat, "metrics-" + uuid.uuid4().hex)
|
||||
c.message(alice, chat, "metrics-" + uuid.uuid4().hex)
|
||||
data = SAMPLE.read_bytes()
|
||||
status, att, _ = _raw_upload(c, alice, chat["id"], "sample.png", data, "image/png")
|
||||
check(status == 202, "upload must be 202")
|
||||
_wait_ready(c, alice, att, timeout=READY_TIMEOUT)
|
||||
|
||||
deadline = time.monotonic() + 120
|
||||
required = {
|
||||
"http_requests_total",
|
||||
"http_request_duration_seconds_bucket",
|
||||
"jobs_processed_total",
|
||||
"job_processing_duration_seconds_bucket",
|
||||
}
|
||||
got: set[str] = set()
|
||||
while time.monotonic() < deadline:
|
||||
got = set()
|
||||
for name in required:
|
||||
r = _prom_query("count(%s)" % name)
|
||||
series = r.get("data", {}).get("result", [])
|
||||
if series:
|
||||
got.add(name)
|
||||
if got == required:
|
||||
break
|
||||
time.sleep(3)
|
||||
missing = required - got
|
||||
check(not missing, "Prometheus missing metrics: %s" % sorted(missing))
|
||||
print(" metrics in Prometheus:", sorted(got))
|
||||
|
||||
r = _prom_query("count by (http_route, http_status_class) (http_requests_total)")
|
||||
series = r.get("data", {}).get("result", [])
|
||||
check(series, "http_requests_total has no series")
|
||||
import re as _re
|
||||
for s in series:
|
||||
metric = s.get("metric", {})
|
||||
route = metric.get("http_route", "")
|
||||
check(route.startswith("/api/") or route.startswith("/health"),
|
||||
"unexpected http_route: %r" % route)
|
||||
check(_re.search(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
|
||||
route) is None,
|
||||
"http_route contains raw UUID: %r" % route)
|
||||
|
||||
r = _prom_query("sum(jobs_processed_total{outcome=\"success\"})")
|
||||
series = r.get("data", {}).get("result", [])
|
||||
check(series, "jobs_processed_total{outcome=success} absent")
|
||||
value = float(series[0]["value"][1])
|
||||
check(value >= 1, "jobs success metric is %r" % value)
|
||||
print(" jobs_processed_total{outcome=success} =", value)
|
||||
|
||||
|
||||
def test_logs_in_loki(c):
|
||||
time.sleep(15)
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
streams = []
|
||||
while time.monotonic() < deadline:
|
||||
r = _loki_query('{service_name="messenger-api"} |= "event=http"',
|
||||
since_seconds=300)
|
||||
streams = r.get("data", {}).get("result", [])
|
||||
if streams:
|
||||
break
|
||||
time.sleep(3)
|
||||
check(streams, "Loki: no messenger-api logs with event=http")
|
||||
lines = [v[1] for s in streams for v in s.get("values", [])]
|
||||
check(any("request_id=" in line for line in lines),
|
||||
"API logs missing request_id")
|
||||
|
||||
r = _loki_query('{service_name="messenger-worker"} |= "event="', since_seconds=300)
|
||||
check(r.get("data", {}).get("result", []),
|
||||
"Loki: no messenger-worker logs")
|
||||
|
||||
# Ищем запись event=http с ненулевым trace_id (корреляция лог↔trace).
|
||||
deadline = time.monotonic() + 90
|
||||
ok = False
|
||||
while time.monotonic() < deadline:
|
||||
r = _loki_query(
|
||||
'{service_name=~"messenger-api|messenger-worker"} '
|
||||
'|~ "event=(http|job_ready)" |~ "trace_id=" ',
|
||||
since_seconds=300,
|
||||
)
|
||||
streams = r.get("data", {}).get("result", [])
|
||||
for s in streams:
|
||||
for v in s.get("values", []):
|
||||
line = v[1]
|
||||
idx = line.find("trace_id=")
|
||||
if idx < 0:
|
||||
continue
|
||||
tail = line[idx + len("trace_id="):]
|
||||
tid = tail.split()[0].strip()
|
||||
if len(tid) == 32 and set(tid) != {"0"}:
|
||||
ok = True
|
||||
break
|
||||
if ok:
|
||||
break
|
||||
if ok:
|
||||
break
|
||||
time.sleep(3)
|
||||
check(ok, "Loki: no logs with non-zero trace_id (log↔trace correlation)")
|
||||
print(" Loki OK: api+worker logs with non-zero trace_id found")
|
||||
|
||||
|
||||
def test_grafana_provisioning(c):
|
||||
deadline = time.monotonic() + 60
|
||||
auth = (GRAFANA_ADMIN_USER, GRAFANA_ADMIN_PASSWORD)
|
||||
while time.monotonic() < deadline:
|
||||
code, _ = _http_get(GRAFANA_URL + "/api/health")
|
||||
if code == 200:
|
||||
break
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise Failure("Grafana API не поднялась за 60 с")
|
||||
|
||||
code, body = _http_get(GRAFANA_URL + "/api/datasources", basic_auth=auth)
|
||||
check(code == 200, "grafana datasources API %s" % code)
|
||||
datasources = {d["type"]: d for d in json.loads(body)}
|
||||
for t in ("prometheus", "loki", "tempo"):
|
||||
check(t in datasources, "Grafana missing datasource: %s (have %s)"
|
||||
% (t, list(datasources)))
|
||||
print(" datasources:", sorted(datasources))
|
||||
|
||||
code, body = _http_get(GRAFANA_URL + "/api/dashboards/uid/messenger-lab6",
|
||||
basic_auth=auth)
|
||||
check(code == 200, "Grafana dashboard messenger-lab6 not found (%s)" % code)
|
||||
dash = json.loads(body)
|
||||
panels = dash.get("dashboard", {}).get("panels", [])
|
||||
titles = {p.get("title") for p in panels}
|
||||
check(any("p95" in (t or "") for t in titles),
|
||||
"dashboard missing p95 panel")
|
||||
check(any("Jobs" in (t or "") or "job" in (t or "").lower() for t in titles),
|
||||
"dashboard missing jobs panel")
|
||||
print(" dashboard panels:", sorted(t for t in titles if t))
|
||||
|
||||
code, body = _http_get(GRAFANA_URL + "/api/v1/provisioning/alert-rules",
|
||||
basic_auth=auth)
|
||||
check(code == 200, "grafana alert-rules API %s" % code)
|
||||
rules = json.loads(body)
|
||||
check(len(rules) >= 2, "expected >=2 alert rules, got %d" % len(rules))
|
||||
print(" alert rules:", [r.get("title") for r in rules])
|
||||
|
||||
|
||||
def _prom_alerts() -> list[dict]:
|
||||
r = _compose_exec("prometheus", "sh", "-c",
|
||||
"wget -qO- 'http://localhost:9090/api/v1/alerts'")
|
||||
if r.returncode != 0 or not r.stdout.strip():
|
||||
return []
|
||||
try:
|
||||
data = json.loads(r.stdout)
|
||||
except Exception:
|
||||
return []
|
||||
return data.get("data", {}).get("alerts", []) or []
|
||||
|
||||
|
||||
def _wait_alert(name: str, state: str, timeout: float = 240.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
alerts = _prom_alerts()
|
||||
for a in alerts:
|
||||
labels = a.get("labels", {})
|
||||
if labels.get("alertname") == name and a.get("state") == state:
|
||||
return
|
||||
time.sleep(3)
|
||||
raise Failure("alert %s never reached %s" % (name, state))
|
||||
|
||||
|
||||
def test_alert_firing_and_resolved(c):
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
stopped = _compose("stop", "postgres")
|
||||
check(stopped.returncode == 0, "stop postgres failed")
|
||||
|
||||
try:
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/api/v1/users/me", (401, 503), actor=alice)
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
_wait_alert("MessengerHighErrorRate", "firing", timeout=240)
|
||||
print(" MessengerHighErrorRate firing")
|
||||
finally:
|
||||
started = _compose("start", "postgres")
|
||||
check(started.returncode == 0, "start postgres failed")
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/health/ready", 200)
|
||||
break
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise Failure("API didn't become ready after postgres restart")
|
||||
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/api/v1/users/me", 200, actor=alice, schema="User")
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
_wait_alert("MessengerHighErrorRate", "inactive", timeout=300)
|
||||
print(" MessengerHighErrorRate resolved")
|
||||
|
||||
|
||||
def test_telemetry_backend_down(c):
|
||||
for svc in ("tempo", "loki", "prometheus"):
|
||||
_compose("start", svc)
|
||||
time.sleep(3)
|
||||
|
||||
stopped = {}
|
||||
for svc in ("prometheus", "loki", "tempo"):
|
||||
r = _compose("stop", svc)
|
||||
check(r.returncode == 0, "stop %s failed: %s" % (svc, r.stderr[:300]))
|
||||
stopped[svc] = True
|
||||
|
||||
try:
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
deadline = time.monotonic() + 30
|
||||
ok = 0
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/api/v1/users/me", 200, actor=alice, schema="User")
|
||||
c.message(alice, chat, "telem-down-" + uuid.uuid4().hex[:8])
|
||||
ok += 1
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
check(ok >= 5, "API unavailable while telemetry backend is down (ok=%d)" % ok)
|
||||
|
||||
ps = _compose_exec("otel-collector", "true")
|
||||
check(ps.returncode == 0,
|
||||
"otel-collector died while backends were unavailable")
|
||||
|
||||
stats = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}",
|
||||
"mtuci-otel-collector"],
|
||||
capture_output=True, text=True, timeout=15,
|
||||
)
|
||||
if stats.returncode == 0:
|
||||
used = stats.stdout.strip().split("/")[0].strip()
|
||||
mb = None
|
||||
if used.endswith("MiB"):
|
||||
mb = float(used[:-3])
|
||||
elif used.endswith("GiB"):
|
||||
mb = float(used[:-3]) * 1024
|
||||
if mb is not None:
|
||||
check(mb < 260, "otel-collector RSS=%s MiB exceeds limit" % mb)
|
||||
print(" otel-collector RSS while backends down:", mb, "MiB")
|
||||
finally:
|
||||
for svc in stopped:
|
||||
_compose("start", svc)
|
||||
time.sleep(3)
|
||||
|
||||
print(" API and Collector remained healthy while backends were down")
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Lab6 level 4 checks")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
|
||||
print("=== trace API -> broker -> worker (Tempo) ===")
|
||||
test_trace_api_to_worker(c)
|
||||
print("PASS: single trace with upload + job.publish + job.consume")
|
||||
|
||||
print("=== metrics in Prometheus ===")
|
||||
test_metrics_in_prometheus(c)
|
||||
print("PASS: http_requests_total + duration + jobs_processed_total present, "
|
||||
"low-cardinality route labels")
|
||||
|
||||
print("=== logs in Loki ===")
|
||||
test_logs_in_loki(c)
|
||||
print("PASS: structured logs of api+worker with trace_id")
|
||||
|
||||
print("=== Grafana provisioning ===")
|
||||
test_grafana_provisioning(c)
|
||||
print("PASS: dashboard messenger-lab6 + >=2 alert rules provisioned")
|
||||
|
||||
print("=== alert firing and resolved ===")
|
||||
test_alert_firing_and_resolved(c)
|
||||
print("PASS: alert fires on artificial outage and resolves on recovery")
|
||||
|
||||
print("=== telemetry backend down ===")
|
||||
test_telemetry_backend_down(c)
|
||||
print("PASS: API works, Collector stays within memory limit")
|
||||
|
||||
print("PASS: all lab6 level-4 checks passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user