forked from mtusi2026/mtusi2026lab6
Реализовать минимум наблюдаемости: OTLP, хранилища и Grafana
This commit is contained in:
@@ -0,0 +1,6 @@
|
|||||||
|
* text=auto
|
||||||
|
*.sh text eol=lf
|
||||||
|
*.py text eol=lf
|
||||||
|
*.yaml text eol=lf
|
||||||
|
*.sql text eol=lf
|
||||||
|
*.cmd text eol=crlf
|
||||||
+62
-1
@@ -2,8 +2,10 @@ name: lyakhonov-lab6
|
|||||||
|
|
||||||
x-app: &app
|
x-app: &app
|
||||||
image: lyakhonov-messenger:lab6
|
image: lyakhonov-messenger:lab6
|
||||||
build: .
|
|
||||||
environment:
|
environment:
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
|
||||||
|
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-1}
|
||||||
|
TRACE_SAMPLE_RATIO: ${TRACE_SAMPLE_RATIO:-1}
|
||||||
DATABASE_URL_FILE: /run/secrets/database_url
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
S3_ENDPOINT: http://s3:9000
|
S3_ENDPOINT: http://s3:9000
|
||||||
S3_ACCESS_KEY_FILE: /run/secrets/s3_access_key
|
S3_ACCESS_KEY_FILE: /run/secrets/s3_access_key
|
||||||
@@ -28,6 +30,58 @@ x-dependencies: &dependencies
|
|||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
|
|
||||||
services:
|
services:
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.137.0
|
||||||
|
command: [--config=/etc/otelcol/config.yaml]
|
||||||
|
volumes: [./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 256m
|
||||||
|
restart: unless-stopped
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.7.3
|
||||||
|
command: [--config.file=/etc/prometheus/prometheus.yaml, --storage.tsdb.retention.time=24h, --storage.tsdb.retention.size=512MB]
|
||||||
|
volumes: [./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro, ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro, metrics_data:/prometheus]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 384m
|
||||||
|
restart: unless-stopped
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.5.7
|
||||||
|
command: [-config.file=/etc/loki/config.yaml]
|
||||||
|
volumes: [./infra/otel/loki.yaml:/etc/loki/config.yaml:ro, logs_data:/loki]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 384m
|
||||||
|
restart: unless-stopped
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.9.0
|
||||||
|
command: [-config.file=/etc/tempo.yaml]
|
||||||
|
volumes: [./infra/otel/tempo.yaml:/etc/tempo.yaml:ro, traces_data:/var/tempo]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 384m
|
||||||
|
restart: unless-stopped
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:12.2.1
|
||||||
|
ports: ['127.0.0.1:${GRAFANA_PORT:-3006}:3000']
|
||||||
|
environment:
|
||||||
|
GF_AUTH_ANONYMOUS_ENABLED: 'true'
|
||||||
|
GF_AUTH_ANONYMOUS_ORG_ROLE: Viewer
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||||
|
GF_ANALYTICS_REPORTING_ENABLED: 'false'
|
||||||
|
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
|
||||||
|
secrets: [grafana_password]
|
||||||
|
volumes: [grafana_data:/var/lib/grafana, ./infra/grafana/provisioning:/etc/grafana/provisioning:ro, ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 384m
|
||||||
|
restart: unless-stopped
|
||||||
|
diagnostics:
|
||||||
|
<<: *app
|
||||||
|
command: [python, -m, src.diagnostics]
|
||||||
|
depends_on: *dependencies
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 128m
|
||||||
|
restart: unless-stopped
|
||||||
inspector:
|
inspector:
|
||||||
<<: *app
|
<<: *app
|
||||||
profiles: [tools]
|
profiles: [tools]
|
||||||
@@ -107,6 +161,7 @@ services:
|
|||||||
disable: true
|
disable: true
|
||||||
api:
|
api:
|
||||||
<<: *app
|
<<: *app
|
||||||
|
build: .
|
||||||
depends_on: *dependencies
|
depends_on: *dependencies
|
||||||
deploy:
|
deploy:
|
||||||
replicas: ${API_REPLICAS:-2}
|
replicas: ${API_REPLICAS:-2}
|
||||||
@@ -155,6 +210,8 @@ services:
|
|||||||
stop_grace_period: 12s
|
stop_grace_period: 12s
|
||||||
|
|
||||||
secrets:
|
secrets:
|
||||||
|
grafana_password:
|
||||||
|
file: ./secrets/grafana_password
|
||||||
s3_root_user:
|
s3_root_user:
|
||||||
file: ./secrets/s3_root_user
|
file: ./secrets/s3_root_user
|
||||||
s3_root_password:
|
s3_root_password:
|
||||||
@@ -175,3 +232,7 @@ volumes:
|
|||||||
postgres_data:
|
postgres_data:
|
||||||
s3_data:
|
s3_data:
|
||||||
broker_data:
|
broker_data:
|
||||||
|
metrics_data:
|
||||||
|
logs_data:
|
||||||
|
traces_data:
|
||||||
|
grafana_data:
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: real OTLP signals, connected producer/consumer/S3/DB graph, logs, metric labels, 24 concurrent replays and negative checks
|
||||||
+17333
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
|||||||
|
PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
@@ -0,0 +1,359 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-lab6",
|
||||||
|
"title": "Messenger: API, jobs and SLO",
|
||||||
|
"schemaVersion": 41,
|
||||||
|
"version": 1,
|
||||||
|
"refresh": "5s",
|
||||||
|
"time": {
|
||||||
|
"from": "now-30m",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "HTTP successful RPS",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum(rate(messenger_http_requests_total{status_class!=\"5xx\"}[1m]))",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "HTTP error ratio",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 0,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])),0.001)",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "API p50/p95/p99",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 8,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.5,sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "0.5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.95,sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "B",
|
||||||
|
"legendFormat": "0.95"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.99,sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "C",
|
||||||
|
"legendFormat": "0.99"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Jobs by outcome",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 8,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum by (outcome)(rate(messenger_jobs_total[1m]))",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "ops"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Worker p95",
|
||||||
|
"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(messenger_job_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Queue depth",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 16,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "messenger_queue_depth",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "Oldest unfinished job",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 24,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "messenger_queue_oldest_seconds",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "DB pool used / waiting",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 24,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "{__name__=~\"messenger_db_pool_(used|waiting)\"}",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"title": "Worker busy / capacity",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 32,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "{__name__=~\"messenger_worker_(busy|capacity)\"}",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"title": "Time to ready p95",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 32,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "histogram_quantile(0.95,sum by (le)(rate(messenger_ready_duration_seconds_bucket[1m])))",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"title": "Process maximum RSS",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 40,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "messenger_process_maxrss_bytes",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 12,
|
||||||
|
"title": "Process CPU cores",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 40,
|
||||||
|
"w": 12,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"expr": "sum by (service_name)(rate(messenger_process_cpu_seconds_total[1m]))",
|
||||||
|
"refId": "A",
|
||||||
|
"legendFormat": "{{service_name}} {{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: messenger
|
||||||
|
type: file
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
url: http://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
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
|
||||||
|
url: http://tempo:3200
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
spanStartTimeShift: '-1m'
|
||||||
|
spanEndTimeShift: '1m'
|
||||||
|
filterByTraceID: true
|
||||||
|
tags: [{key: service.name, value: service_name}]
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger-slo
|
||||||
|
interval: 5s
|
||||||
|
rules:
|
||||||
|
- alert: HighAPIErrorRate
|
||||||
|
expr: sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_requests_total[30s])),0.001)
|
||||||
|
> 0.1
|
||||||
|
for: 10s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: API 5xx >10%; inspect DB spans and pool
|
||||||
|
runbook: RUNBOOK.md
|
||||||
|
- alert: QueueLag
|
||||||
|
expr: messenger_queue_oldest_seconds > 10 and messenger_queue_depth > 0
|
||||||
|
for: 10s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: Unfinished job age >10s; inspect worker busy/capacity and consume logs
|
||||||
|
runbook: RUNBOOK.md
|
||||||
|
- alert: APIBurnFast
|
||||||
|
expr: (sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_requests_total[30s])),0.001)
|
||||||
|
/ 0.01 > 14.4) and (sum(rate(messenger_http_requests_total{status_class="5xx"}[2m]))
|
||||||
|
/ clamp_min(sum(rate(messenger_http_requests_total[2m])),0.001) / 0.01 > 14.4)
|
||||||
|
for: 15s
|
||||||
|
labels:
|
||||||
|
severity: critical
|
||||||
|
annotations:
|
||||||
|
summary: API budget burn >14.4 in 30s AND 2m
|
||||||
|
runbook: RUNBOOK.md#api
|
||||||
|
- alert: ReadyBurnFast
|
||||||
|
expr: (sum(messenger_ready_window_bad{window="30s"}) / clamp_min(sum(messenger_ready_window_total{window="30s"}),1)
|
||||||
|
/ 0.05 > 6) and (sum(messenger_ready_window_bad{window="2m"}) / clamp_min(sum(messenger_ready_window_total{window="2m"}),1)
|
||||||
|
/ 0.05 > 6)
|
||||||
|
for: 15s
|
||||||
|
labels:
|
||||||
|
severity: critical
|
||||||
|
annotations:
|
||||||
|
summary: Time-to-ready budget burn in 30s AND 2m, unfinished/failed included
|
||||||
|
runbook: RUNBOOK.md#ready
|
||||||
|
- alert: APIBurnSlow
|
||||||
|
expr: (sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])),0.001)
|
||||||
|
/ 0.01 > 6) and (sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
|
||||||
|
/ clamp_min(sum(rate(messenger_http_requests_total[5m])),0.001) / 0.01 > 6)
|
||||||
|
for: 30s
|
||||||
|
labels:
|
||||||
|
severity: critical
|
||||||
|
annotations:
|
||||||
|
summary: API budget burn >6 in 1m AND 5m
|
||||||
|
runbook: RUNBOOK.md#api
|
||||||
|
- alert: ReadyBurnSlow
|
||||||
|
expr: (sum(messenger_ready_window_bad{window="1m"}) / clamp_min(sum(messenger_ready_window_total{window="1m"}),1)
|
||||||
|
/ 0.05 > 3) and (sum(messenger_ready_window_bad{window="5m"}) / clamp_min(sum(messenger_ready_window_total{window="5m"}),1)
|
||||||
|
/ 0.05 > 3)
|
||||||
|
for: 30s
|
||||||
|
labels:
|
||||||
|
severity: critical
|
||||||
|
annotations:
|
||||||
|
summary: Time-to-ready budget burn in 1m AND 5m, unfinished/failed included
|
||||||
|
runbook: RUNBOOK.md#ready
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 160
|
||||||
|
spike_limit_mib: 32
|
||||||
|
batch:
|
||||||
|
timeout: 1s
|
||||||
|
send_batch_size: 128
|
||||||
|
send_batch_max_size: 256
|
||||||
|
exporters:
|
||||||
|
prometheus:
|
||||||
|
endpoint: 0.0.0.0:8889
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
otlphttp/tempo:
|
||||||
|
endpoint: http://tempo:4318
|
||||||
|
timeout: 2s
|
||||||
|
retry_on_failure:
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 5s
|
||||||
|
max_elapsed_time: 15s
|
||||||
|
sending_queue:
|
||||||
|
queue_size: 128
|
||||||
|
num_consumers: 2
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: http://loki:3100/otlp
|
||||||
|
timeout: 2s
|
||||||
|
retry_on_failure:
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 5s
|
||||||
|
max_elapsed_time: 15s
|
||||||
|
sending_queue:
|
||||||
|
queue_size: 128
|
||||||
|
num_consumers: 2
|
||||||
|
service:
|
||||||
|
telemetry:
|
||||||
|
metrics:
|
||||||
|
level: detailed
|
||||||
|
readers:
|
||||||
|
- pull:
|
||||||
|
exporter:
|
||||||
|
prometheus:
|
||||||
|
host: 0.0.0.0
|
||||||
|
port: 8888
|
||||||
|
pipelines:
|
||||||
|
traces:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/tempo]
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [prometheus]
|
||||||
|
logs:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
common:
|
||||||
|
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,14 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 5s
|
||||||
|
evaluation_interval: 5s
|
||||||
|
rule_files: [/etc/prometheus/alerts.yaml]
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: application
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:8889]
|
||||||
|
- job_name: collector
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:8888]
|
||||||
|
- job_name: backlog
|
||||||
|
static_configs:
|
||||||
|
- targets: [diagnostics:9099]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
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: 24h
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/blocks
|
||||||
|
usage_report:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE attachment_jobs ADD COLUMN trace_context jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||||
+51
-20
@@ -1,35 +1,66 @@
|
|||||||
annotated-types==0.8.0
|
annotated-types==0.8.0
|
||||||
anyio==4.15.1
|
anyio==4.16.0
|
||||||
argon2-cffi==23.1.0
|
argon2-cffi==23.1.0
|
||||||
argon2-cffi-bindings==26.1.0
|
argon2-cffi-bindings==26.2.0
|
||||||
|
attrs==26.1.0
|
||||||
|
boto3==1.40.61
|
||||||
|
botocore==1.40.76
|
||||||
|
certifi==2026.11.20
|
||||||
cffi==2.1.1
|
cffi==2.1.1
|
||||||
click==8.5.0
|
charset-normalizer==3.5.3
|
||||||
|
click==8.5.1
|
||||||
|
colorama==0.4.6
|
||||||
fastapi==0.115.0
|
fastapi==0.115.0
|
||||||
|
googleapis-common-protos==1.76.0
|
||||||
h11==0.16.0
|
h11==0.16.0
|
||||||
httptools==0.8.0
|
httptools==0.9.0
|
||||||
idna==3.20
|
idna==3.20
|
||||||
|
importlib_metadata==8.7.1
|
||||||
|
jmespath==1.1.0
|
||||||
|
jsonschema==4.26.0
|
||||||
|
jsonschema-path==0.3.4
|
||||||
|
jsonschema-specifications==2025.9.1
|
||||||
|
lazy-object-proxy==1.13.0
|
||||||
|
openapi-schema-validator==0.6.3
|
||||||
|
openapi-spec-validator==0.7.2
|
||||||
|
opentelemetry-api==1.38.0
|
||||||
|
opentelemetry-exporter-otlp-proto-common==1.38.0
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.38.0
|
||||||
|
opentelemetry-instrumentation==0.59b0
|
||||||
|
opentelemetry-instrumentation-botocore==0.59b0
|
||||||
|
opentelemetry-instrumentation-dbapi==0.59b0
|
||||||
|
opentelemetry-instrumentation-psycopg==0.59b0
|
||||||
|
opentelemetry-propagator-aws-xray==1.0.2
|
||||||
|
opentelemetry-proto==1.38.0
|
||||||
|
opentelemetry-sdk==1.38.0
|
||||||
|
opentelemetry-semantic-conventions==0.59b0
|
||||||
|
packaging==26.4
|
||||||
|
pathable==0.4.4
|
||||||
|
pika==1.3.2
|
||||||
|
pillow==12.0.0
|
||||||
|
protobuf==6.33.6
|
||||||
psycopg==3.2.3
|
psycopg==3.2.3
|
||||||
psycopg-binary==3.2.3
|
psycopg-binary==3.2.3
|
||||||
psycopg-pool==3.2.4
|
psycopg-pool==3.2.4
|
||||||
pycparser==3.1
|
pycparser==3.12
|
||||||
pydantic==2.9.2
|
pydantic==2.9.2
|
||||||
pydantic_core==2.23.4
|
pydantic_core==2.23.4
|
||||||
|
python-dateutil==2.9.0.post0
|
||||||
python-dotenv==1.2.4
|
python-dotenv==1.2.4
|
||||||
PyYAML==6.0.3
|
PyYAML==6.0.4
|
||||||
|
redis==5.2.0
|
||||||
|
referencing==0.36.2
|
||||||
|
requests==2.34.2
|
||||||
|
rfc3339-validator==0.1.4
|
||||||
|
rpds-py==2026.9.1
|
||||||
|
s3transfer==0.14.0
|
||||||
|
six==1.17.0
|
||||||
starlette==0.38.6
|
starlette==0.38.6
|
||||||
typing_extensions==4.16.0
|
typing_extensions==4.16.0
|
||||||
uvicorn==0.32.0
|
tzdata==2026.6
|
||||||
uvloop==0.23.0
|
|
||||||
watchfiles==1.3.0
|
|
||||||
websockets==17.2
|
|
||||||
redis==5.2.0
|
|
||||||
|
|
||||||
boto3==1.40.61
|
|
||||||
Pillow==12.0.0
|
|
||||||
pika==1.3.2
|
|
||||||
botocore==1.40.76
|
|
||||||
s3transfer==0.14.0
|
|
||||||
jmespath==1.1.0
|
|
||||||
python-dateutil==2.9.0.post0
|
|
||||||
six==1.17.0
|
|
||||||
urllib3==2.8.0
|
urllib3==2.8.0
|
||||||
|
uvicorn==0.32.0
|
||||||
|
watchfiles==1.3.0
|
||||||
|
websockets==17.4
|
||||||
|
wrapt==1.17.3
|
||||||
|
zipp==4.1.2
|
||||||
|
|||||||
@@ -9,3 +9,8 @@ redis==5.2.0
|
|||||||
boto3==1.40.61
|
boto3==1.40.61
|
||||||
Pillow==12.0.0
|
Pillow==12.0.0
|
||||||
pika==1.3.2
|
pika==1.3.2
|
||||||
|
|
||||||
|
opentelemetry-sdk==1.38.0
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.38.0
|
||||||
|
opentelemetry-instrumentation-psycopg==0.59b0
|
||||||
|
opentelemetry-instrumentation-botocore==0.59b0
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ def main():
|
|||||||
directory = ROOT / 'secrets'
|
directory = ROOT / 'secrets'
|
||||||
directory.mkdir(mode=0o700, exist_ok=True)
|
directory.mkdir(mode=0o700, exist_ok=True)
|
||||||
for name in ('db_password', 'broker_password', 's3_root_user', 's3_root_password',
|
for name in ('db_password', 'broker_password', 's3_root_user', 's3_root_password',
|
||||||
's3_access_key', 's3_secret_key'):
|
's3_access_key', 's3_secret_key', 'grafana_password'):
|
||||||
create(directory / name, token_hex(24))
|
create(directory / name, token_hex(24))
|
||||||
db = quote((directory / 'db_password').read_text(encoding='utf-8').strip(), safe='')
|
db = quote((directory / 'db_password').read_text(encoding='utf-8').strip(), safe='')
|
||||||
broker = quote((directory / 'broker_password').read_text(encoding='utf-8').strip(), safe='')
|
broker = quote((directory / 'broker_password').read_text(encoding='utf-8').strip(), safe='')
|
||||||
|
|||||||
@@ -18,6 +18,10 @@ from botocore.exceptions import BotoCoreError, ClientError
|
|||||||
from src.storage import storage
|
from src.storage import storage
|
||||||
|
|
||||||
|
|
||||||
|
from src import telemetry
|
||||||
|
telemetry.setup("messenger-api")
|
||||||
|
telemetry.register_gauges(storage.pool)
|
||||||
|
|
||||||
def create_app() -> FastAPI:
|
def create_app() -> FastAPI:
|
||||||
"""Создать и настроить приложение FastAPI."""
|
"""Создать и настроить приложение FastAPI."""
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
@@ -159,6 +163,7 @@ def create_app() -> FastAPI:
|
|||||||
app.include_router(messages.router)
|
app.include_router(messages.router)
|
||||||
app.include_router(attachments.router)
|
app.include_router(attachments.router)
|
||||||
|
|
||||||
|
app.add_middleware(telemetry.HTTPMiddleware)
|
||||||
return app
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
"""Internal exporter: durable backlog, including jobs not yet published to broker."""
|
||||||
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||||
|
from src.storage import storage
|
||||||
|
|
||||||
|
|
||||||
|
class Handler(BaseHTTPRequestHandler):
|
||||||
|
def log_message(self, *args):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def do_GET(self):
|
||||||
|
try:
|
||||||
|
with storage.pool.connection() as conn:
|
||||||
|
row = conn.execute("SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM "
|
||||||
|
"clock_timestamp()-min(created_at)),0) AS age FROM attachment_jobs "
|
||||||
|
"WHERE state IN ('queued','processing')").fetchone()
|
||||||
|
windows = {}
|
||||||
|
for window, seconds in [('30s',30),('1m',60),('2m',120),('5m',300)]:
|
||||||
|
result = conn.execute("SELECT count(*) AS total, count(*) FILTER (WHERE "
|
||||||
|
"state <> 'ready' OR updated_at-created_at > interval '5 seconds') AS bad "
|
||||||
|
"FROM attachments WHERE created_at <= clock_timestamp()-interval '5 seconds' "
|
||||||
|
"AND created_at > clock_timestamp()-(%s+5)*interval '1 second'", (seconds,)).fetchone()
|
||||||
|
windows[window] = result
|
||||||
|
values = {'messenger_queue_depth': row['depth'], 'messenger_queue_oldest_seconds': row['age'],
|
||||||
|
'messenger_diagnostics_db_up': 1}
|
||||||
|
data = ''.join(f'{key} {value}\n' for key, value in values.items()).encode()
|
||||||
|
for window, result in windows.items():
|
||||||
|
for kind in ('bad','total'):
|
||||||
|
data += f'messenger_ready_window_{kind}{{window="{window}"}} {result[kind]}\n'.encode()
|
||||||
|
except Exception:
|
||||||
|
data = b'messenger_diagnostics_db_up 0\n'
|
||||||
|
self.send_response(200)
|
||||||
|
self.send_header('Content-Type', 'text/plain; version=0.0.4')
|
||||||
|
self.end_headers()
|
||||||
|
self.wfile.write(data)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
storage.pool.open(wait=True)
|
||||||
|
try:
|
||||||
|
HTTPServer(('0.0.0.0',9099), Handler).serve_forever()
|
||||||
|
finally:
|
||||||
|
storage.pool.close()
|
||||||
+13
-2
@@ -9,11 +9,15 @@ import pika
|
|||||||
import psycopg
|
import psycopg
|
||||||
from psycopg_pool import PoolTimeout
|
from psycopg_pool import PoolTimeout
|
||||||
|
|
||||||
from src import broker, jobs, faults
|
from src import broker, jobs, faults, telemetry
|
||||||
|
from opentelemetry.propagate import extract
|
||||||
|
from opentelemetry.trace import SpanKind
|
||||||
from src.storage import storage
|
from src.storage import storage
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
telemetry.setup("messenger-dispatcher")
|
||||||
|
telemetry.register_gauges(storage.pool)
|
||||||
logging.basicConfig(level=logging.WARNING)
|
logging.basicConfig(level=logging.WARNING)
|
||||||
stopping = threading.Event()
|
stopping = threading.Event()
|
||||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||||
@@ -33,7 +37,14 @@ def main():
|
|||||||
reserved = jobs.reserve_publish()
|
reserved = jobs.reserve_publish()
|
||||||
if reserved:
|
if reserved:
|
||||||
faults.hit('before_publish', reserved)
|
faults.hit('before_publish', reserved)
|
||||||
broker.publish(channel, jobs.envelope(reserved))
|
with telemetry.tracer.start_as_current_span("attachment.publish",
|
||||||
|
context=extract(reserved["trace_context"]), kind=SpanKind.PRODUCER) as sp:
|
||||||
|
sp.set_attribute("messaging.system", "rabbitmq")
|
||||||
|
sp.set_attribute("messaging.destination.name", broker.QUEUE)
|
||||||
|
sp.set_attribute("job.id", str(reserved["id"]))
|
||||||
|
message = jobs.envelope(reserved) | telemetry.carrier()
|
||||||
|
broker.publish(channel, message)
|
||||||
|
telemetry.event("job.published", job_id=str(reserved["id"]), attempt=reserved["attempt"])
|
||||||
faults.hit('after_publish', reserved)
|
faults.hit('after_publish', reserved)
|
||||||
jobs.confirm_publish(reserved)
|
jobs.confirm_publish(reserved)
|
||||||
reserved = None
|
reserved = None
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ from src.routes.common import require_user, make_error, get_request_id
|
|||||||
from src.storage import storage, timestamp
|
from src.storage import storage, timestamp
|
||||||
from src.objects import client, BUCKET, object_lock, put_immutable
|
from src.objects import client, BUCKET, object_lock, put_immutable
|
||||||
from src.config import setting
|
from src.config import setting
|
||||||
|
from src import telemetry
|
||||||
|
import json
|
||||||
|
|
||||||
router = APIRouter()
|
router = APIRouter()
|
||||||
slots = asyncio.Semaphore(1)
|
slots = asyncio.Semaphore(1)
|
||||||
@@ -64,9 +66,9 @@ def save(stream, chat_id, owner, filename, content_type, size, digest):
|
|||||||
row=conn.execute("INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256,state) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *",
|
row=conn.execute("INSERT INTO attachments(id,chat_id,owner_id,object_key,filename,content_type,size_bytes,sha256,state) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *",
|
||||||
(attachment_id,chat_id,owner,key,filename,content_type,size,digest)).fetchone()
|
(attachment_id,chat_id,owner,key,filename,content_type,size,digest)).fetchone()
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at) "
|
"INSERT INTO attachment_jobs(id,attachment_id,staging_key,attempt_limit,next_publish_at,trace_context) "
|
||||||
"VALUES (%s,%s,%s,%s,clock_timestamp())",
|
"VALUES (%s,%s,%s,%s,clock_timestamp(),%s)",
|
||||||
(uuid.uuid4(), attachment_id, staging_key, int(setting('JOB_MAX_ATTEMPTS', '5'))),
|
(uuid.uuid4(), attachment_id, staging_key, int(setting('JOB_MAX_ATTEMPTS', '5')),json.dumps(telemetry.carrier())),
|
||||||
)
|
)
|
||||||
return metadata(row)
|
return metadata(row)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""Bounded OTLP pipelines; explicit, low-cardinality application signals."""
|
||||||
|
import atexit
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
from opentelemetry import trace, metrics
|
||||||
|
from opentelemetry.context import attach, detach
|
||||||
|
from opentelemetry.propagate import extract, inject
|
||||||
|
from opentelemetry.sdk.resources import Resource
|
||||||
|
from opentelemetry.sdk.trace import TracerProvider
|
||||||
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||||
|
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
|
||||||
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
|
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
|
||||||
|
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||||
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
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
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
|
||||||
|
_initialized = False
|
||||||
|
logger = logging.getLogger('messenger.events')
|
||||||
|
logger.propagate = False
|
||||||
|
logger.setLevel(logging.INFO)
|
||||||
|
busy = 0
|
||||||
|
tracer = trace.get_tracer('messenger', '1.6.0')
|
||||||
|
meter = metrics.get_meter('messenger', '1.6.0')
|
||||||
|
http_count = meter.create_counter('messenger.http.requests')
|
||||||
|
http_duration = meter.create_histogram('messenger.http.duration', unit='s')
|
||||||
|
job_count = meter.create_counter('messenger.jobs')
|
||||||
|
job_duration = meter.create_histogram('messenger.job.duration', unit='s')
|
||||||
|
ready_duration = meter.create_histogram('messenger.ready.duration', unit='s')
|
||||||
|
|
||||||
|
|
||||||
|
def setup(service):
|
||||||
|
global _initialized
|
||||||
|
if _initialized or os.getenv('TELEMETRY_ENABLED', '1') == '0':
|
||||||
|
return
|
||||||
|
_initialized = True
|
||||||
|
resource = Resource.create({'service.name': service, 'service.version': '1.6.0',
|
||||||
|
'service.instance.id': socket.gethostname(), 'deployment.environment.name': 'lab'})
|
||||||
|
endpoint = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318')
|
||||||
|
tp = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased(
|
||||||
|
float(os.getenv('TRACE_SAMPLE_RATIO', '1')))))
|
||||||
|
tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint+'/v1/traces', timeout=2),
|
||||||
|
max_queue_size=256, max_export_batch_size=64, schedule_delay_millis=1000))
|
||||||
|
trace.set_tracer_provider(tp)
|
||||||
|
mp = MeterProvider(resource=resource, metric_readers=[PeriodicExportingMetricReader(
|
||||||
|
OTLPMetricExporter(endpoint=endpoint+'/v1/metrics', timeout=2), export_interval_millis=5000)],
|
||||||
|
views=[View(instrument_type=metrics.Histogram,
|
||||||
|
aggregation=ExplicitBucketHistogramAggregation([.005,.01,.025,.05,.1,.25,.5,1,2,5,10,20,30,60,120]))])
|
||||||
|
metrics.set_meter_provider(mp)
|
||||||
|
lp = LoggerProvider(resource=resource)
|
||||||
|
lp.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint+'/v1/logs', timeout=2),
|
||||||
|
max_queue_size=256, max_export_batch_size=64, schedule_delay_millis=1000))
|
||||||
|
logger.addHandler(LoggingHandler(level=logging.INFO, logger_provider=lp))
|
||||||
|
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
|
||||||
|
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
|
||||||
|
# DB statements have placeholders; parameters and credentials are never captured.
|
||||||
|
PsycopgInstrumentor().instrument(skip_dep_check=True)
|
||||||
|
BotocoreInstrumentor().instrument()
|
||||||
|
atexit.register(lp.shutdown)
|
||||||
|
|
||||||
|
|
||||||
|
def event(name, **fields):
|
||||||
|
context = trace.get_current_span().get_span_context()
|
||||||
|
logger.info(json.dumps({'event': name, 'trace_id': format(context.trace_id, '032x'),
|
||||||
|
'span_id': format(context.span_id, '016x'), **fields}, separators=(',', ':')))
|
||||||
|
|
||||||
|
|
||||||
|
def carrier():
|
||||||
|
result = {}
|
||||||
|
inject(result)
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def span(name, **attrs):
|
||||||
|
with tracer.start_as_current_span(name, attributes=attrs, record_exception=False,
|
||||||
|
set_status_on_exception=False) as current:
|
||||||
|
try:
|
||||||
|
yield current
|
||||||
|
except Exception as exc:
|
||||||
|
current.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||||
|
current.set_attribute('error.type', type(exc).__name__)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
|
class HTTPMiddleware:
|
||||||
|
"""No bodies, raw URLs, query strings or incoming arbitrary headers are exported."""
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
async def __call__(self, scope, receive, send):
|
||||||
|
if scope['type'] != 'http' or scope['path'].startswith('/health/'):
|
||||||
|
return await self.app(scope, receive, send)
|
||||||
|
start = time.monotonic()
|
||||||
|
status = 500
|
||||||
|
method = scope['method'] if scope['method'] in ('GET','POST','PUT','DELETE','PATCH','HEAD','OPTIONS') else 'OTHER'
|
||||||
|
headers = {k.decode('latin1'): v.decode('latin1') for k,v in scope['headers'] if k in (b'traceparent',b'tracestate')}
|
||||||
|
with tracer.start_as_current_span('HTTP request', context=extract(headers), kind=SpanKind.SERVER,
|
||||||
|
record_exception=False, set_status_on_exception=False) as current:
|
||||||
|
async def wrapped(message):
|
||||||
|
nonlocal status
|
||||||
|
if message['type'] == 'http.response.start':
|
||||||
|
status = message['status']
|
||||||
|
message['headers'].append((b'x-trace-id', format(current.get_span_context().trace_id, '032x').encode()))
|
||||||
|
await send(message)
|
||||||
|
try:
|
||||||
|
await self.app(scope, receive, wrapped)
|
||||||
|
finally:
|
||||||
|
route = getattr(scope.get('route'), 'path', 'unmatched')
|
||||||
|
attrs = {'method': method, 'route': route, 'status_class': str(status//100)+'xx'}
|
||||||
|
current.update_name(method+' '+route)
|
||||||
|
current.set_attributes({'http.request.method': method, 'http.route': route, 'http.response.status_code': status})
|
||||||
|
if status >= 500:
|
||||||
|
current.set_status(Status(StatusCode.ERROR))
|
||||||
|
http_count.add(1, attrs)
|
||||||
|
http_duration.record(time.monotonic()-start, attrs)
|
||||||
|
event('http.completed', method=method, route=route, status=status,
|
||||||
|
request_id=scope.get('state', {}).get('request_id', ''))
|
||||||
|
|
||||||
|
|
||||||
|
def register_gauges(pool, worker=False):
|
||||||
|
from opentelemetry.metrics import Observation
|
||||||
|
def pool_values(key):
|
||||||
|
return lambda options: [Observation(pool.get_stats().get(key, 0))]
|
||||||
|
meter.create_observable_gauge('messenger.db.pool.used', callbacks=[lambda _: [Observation(
|
||||||
|
pool.get_stats().get('pool_size',0)-pool.get_stats().get('pool_available',0))]])
|
||||||
|
meter.create_observable_gauge('messenger.db.pool.waiting', callbacks=[pool_values('requests_waiting')])
|
||||||
|
if worker:
|
||||||
|
meter.create_observable_gauge('messenger.worker.busy', callbacks=[lambda _: [Observation(busy)]])
|
||||||
|
meter.create_observable_gauge('messenger.worker.capacity', callbacks=[lambda _: [Observation(1)]])
|
||||||
|
def process_stats(options):
|
||||||
|
import resource
|
||||||
|
return [Observation(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024)]
|
||||||
|
meter.create_observable_gauge('messenger.process.maxrss', unit='By', callbacks=[process_stats])
|
||||||
|
meter.create_observable_counter('messenger.process.cpu', unit='s', callbacks=[lambda _: [Observation(
|
||||||
|
sum(os.times()[:2]))]])
|
||||||
+43
-3
@@ -8,6 +8,8 @@ import subprocess
|
|||||||
import sys
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
|
from datetime import datetime, timezone
|
||||||
from contextlib import closing
|
from contextlib import closing
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -16,7 +18,9 @@ import psycopg
|
|||||||
from botocore.exceptions import BotoCoreError, ClientError
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
from psycopg_pool import PoolTimeout
|
from psycopg_pool import PoolTimeout
|
||||||
|
|
||||||
from src import broker, jobs, faults
|
from src import broker, jobs, faults, telemetry
|
||||||
|
from opentelemetry.propagate import extract
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
from src.objects import BUCKET, ObjectConflict, client, put_immutable
|
from src.objects import BUCKET, ObjectConflict, client, put_immutable
|
||||||
from src.storage import storage
|
from src.storage import storage
|
||||||
|
|
||||||
@@ -70,11 +74,13 @@ def process(job):
|
|||||||
put_immutable(s3, key, stream, size, mime, digest)
|
put_immutable(s3, key, stream, size, mime, digest)
|
||||||
variants.append((name, key, mime, size, digest, width, height))
|
variants.append((name, key, mime, size, digest, width, height))
|
||||||
faults.hit('after_variants', job)
|
faults.hit('after_variants', job)
|
||||||
jobs.complete(job, variants)
|
published = jobs.complete(job, variants)
|
||||||
|
if published:
|
||||||
|
telemetry.ready_duration.record((datetime.now(timezone.utc)-job["attachment"]["created_at"]).total_seconds(), {"job_type":"attachment"})
|
||||||
faults.hit('after_commit', job)
|
faults.hit('after_commit', job)
|
||||||
|
|
||||||
|
|
||||||
def handle(channel, delivery, body):
|
def handle_inner(channel, delivery, body):
|
||||||
try:
|
try:
|
||||||
message = jobs.validate(json.loads(body))
|
message = jobs.validate(json.loads(body))
|
||||||
except (ValueError, TypeError, AttributeError):
|
except (ValueError, TypeError, AttributeError):
|
||||||
@@ -84,19 +90,53 @@ def handle(channel, delivery, body):
|
|||||||
|
|
||||||
job = jobs.claim(message)
|
job = jobs.claim(message)
|
||||||
if job:
|
if job:
|
||||||
|
telemetry.busy = 1
|
||||||
|
started = time.monotonic()
|
||||||
|
outcome = "success"
|
||||||
try:
|
try:
|
||||||
|
with telemetry.span("attachment.transform_and_publish"):
|
||||||
process(job)
|
process(job)
|
||||||
except PermanentError as exc:
|
except PermanentError as exc:
|
||||||
|
outcome = "failed"
|
||||||
jobs.fail(job, str(exc), permanent=True)
|
jobs.fail(job, str(exc), permanent=True)
|
||||||
except ObjectConflict:
|
except ObjectConflict:
|
||||||
|
outcome = "failed"
|
||||||
jobs.fail(job, 'object_conflict', permanent=True)
|
jobs.fail(job, 'object_conflict', permanent=True)
|
||||||
except (BotoCoreError, ClientError, OSError, subprocess.SubprocessError) as exc:
|
except (BotoCoreError, ClientError, OSError, subprocess.SubprocessError) as exc:
|
||||||
|
outcome = "retry"
|
||||||
logging.warning('processing retry job=%s cause=%s', job['id'], type(exc).__name__)
|
logging.warning('processing retry job=%s cause=%s', job['id'], type(exc).__name__)
|
||||||
jobs.fail(job, 'processing_timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'processing_failed')
|
jobs.fail(job, 'processing_timeout' if isinstance(exc, subprocess.TimeoutExpired) else 'processing_failed')
|
||||||
|
finally:
|
||||||
|
telemetry.busy = 0
|
||||||
|
attrs = {"job_type":"attachment", "outcome":outcome}
|
||||||
|
telemetry.job_count.add(1, attrs)
|
||||||
|
telemetry.job_duration.record(time.monotonic()-started, attrs)
|
||||||
|
if outcome != "success":
|
||||||
|
telemetry.trace.get_current_span().set_status(Status(StatusCode.ERROR))
|
||||||
|
telemetry.event("job.processed", job_id=str(job["id"]), attempt=job["attempt"], outcome=outcome)
|
||||||
|
else:
|
||||||
|
telemetry.event("job.duplicate")
|
||||||
channel.basic_ack(delivery.delivery_tag)
|
channel.basic_ack(delivery.delivery_tag)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def handle(channel, delivery, body):
|
||||||
|
try:
|
||||||
|
raw = json.loads(body)
|
||||||
|
carrier = {k:raw[k] for k in ('traceparent','tracestate') if k in raw}
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
carrier = {}
|
||||||
|
with telemetry.tracer.start_as_current_span('attachment.consume', context=extract(carrier),
|
||||||
|
kind=SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False) as sp:
|
||||||
|
sp.set_attribute('messaging.system', 'rabbitmq')
|
||||||
|
sp.set_attribute('messaging.destination.name', broker.QUEUE)
|
||||||
|
sp.set_attribute('messaging.message.redelivered', delivery.redelivered)
|
||||||
|
handle_inner(channel, delivery, body)
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
|
telemetry.setup("messenger-worker")
|
||||||
|
telemetry.register_gauges(storage.pool, worker=True)
|
||||||
logging.basicConfig(level=logging.WARNING)
|
logging.basicConfig(level=logging.WARNING)
|
||||||
stopping = threading.Event()
|
stopping = threading.Event()
|
||||||
for sig in (signal.SIGINT, signal.SIGTERM):
|
for sig in (signal.SIGINT, signal.SIGTERM):
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'tests'))
|
||||||
|
from client import Client, check
|
||||||
|
BASE = os.getenv('BASE_URL','http://127.0.0.1:8086')
|
||||||
|
GRAFANA = os.getenv('GRAFANA_URL','http://127.0.0.1:3006')
|
||||||
|
PROJECT = os.getenv('COMPOSE_PROJECT_NAME','lyakhonov-lab6')
|
||||||
|
|
||||||
|
|
||||||
|
def dc(*args):
|
||||||
|
return subprocess.check_output(['docker','compose','-p',PROJECT,*args],cwd=ROOT,text=True,stderr=subprocess.STDOUT)
|
||||||
|
|
||||||
|
|
||||||
|
def query(uid, path, **params):
|
||||||
|
url=GRAFANA+'/api/datasources/proxy/uid/'+uid+path
|
||||||
|
if params:
|
||||||
|
url += '?'+urllib.parse.urlencode(params)
|
||||||
|
with urllib.request.urlopen(url,timeout=15) as r:
|
||||||
|
return json.load(r)
|
||||||
|
|
||||||
|
|
||||||
|
def prom(expr):
|
||||||
|
return query('prometheus','/api/v1/query',query=expr)['data']['result']
|
||||||
|
|
||||||
|
|
||||||
|
def snapshot():
|
||||||
|
ids=dc('ps','-aq').split()
|
||||||
|
result=[]
|
||||||
|
for row in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
|
||||||
|
result.append({'id':row['Id'],'service':row['Config']['Labels']['com.docker.compose.service'],
|
||||||
|
'started_at':row['State']['StartedAt'],'status':row['State']['Status'],
|
||||||
|
'memory_limit':row['HostConfig']['Memory'],'nano_cpus':row['HostConfig']['NanoCpus']})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def save(name,data):
|
||||||
|
path=ROOT/'evidence'/name
|
||||||
|
path.write_text(json.dumps(data,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||||
|
|
||||||
|
|
||||||
|
def trace_spans(document):
|
||||||
|
result=[]
|
||||||
|
for batch in document.get('batches', document.get('resourceSpans',[])):
|
||||||
|
attrs={x['key']:next(iter(x['value'].values())) for x in batch['resource'].get('attributes',[])}
|
||||||
|
for scope in batch.get('scopeSpans',[]):
|
||||||
|
for sp in scope.get('spans',[]):
|
||||||
|
def hexid(value):
|
||||||
|
if not value:return ''
|
||||||
|
return base64.b64decode(value).hex() if len(value) not in (16,32) else value
|
||||||
|
result.append({'service':attrs.get('service.name'),'name':sp['name'],
|
||||||
|
'id':hexid(sp['spanId']),'parent':hexid(sp.get('parentSpanId','')),
|
||||||
|
'kind':sp.get('kind'),'status':sp.get('status',{}),
|
||||||
|
'duration_ms':(int(sp['endTimeUnixNano'])-int(sp['startTimeUnixNano']))/1e6})
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def trace_wait(trace_id, services=('messenger-api','messenger-worker')):
|
||||||
|
deadline=time.monotonic()+40
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
try:
|
||||||
|
doc=query('tempo','/api/traces/'+trace_id)
|
||||||
|
spans=trace_spans(doc)
|
||||||
|
if set(services)<={s['service'] for s in spans}:return doc,spans
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(1)
|
||||||
|
raise AssertionError('trace not present: '+trace_id)
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
"""Fresh trace graph, correlated logs, real metrics, negative and concurrent requests."""
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from common import *
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c=Client(BASE)
|
||||||
|
alice,bob,eve,chat=c.bootstrap()
|
||||||
|
payload=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||||
|
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',202,
|
||||||
|
actor=alice,raw=payload,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||||
|
att=response['json']; tid=response['headers']['X-Trace-Id']
|
||||||
|
ready=c.wait_ready(bob,att)
|
||||||
|
check({v['name'] for v in ready['variants']}=={'thumbnail','crop','optimized'},'variants missing')
|
||||||
|
for variant in ['original','thumbnail','crop','optimized']:
|
||||||
|
result=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+variant,actor=bob)
|
||||||
|
meta=ready if variant=='original' else next(v for v in ready['variants'] if v['name']==variant)
|
||||||
|
check(hashlib.sha256(result['bytes']).hexdigest()==meta['sha256'],'variant bytes mismatch')
|
||||||
|
doc,spans=trace_wait(tid)
|
||||||
|
check(any(s['kind']=='SPAN_KIND_PRODUCER' for s in spans),'producer missing')
|
||||||
|
check(any(s['kind']=='SPAN_KIND_CONSUMER' for s in spans),'consumer missing')
|
||||||
|
ids={s['id'] for s in spans}
|
||||||
|
check(all(s['parent'] in ids for s in spans if s['kind']=='SPAN_KIND_CONSUMER'),'consumer parent missing')
|
||||||
|
check(any('S3.' in s['name'] for s in spans),'S3 span missing')
|
||||||
|
check(any(s['name'].startswith(('INSERT','UPDATE','SELECT','COMMIT')) for s in spans),'DB span missing')
|
||||||
|
logs=query('loki','/loki/api/v1/query_range',query='{service_name=~"messenger-api|messenger-worker|messenger-dispatcher"} |= "'+tid+'"',limit=100)
|
||||||
|
log_services={x['stream']['service_name'] for x in logs['data']['result']}
|
||||||
|
check({'messenger-api','messenger-worker'}<=log_services,'correlated logs missing')
|
||||||
|
key='concurrent-'+str(time.time_ns())
|
||||||
|
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||||
|
messages=list(pool.map(lambda _: c.message(alice,chat,'synthetic concurrent',key=key)['json'],range(24)))
|
||||||
|
check(len({m['id'] for m in messages})==1,'duplicate messages')
|
||||||
|
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',409,actor=alice,body={'text':'other'},headers={'Idempotency-Key':key})
|
||||||
|
c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=bad.png',415,actor=alice,raw=b'invalid',headers={'Content-Type':'image/png'})
|
||||||
|
c.call('GET','/api/v1/attachments/'+att['id'],404,actor=eve)
|
||||||
|
time.sleep(7)
|
||||||
|
signals={name:prom(name) for name in ['messenger_http_requests_total','messenger_http_duration_seconds_bucket',
|
||||||
|
'messenger_jobs_total','messenger_job_duration_seconds_bucket','messenger_ready_duration_seconds_bucket',
|
||||||
|
'messenger_worker_capacity','messenger_db_pool_used','messenger_queue_depth']}
|
||||||
|
check(all(signals.values()),'required metric missing')
|
||||||
|
forbidden={'user_id','chat_id','message_id','attachment_id','request_id','filename'}
|
||||||
|
check(not any(forbidden & set(row['metric']) for rows in signals.values() for row in rows),'high cardinality metric label')
|
||||||
|
telemetry=json.dumps([doc,logs,signals])
|
||||||
|
for secret in [alice['token'],bob['token'],alice['registration']['password'],'synthetic concurrent']:
|
||||||
|
check(secret not in telemetry,'sensitive data in telemetry')
|
||||||
|
save('signals.json',{'trace_id':tid,'spans':spans,'logs':logs,'metrics':signals,
|
||||||
|
'concurrent_requests':24,'unique_messages':1,'checks':'PASS'})
|
||||||
|
print('PASS: real OTLP signals, connected producer/consumer/S3/DB graph, logs, metric labels, 24 concurrent replays and negative checks')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
Reference in New Issue
Block a user