ЛР 6 — БВТ2304 — Травкин — на 5 #85
@@ -225,6 +225,7 @@ services:
|
||||
- --storage.tsdb.retention.size=1GB
|
||||
volumes:
|
||||
- ./infra/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/prometheus/rules.yaml:/etc/prometheus/rules.yml:ro
|
||||
- prometheus_data:/prometheus
|
||||
ports:
|
||||
- "127.0.0.1:9090:9090"
|
||||
|
||||
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 287 KiB |
|
After Width: | Height: | Size: 236 KiB |
|
After Width: | Height: | Size: 333 KiB |
|
After Width: | Height: | Size: 61 KiB |
|
After Width: | Height: | Size: 65 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 59 KiB |
|
After Width: | Height: | Size: 498 KiB |
@@ -0,0 +1,27 @@
|
||||
|
||||
=== sum by (outcome) (messenger_jobs_total) ===
|
||||
{'outcome': 'success'} 2
|
||||
{'outcome': 'retry'} 1
|
||||
|
||||
=== sum by (outcome) (increase(messenger_jobs_total[5m])) ===
|
||||
{'outcome': 'success'} 1.0672198986211507
|
||||
{'outcome': 'retry'} 0
|
||||
|
||||
=== max_over_time(messenger_worker_busy[5m]) ===
|
||||
{'deployment_environment_name': 'lab', 'exported_instance': 'b6278c820248', 'exported_job': 'messenger-worker', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'service_instance_id': 'b6278c820248', 'service_name': 'messenger-worker', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 0
|
||||
{'deployment_environment_name': 'lab', 'exported_instance': 'a60db76c87a5', 'exported_job': 'messenger-worker', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'service_instance_id': 'a60db76c87a5', 'service_name': 'messenger-worker', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 1
|
||||
|
||||
=== messenger_worker_capacity ===
|
||||
{'__name__': 'messenger_worker_capacity', 'deployment_environment_name': 'lab', 'exported_instance': 'a60db76c87a5', 'exported_job': 'messenger-worker', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'service_instance_id': 'a60db76c87a5', 'service_name': 'messenger-worker', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 1
|
||||
|
||||
=== messenger_worker_busy ===
|
||||
{'__name__': 'messenger_worker_busy', 'deployment_environment_name': 'lab', 'exported_instance': 'a60db76c87a5', 'exported_job': 'messenger-worker', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'service_instance_id': 'a60db76c87a5', 'service_name': 'messenger-worker', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 0
|
||||
|
||||
=== messenger_attachment_ready_duration_seconds_count ===
|
||||
{'__name__': 'messenger_attachment_ready_duration_seconds_count', 'deployment_environment_name': 'lab', 'exported_instance': 'a60db76c87a5', 'exported_job': 'messenger-worker', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'job_type': 'attachment.process.v1', 'service_instance_id': 'a60db76c87a5', 'service_name': 'messenger-worker', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 2
|
||||
|
||||
=== messenger_queue_depth ===
|
||||
{'__name__': 'messenger_queue_depth', 'deployment_environment_name': 'lab', 'exported_instance': 'efee40d00d01', 'exported_job': 'messenger-dispatcher', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'queue_name': 'attachment.process.v1', 'service_instance_id': 'efee40d00d01', 'service_name': 'messenger-dispatcher', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 0
|
||||
|
||||
=== messenger_queue_oldest_age_seconds ===
|
||||
{'__name__': 'messenger_queue_oldest_age_seconds', 'deployment_environment_name': 'lab', 'exported_instance': 'efee40d00d01', 'exported_job': 'messenger-dispatcher', 'instance': 'otel-collector:8889', 'job': 'otel-collector', 'queue_name': 'attachment.process.v1', 'service_instance_id': 'efee40d00d01', 'service_name': 'messenger-dispatcher', 'service_version': '6.0.0', 'telemetry_sdk_language': 'python', 'telemetry_sdk_name': 'opentelemetry', 'telemetry_sdk_version': '1.45.2'} 0
|
||||
|
After Width: | Height: | Size: 445 KiB |
|
After Width: | Height: | Size: 138 KiB |
@@ -0,0 +1,23 @@
|
||||
|
||||
=== otelcol_exporter_queue_size ===
|
||||
{'__name__': 'otelcol_exporter_queue_size', 'data_type': 'logs', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 0
|
||||
{'__name__': 'otelcol_exporter_queue_size', 'data_type': 'traces', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 0
|
||||
|
||||
=== otelcol_exporter_queue_capacity ===
|
||||
{'__name__': 'otelcol_exporter_queue_capacity', 'data_type': 'logs', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 128
|
||||
{'__name__': 'otelcol_exporter_queue_capacity', 'data_type': 'traces', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 128
|
||||
|
||||
=== otelcol_process_memory_rss ===
|
||||
{'__name__': 'otelcol_process_memory_rss', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 209420288
|
||||
|
||||
=== {__name__=~"otelcol_exporter_.*(spans|log_records).*"} ===
|
||||
{'__name__': 'otelcol_exporter_send_failed_log_records', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 0
|
||||
{'__name__': 'otelcol_exporter_send_failed_spans', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 0
|
||||
{'__name__': 'otelcol_exporter_sent_log_records', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 1659
|
||||
{'__name__': 'otelcol_exporter_sent_spans', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 19586
|
||||
|
||||
=== {__name__=~"otelcol_receiver_.*(spans|log_records).*"} ===
|
||||
{'__name__': 'otelcol_receiver_accepted_log_records', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 1659
|
||||
{'__name__': 'otelcol_receiver_accepted_spans', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 19586
|
||||
{'__name__': 'otelcol_receiver_refused_log_records', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 0
|
||||
{'__name__': 'otelcol_receiver_refused_spans', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 0
|
||||
|
After Width: | Height: | Size: 127 KiB |
|
After Width: | Height: | Size: 156 KiB |
@@ -0,0 +1,23 @@
|
||||
|
||||
=== otelcol_exporter_queue_size ===
|
||||
{'__name__': 'otelcol_exporter_queue_size', 'data_type': 'logs', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 51
|
||||
{'__name__': 'otelcol_exporter_queue_size', 'data_type': 'traces', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 56
|
||||
|
||||
=== otelcol_exporter_queue_capacity ===
|
||||
{'__name__': 'otelcol_exporter_queue_capacity', 'data_type': 'logs', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 128
|
||||
{'__name__': 'otelcol_exporter_queue_capacity', 'data_type': 'traces', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 128
|
||||
|
||||
=== otelcol_process_memory_rss ===
|
||||
{'__name__': 'otelcol_process_memory_rss', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 203780096
|
||||
|
||||
=== {__name__=~"otelcol_exporter_.*(spans|log_records).*"} ===
|
||||
{'__name__': 'otelcol_exporter_send_failed_log_records', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 64
|
||||
{'__name__': 'otelcol_exporter_send_failed_spans', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 352
|
||||
{'__name__': 'otelcol_exporter_sent_log_records', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 1663
|
||||
{'__name__': 'otelcol_exporter_sent_spans', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 19678
|
||||
|
||||
=== {__name__=~"otelcol_receiver_.*(spans|log_records).*"} ===
|
||||
{'__name__': 'otelcol_receiver_accepted_log_records', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 2332
|
||||
{'__name__': 'otelcol_receiver_accepted_spans', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 23608
|
||||
{'__name__': 'otelcol_receiver_refused_log_records', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 0
|
||||
{'__name__': 'otelcol_receiver_refused_spans', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 0
|
||||
|
After Width: | Height: | Size: 139 KiB |
|
After Width: | Height: | Size: 154 KiB |
@@ -0,0 +1,35 @@
|
||||
|
||||
=== otelcol_exporter_queue_size ===
|
||||
{'__name__': 'otelcol_exporter_queue_size', 'data_type': 'logs', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 0
|
||||
{'__name__': 'otelcol_exporter_queue_size', 'data_type': 'traces', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 0
|
||||
|
||||
=== otelcol_exporter_queue_capacity ===
|
||||
{'__name__': 'otelcol_exporter_queue_capacity', 'data_type': 'logs', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 128
|
||||
{'__name__': 'otelcol_exporter_queue_capacity', 'data_type': 'traces', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 128
|
||||
|
||||
=== otelcol_process_memory_rss / 1024 / 1024 ===
|
||||
{'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 198.5
|
||||
|
||||
=== otelcol_exporter_send_failed_spans ===
|
||||
{'__name__': 'otelcol_exporter_send_failed_spans', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 913
|
||||
|
||||
=== otelcol_exporter_send_failed_log_records ===
|
||||
{'__name__': 'otelcol_exporter_send_failed_log_records', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 143
|
||||
|
||||
=== otelcol_exporter_sent_spans ===
|
||||
{'__name__': 'otelcol_exporter_sent_spans', 'exporter': 'otlp/tempo', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 25673
|
||||
|
||||
=== otelcol_exporter_sent_log_records ===
|
||||
{'__name__': 'otelcol_exporter_sent_log_records', 'exporter': 'otlphttp/loki', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1'} 2380
|
||||
|
||||
=== otelcol_receiver_accepted_spans ===
|
||||
{'__name__': 'otelcol_receiver_accepted_spans', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 26594
|
||||
|
||||
=== otelcol_receiver_accepted_log_records ===
|
||||
{'__name__': 'otelcol_receiver_accepted_log_records', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 2523
|
||||
|
||||
=== otelcol_receiver_refused_spans ===
|
||||
{'__name__': 'otelcol_receiver_refused_spans', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 0
|
||||
|
||||
=== otelcol_receiver_refused_log_records ===
|
||||
{'__name__': 'otelcol_receiver_refused_log_records', 'instance': 'otel-collector:8888', 'job': 'otel-collector-internal', 'receiver': 'otlp', 'service.instance.id': '5efc7ed0-ab90-45c3-b895-76ac6853bcd2', 'service.name': 'otelcol-contrib', 'service.version': '0.120.1', 'transport': 'http'} 0
|
||||
|
After Width: | Height: | Size: 409 KiB |
@@ -9,7 +9,7 @@
|
||||
],
|
||||
"timezone": "browser",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"version": 2,
|
||||
"editable": false,
|
||||
"refresh": "10s",
|
||||
"time": {
|
||||
@@ -338,6 +338,586 @@
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "HTTP Latency Percentiles",
|
||||
"description": "Business request latency across both API replicas",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route=~\"/api/.*\"}[$__rate_interval])))",
|
||||
"legendFormat": "p50",
|
||||
"range": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route=~\"/api/.*\"}[$__rate_interval])))",
|
||||
"legendFormat": "p95",
|
||||
"range": true
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route=~\"/api/.*\"}[$__rate_interval])))",
|
||||
"legendFormat": "p99",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "HTTP Error Ratio",
|
||||
"description": "5xx divided by all business API requests; health excluded",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "100 * (sum(rate(messenger_http_requests_total{route=~\"/api/.*\",status_code=~\"5..\"}[$__rate_interval])) or (0 * sum(rate(messenger_http_requests_total{route=~\"/api/.*\"}[$__rate_interval])))) / (sum(rate(messenger_http_requests_total{route=~\"/api/.*\"}[$__rate_interval])) > 0)",
|
||||
"legendFormat": "5xx ratio",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Queue Backlog",
|
||||
"description": "Durable queued attachment jobs",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "max by (queue_name) (messenger_queue_depth)",
|
||||
"legendFormat": "{{queue_name}}",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Oldest Queued Job Age",
|
||||
"description": "Age of oldest queued attachment job",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "max by (queue_name) (messenger_queue_oldest_age_seconds)",
|
||||
"legendFormat": "{{queue_name}}",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "Database Pool Used / Capacity",
|
||||
"description": "Checked-out connections and maximum capacity per process",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_db_pool_used",
|
||||
"legendFormat": "Used {{service_name}} {{service_instance_id}}",
|
||||
"range": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_db_pool_capacity",
|
||||
"legendFormat": "Capacity {{service_name}} {{service_instance_id}}",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "Database Pool Waiting",
|
||||
"description": "Connection acquisitions waiting on the pool queue",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_db_pool_waiting",
|
||||
"legendFormat": "{{service_name}} {{service_instance_id}}",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "Worker Busy / Capacity",
|
||||
"description": "Concurrent active processing attempts and worker capacity",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_worker_busy",
|
||||
"legendFormat": "Busy",
|
||||
"range": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_worker_capacity",
|
||||
"legendFormat": "Capacity",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "Process CPU",
|
||||
"description": "CPU utilization per process; 100% equals one CPU core",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_process_cpu_percent",
|
||||
"legendFormat": "{{service_name}} {{service_instance_id}}",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percent",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"title": "Process RAM",
|
||||
"description": "Resident memory per application process",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "messenger_process_memory_bytes",
|
||||
"legendFormat": "{{service_name}} {{service_instance_id}}",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"title": "Attachment End-to-End Time",
|
||||
"description": "Time from durable acceptance to committed ready state",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p50",
|
||||
"range": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p95",
|
||||
"range": true
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[$__rate_interval])))",
|
||||
"legendFormat": "p99",
|
||||
"range": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s",
|
||||
"min": 0,
|
||||
"custom": {
|
||||
"drawStyle": "line",
|
||||
"lineWidth": 2,
|
||||
"fillOpacity": 10,
|
||||
"showPoints": "auto"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "none"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -11,25 +11,52 @@ processors:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 48
|
||||
|
||||
batch:
|
||||
timeout: 2s
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
metric_expiration: 30s
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
timeout: 5s
|
||||
tls:
|
||||
insecure: true
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 128
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 128
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
address: 0.0.0.0:8888
|
||||
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# Регламент диагностики и устранения инцидентов
|
||||
|
||||
## SLI / SLO
|
||||
|
||||
- SLO доступности API: не менее 99% за 30 дней.
|
||||
- SLO задержки: не менее 95% бизнес-запросов выполняются за 500 мс за 30 дней.
|
||||
- SLI доступности: 1 - количество HTTP 5xx / общее количество бизнес-запросов.
|
||||
- SLI задержки: доля бизнес-запросов, выполненных не более чем за 500 мс.
|
||||
- Запросы к health endpoints исключаются из расчётов.
|
||||
- При отсутствии запросов показатели не оцениваются.
|
||||
- Для демонстрации инцидентов используются сокращённые окна наблюдения.
|
||||
|
||||
## Ошибки HTTP
|
||||
|
||||
<a id="http-errors"></a>
|
||||
|
||||
Алерт: MessengerHighHTTPErrorRate.
|
||||
|
||||
Условие срабатывания: доля HTTP 5xx превышает 1%
|
||||
за последнюю минуту в течение 15 секунд.
|
||||
|
||||
### Диагностика
|
||||
|
||||
1. Проверить долю ошибок и задержки HTTP-запросов в Grafana.
|
||||
2. Проверить доступность PostgreSQL и состояние пула соединений.
|
||||
3. Найти логи ошибочных запросов в Loki.
|
||||
4. Открыть соответствующие трассировки в Tempo.
|
||||
5. Определить причину ошибки или замедления.
|
||||
|
||||
### Восстановление
|
||||
|
||||
Восстановить работоспособность проблемного сервиса.
|
||||
Проверить готовность API, выполнить smoke-тесты
|
||||
и убедиться, что алерт перешёл в неактивное состояние.
|
||||
|
||||
## Задержка очереди
|
||||
|
||||
<a id="queue-lag"></a>
|
||||
|
||||
Алерт: MessengerQueueLag.
|
||||
|
||||
Условие срабатывания: возраст самой старой задачи
|
||||
в очереди превышает 30 секунд в течение 15 секунд.
|
||||
|
||||
### Диагностика
|
||||
|
||||
1. Проверить глубину очереди и возраст самой старой задачи.
|
||||
2. Проверить доступность и загрузку worker.
|
||||
3. Проверить очереди и потребителей RabbitMQ.
|
||||
4. Изучить логи dispatcher и worker в Loki.
|
||||
5. Проверить трассировки обработки вложений в Tempo.
|
||||
|
||||
### Восстановление
|
||||
|
||||
Восстановить работу worker или проблемного сервиса.
|
||||
Убедиться, что очередь сокращается, вложения переходят
|
||||
в состояние ready, а алерт становится неактивным.
|
||||
|
||||
## Отказ системы сбора телеметрии
|
||||
|
||||
### Диагностика
|
||||
|
||||
1. Проверить доступность Tempo и Loki.
|
||||
2. Проверить потребление памяти OpenTelemetry Collector.
|
||||
3. Проверить размер и ёмкость очередей экспортёров.
|
||||
4. Проверить количество ошибок экспорта и потерь телеметрии.
|
||||
5. Убедиться, что бизнес-API продолжает работать.
|
||||
|
||||
### Восстановление
|
||||
|
||||
Восстановить доступность проблемного backend.
|
||||
Убедиться, что очереди экспортёров сокращаются,
|
||||
отправка телеметрии возобновилась, а API работает корректно.
|
||||
Зафиксировать количество потерянной телеметрии.
|
||||
@@ -2,12 +2,20 @@ global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
static_configs:
|
||||
- targets:
|
||||
- otel-collector:8889
|
||||
|
||||
- job_name: otel-collector-internal
|
||||
static_configs:
|
||||
- targets:
|
||||
- otel-collector:8888
|
||||
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets:
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 5s
|
||||
rules:
|
||||
- record: messenger:sli_http_error_ratio:1m
|
||||
expr: |
|
||||
(
|
||||
sum(rate(messenger_http_requests_total{route=~"/api/.*",status_class="5xx"}[1m]))
|
||||
or vector(0)
|
||||
)
|
||||
/
|
||||
sum(rate(messenger_http_requests_total{route=~"/api/.*"}[1m]))
|
||||
|
||||
- record: messenger:sli_http_availability:1m
|
||||
expr: |
|
||||
1 - messenger:sli_http_error_ratio:1m
|
||||
|
||||
- record: messenger:sli_http_p95_seconds:1m
|
||||
expr: |
|
||||
histogram_quantile(
|
||||
0.95,
|
||||
sum by (le) (
|
||||
rate(messenger_http_request_duration_seconds_bucket{route=~"/api/.*"}[1m])
|
||||
)
|
||||
)
|
||||
|
||||
- record: messenger:sli_http_latency_good_ratio:1m
|
||||
expr: |
|
||||
sum(rate(messenger_http_request_duration_seconds_bucket{route=~"/api/.*",le="0.5"}[1m]))
|
||||
/
|
||||
sum(rate(messenger_http_request_duration_seconds_count{route=~"/api/.*"}[1m]))
|
||||
|
||||
- name: messenger-alerts
|
||||
interval: 5s
|
||||
rules:
|
||||
- alert: MessengerHighHTTPErrorRate
|
||||
expr: |
|
||||
messenger:sli_http_error_ratio:1m > 0.01
|
||||
for: 15s
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "HTTP 5xx error ratio exceeds 1%"
|
||||
description: "Business API error ratio is {{ $value }}"
|
||||
runbook: "infra/prometheus/RUNBOOK.md#http-errors"
|
||||
|
||||
- alert: MessengerQueueLag
|
||||
expr: |
|
||||
max by (queue_name) (
|
||||
messenger_queue_oldest_age_seconds
|
||||
) > 30
|
||||
for: 15s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Attachment queue lag exceeds 30 seconds"
|
||||
description: "Oldest pending job age is {{ $value }} seconds"
|
||||
runbook: "infra/prometheus/RUNBOOK.md#queue-lag"
|
||||
@@ -0,0 +1,25 @@
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = "d6a12026a006"
|
||||
down_revision = "c9b12026a005"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column(
|
||||
"attachment_jobs",
|
||||
sa.Column("traceparent", sa.Text(), nullable=True),
|
||||
)
|
||||
|
||||
op.add_column(
|
||||
"attachment_jobs",
|
||||
sa.Column("tracestate", sa.Text(), nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column("attachment_jobs", "tracestate")
|
||||
op.drop_column("attachment_jobs", "traceparent")
|
||||
@@ -26,7 +26,6 @@ opentelemetry-sdk==1.45.2
|
||||
opentelemetry-exporter-otlp-proto-http==1.45.2
|
||||
opentelemetry-instrumentation-fastapi==0.66b2
|
||||
opentelemetry-instrumentation-asgi==0.66b2
|
||||
opentelemetry-instrumentation-sqlalchemy==0.66b2
|
||||
opentelemetry-instrumentation-logging==0.66b2
|
||||
opentelemetry-instrumentation-botocore==0.66b2
|
||||
opentelemetry-instrumentation-pika==0.66b2
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import socket
|
||||
from threading import Lock
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.pool import AsyncAdaptedQueuePool
|
||||
from sqlalchemy.util.queue import AsyncAdaptedQueue
|
||||
|
||||
from sqlalchemy import event, text
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
AsyncSession,
|
||||
@@ -24,10 +30,66 @@ def read_database_url() -> str:
|
||||
return file.read().strip()
|
||||
|
||||
|
||||
class MeasuredQueue(AsyncAdaptedQueue):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.waiting = 0
|
||||
self.waiting_lock = Lock()
|
||||
|
||||
def get(self, block=True, timeout=None):
|
||||
waiting = block and self.empty()
|
||||
|
||||
if waiting:
|
||||
with self.waiting_lock:
|
||||
self.waiting += 1
|
||||
|
||||
try:
|
||||
return super().get(block, timeout)
|
||||
finally:
|
||||
if waiting:
|
||||
with self.waiting_lock:
|
||||
self.waiting -= 1
|
||||
|
||||
|
||||
class MeasuredPool(AsyncAdaptedQueuePool):
|
||||
_queue_class = MeasuredQueue
|
||||
|
||||
def connect(self):
|
||||
tracer = trace.get_tracer("messenger.database")
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
"postgresql.pool.acquire",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={
|
||||
"db.system.name": "postgresql",
|
||||
"db.operation.name": "CONNECT",
|
||||
"server.address": "postgres",
|
||||
},
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
try:
|
||||
connection = super().connect()
|
||||
except BaseException as exc:
|
||||
span.set_attribute(
|
||||
"error.type", type(exc).__name__
|
||||
)
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
return connection
|
||||
|
||||
def waiting_count(self):
|
||||
with self._pool.waiting_lock:
|
||||
return self._pool.waiting
|
||||
|
||||
|
||||
database_url = read_database_url()
|
||||
|
||||
engine = create_async_engine(
|
||||
database_url,
|
||||
poolclass=MeasuredPool,
|
||||
pool_size=POOL_SIZE,
|
||||
max_overflow=MAX_OVERFLOW,
|
||||
pool_timeout=POOL_TIMEOUT_SECONDS,
|
||||
@@ -37,6 +99,66 @@ engine = create_async_engine(
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
@event.listens_for(engine.sync_engine, "before_cursor_execute")
|
||||
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
operation = statement.lstrip().split(None, 1)
|
||||
operation = operation[0].upper() if operation else "OTHER"
|
||||
|
||||
if operation not in {
|
||||
"SELECT", "INSERT", "UPDATE", "DELETE",
|
||||
"WITH", "CREATE", "ALTER", "DROP",
|
||||
}:
|
||||
operation = "OTHER"
|
||||
|
||||
tracer = trace.get_tracer("messenger.database")
|
||||
|
||||
manager = tracer.start_as_current_span(
|
||||
f"postgresql.{operation}",
|
||||
kind=SpanKind.CLIENT,
|
||||
attributes={
|
||||
"db.system.name": "postgresql",
|
||||
"db.operation.name": operation,
|
||||
"server.address": "postgres",
|
||||
},
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
)
|
||||
|
||||
span = manager.__enter__()
|
||||
context._messenger_db_span = (manager, span)
|
||||
|
||||
|
||||
def finish_database_span(context, failed=False):
|
||||
if context is None:
|
||||
return
|
||||
|
||||
state = getattr(context, "_messenger_db_span", None)
|
||||
|
||||
if state is None:
|
||||
return
|
||||
|
||||
context._messenger_db_span = None
|
||||
manager, span = state
|
||||
|
||||
span.set_status(
|
||||
Status(StatusCode.ERROR if failed else StatusCode.OK)
|
||||
)
|
||||
|
||||
manager.__exit__(None, None, None)
|
||||
|
||||
|
||||
@event.listens_for(engine.sync_engine, "after_cursor_execute")
|
||||
def after_cursor_execute(conn, cursor, statement, parameters, context, executemany):
|
||||
finish_database_span(context)
|
||||
|
||||
|
||||
@event.listens_for(engine.sync_engine, "handle_error")
|
||||
def handle_database_error(exception_context):
|
||||
finish_database_span(
|
||||
exception_context.execution_context,
|
||||
failed=True,
|
||||
)
|
||||
|
||||
SessionFactory = async_sessionmaker(
|
||||
bind=engine,
|
||||
expire_on_commit=False,
|
||||
|
||||
@@ -1,149 +1,175 @@
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory, engine
|
||||
from src.queue import connect, publish, publish_failed
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def dispatch(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued',
|
||||
published_at = NULL,
|
||||
started_at = NULL,
|
||||
execution_id = NULL
|
||||
WHERE status = 'processing'
|
||||
AND started_at < now() - interval '90 seconds'
|
||||
""")
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
updated_at = now()
|
||||
WHERE status = 'processing'
|
||||
AND id IN (
|
||||
SELECT attachment_id
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
)
|
||||
""")
|
||||
)
|
||||
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation, created_at
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
AND (
|
||||
next_attempt_at IS NULL
|
||||
OR next_attempt_at <= now()
|
||||
)
|
||||
ORDER BY created_at LIMIT 25
|
||||
FOR
|
||||
UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
publish(channel, row)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def dispatch_failed(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation,
|
||||
last_error_code, created_at, finished_at
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'failed'
|
||||
AND failed_published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 25
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"type": "attachment.failed.v1",
|
||||
"job_id": str(row.id),
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"error_code": row.last_error_code,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"finished_at": (
|
||||
row.finished_at.isoformat()
|
||||
if row.finished_at
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
publish_failed(channel, payload)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET failed_published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def main():
|
||||
while True:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.confirm_delivery()
|
||||
|
||||
while True:
|
||||
count = await dispatch(channel)
|
||||
failed_count = await dispatch_failed(channel)
|
||||
await asyncio.sleep(0.2 if count or failed_count else 1)
|
||||
|
||||
except Exception:
|
||||
logging.exception("Dispatcher reconnect")
|
||||
await asyncio.sleep(3)
|
||||
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
finally:
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory, engine
|
||||
from src.queue import connect, publish, publish_failed
|
||||
from src.telemetry import setup
|
||||
from src.runtime_metrics import update_queue
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
|
||||
async def collect_queue_metrics():
|
||||
async with SessionFactory() as session:
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT
|
||||
count(*) AS depth,
|
||||
COALESCE(
|
||||
EXTRACT(EPOCH FROM (
|
||||
now() - min(created_at)
|
||||
)),
|
||||
0
|
||||
) AS oldest
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
""")
|
||||
)
|
||||
|
||||
row = result.one()
|
||||
update_queue(row.depth, row.oldest)
|
||||
|
||||
|
||||
async def dispatch(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET status = 'queued',
|
||||
published_at = NULL,
|
||||
started_at = NULL,
|
||||
execution_id = NULL
|
||||
WHERE status = 'processing'
|
||||
AND started_at < now() - interval '90 seconds'
|
||||
""")
|
||||
)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachments
|
||||
SET status = 'queued',
|
||||
updated_at = now()
|
||||
WHERE status = 'processing'
|
||||
AND id IN (
|
||||
SELECT attachment_id
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'queued'
|
||||
)
|
||||
""")
|
||||
)
|
||||
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation, created_at,
|
||||
traceparent, tracestate
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
AND (
|
||||
next_attempt_at IS NULL
|
||||
OR next_attempt_at <= now()
|
||||
)
|
||||
ORDER BY created_at LIMIT 25
|
||||
FOR
|
||||
UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
publish(channel, row)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def dispatch_failed(channel):
|
||||
async with SessionFactory() as session:
|
||||
async with session.begin():
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT id, attachment_id, attempt, generation,
|
||||
last_error_code, created_at, finished_at
|
||||
FROM attachment_jobs
|
||||
WHERE status = 'failed'
|
||||
AND failed_published_at IS NULL
|
||||
ORDER BY created_at
|
||||
LIMIT 25
|
||||
FOR UPDATE SKIP LOCKED
|
||||
""")
|
||||
)
|
||||
|
||||
rows = result.all()
|
||||
|
||||
for row in rows:
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"type": "attachment.failed.v1",
|
||||
"job_id": str(row.id),
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"error_code": row.last_error_code,
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"finished_at": (
|
||||
row.finished_at.isoformat()
|
||||
if row.finished_at
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
publish_failed(channel, payload)
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
UPDATE attachment_jobs
|
||||
SET failed_published_at = now()
|
||||
WHERE id = :id
|
||||
"""),
|
||||
{"id": row.id},
|
||||
)
|
||||
|
||||
return len(rows)
|
||||
|
||||
|
||||
async def main():
|
||||
setup("messenger-dispatcher")
|
||||
while True:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
connection, channel = connect()
|
||||
channel.confirm_delivery()
|
||||
|
||||
while True:
|
||||
count = await dispatch(channel)
|
||||
failed_count = await dispatch_failed(channel)
|
||||
await collect_queue_metrics()
|
||||
await asyncio.sleep(0.2 if count or failed_count else 1)
|
||||
|
||||
except Exception:
|
||||
logging.exception("Dispatcher reconnect")
|
||||
await asyncio.sleep(3)
|
||||
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
asyncio.run(main())
|
||||
finally:
|
||||
asyncio.run(engine.dispose())
|
||||
@@ -56,7 +56,7 @@ async def lifespan(app: FastAPI):
|
||||
|
||||
|
||||
|
||||
from src.telemetry import setup, HTTPMetricsMiddleware
|
||||
from src.telemetry import setup, HTTPMetricsMiddleware, capture_trace_context
|
||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||
|
||||
setup("messenger-api")
|
||||
@@ -637,14 +637,22 @@ async def upload_attachment_endpoint(
|
||||
s3_key=s3_key,
|
||||
)
|
||||
|
||||
trace_context = capture_trace_context()
|
||||
|
||||
await session.execute(
|
||||
text("""
|
||||
INSERT INTO attachment_jobs (id, attachment_id)
|
||||
VALUES (:job_id, :attachment_id)
|
||||
INSERT INTO attachment_jobs (
|
||||
id, attachment_id, traceparent, tracestate
|
||||
)
|
||||
VALUES (
|
||||
:job_id, :attachment_id, :traceparent, :tracestate
|
||||
)
|
||||
"""),
|
||||
{
|
||||
"job_id": uuid4(),
|
||||
"attachment_id": attachment_id,
|
||||
"traceparent": trace_context.get("traceparent"),
|
||||
"tracestate": trace_context.get("tracestate"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -1,78 +1,110 @@
|
||||
import json
|
||||
import os
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.failed.v1"
|
||||
|
||||
|
||||
def connect():
|
||||
password = Path(
|
||||
os.environ["RABBITMQ_PASSWORD_FILE"]
|
||||
).read_text().strip()
|
||||
|
||||
credentials = pika.PlainCredentials(
|
||||
"messenger",
|
||||
password,
|
||||
)
|
||||
|
||||
connection = pika.BlockingConnection(
|
||||
pika.ConnectionParameters(
|
||||
host=os.getenv("RABBITMQ_HOST", "rabbitmq"),
|
||||
credentials=credentials,
|
||||
heartbeat=60,
|
||||
blocked_connection_timeout=30,
|
||||
connection_attempts=3,
|
||||
retry_delay=2,
|
||||
)
|
||||
)
|
||||
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
|
||||
return connection, channel
|
||||
|
||||
|
||||
def publish(channel, row):
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(row.id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"created_at": row.created_at.astimezone(
|
||||
timezone.utc
|
||||
).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=str(row.id),
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
|
||||
def publish_failed(channel, payload: dict):
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=DLQ,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=payload["job_id"],
|
||||
),
|
||||
mandatory=True,
|
||||
import json
|
||||
import os
|
||||
from datetime import timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from src.telemetry import capture_trace_context, restore_trace_context
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.failed.v1"
|
||||
|
||||
|
||||
def connect():
|
||||
password = Path(
|
||||
os.environ["RABBITMQ_PASSWORD_FILE"]
|
||||
).read_text().strip()
|
||||
|
||||
credentials = pika.PlainCredentials(
|
||||
"messenger",
|
||||
password,
|
||||
)
|
||||
|
||||
connection = pika.BlockingConnection(
|
||||
pika.ConnectionParameters(
|
||||
host=os.getenv("RABBITMQ_HOST", "rabbitmq"),
|
||||
credentials=credentials,
|
||||
heartbeat=60,
|
||||
blocked_connection_timeout=30,
|
||||
connection_attempts=3,
|
||||
retry_delay=2,
|
||||
)
|
||||
)
|
||||
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
|
||||
return connection, channel
|
||||
|
||||
|
||||
def publish(channel, row):
|
||||
tracer = trace.get_tracer("messenger.dispatcher")
|
||||
context = restore_trace_context({
|
||||
"traceparent": row.traceparent,
|
||||
"tracestate": row.tracestate,
|
||||
})
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
"attachment.publish",
|
||||
context=context,
|
||||
kind=SpanKind.PRODUCER,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
attributes={
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE,
|
||||
"job.attempt": row.attempt,
|
||||
"job.generation": row.generation,
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
publish_message(channel, row)
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
|
||||
def publish_message(channel, row):
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(row.id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(row.attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": row.attempt,
|
||||
"generation": row.generation,
|
||||
"created_at": row.created_at.astimezone(
|
||||
timezone.utc
|
||||
).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=QUEUE,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=str(row.id),
|
||||
headers=capture_trace_context(),
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
|
||||
def publish_failed(channel, payload: dict):
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=DLQ,
|
||||
body=json.dumps(payload).encode(),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=payload["job_id"],
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
@@ -0,0 +1,158 @@
|
||||
import os
|
||||
import resource
|
||||
import time
|
||||
from threading import Lock
|
||||
|
||||
from opentelemetry import metrics
|
||||
from opentelemetry.metrics import Observation
|
||||
|
||||
|
||||
_lock = Lock()
|
||||
_busy = 0
|
||||
_backlog = 0
|
||||
_oldest = 0.0
|
||||
_queue_updated = 0.0
|
||||
_initialized = False
|
||||
_last_cpu = time.process_time()
|
||||
_last_wall = time.monotonic()
|
||||
|
||||
|
||||
def cpu_usage(options):
|
||||
global _last_cpu, _last_wall
|
||||
|
||||
with _lock:
|
||||
cpu = time.process_time()
|
||||
wall = time.monotonic()
|
||||
|
||||
value = (cpu - _last_cpu) / max(wall - _last_wall, 0.001)
|
||||
|
||||
_last_cpu = cpu
|
||||
_last_wall = wall
|
||||
|
||||
return [Observation(max(0, value) * 100)]
|
||||
|
||||
|
||||
def memory_usage(options):
|
||||
with open("/proc/self/statm", encoding="utf-8") as file:
|
||||
resident = int(file.read().split()[1])
|
||||
|
||||
return [Observation(resident * os.sysconf("SC_PAGE_SIZE"))]
|
||||
|
||||
|
||||
def worker_started():
|
||||
global _busy
|
||||
|
||||
with _lock:
|
||||
_busy += 1
|
||||
|
||||
|
||||
def worker_finished():
|
||||
global _busy
|
||||
|
||||
with _lock:
|
||||
_busy -= 1
|
||||
|
||||
|
||||
def update_queue(depth, oldest):
|
||||
global _backlog, _oldest, _queue_updated
|
||||
|
||||
with _lock:
|
||||
_backlog = int(depth)
|
||||
_oldest = float(oldest)
|
||||
_queue_updated = time.monotonic()
|
||||
|
||||
|
||||
def queue_observation(field):
|
||||
def callback(options):
|
||||
with _lock:
|
||||
if not _queue_updated:
|
||||
return []
|
||||
|
||||
if time.monotonic() - _queue_updated > 15:
|
||||
return []
|
||||
|
||||
value = _backlog if field == "depth" else _oldest
|
||||
|
||||
return [
|
||||
Observation(
|
||||
value,
|
||||
{"queue_name": "attachment.process.v1"},
|
||||
)
|
||||
]
|
||||
|
||||
return callback
|
||||
|
||||
|
||||
def setup_runtime_metrics(service_name):
|
||||
global _initialized
|
||||
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
from src.database import engine, POOL_SIZE, MAX_OVERFLOW
|
||||
|
||||
meter = metrics.get_meter("messenger.runtime")
|
||||
pool = engine.sync_engine.pool
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_process_cpu_percent",
|
||||
callbacks=[cpu_usage],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_process_memory_bytes",
|
||||
callbacks=[memory_usage],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_db_pool_used",
|
||||
callbacks=[
|
||||
lambda options: [Observation(pool.checkedout())]
|
||||
],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_db_pool_capacity",
|
||||
callbacks=[
|
||||
lambda options: [
|
||||
Observation(POOL_SIZE + MAX_OVERFLOW)
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_db_pool_waiting",
|
||||
callbacks=[
|
||||
lambda options: [
|
||||
Observation(pool.waiting_count())
|
||||
]
|
||||
],
|
||||
)
|
||||
|
||||
if service_name == "messenger-worker":
|
||||
meter.create_observable_gauge(
|
||||
"messenger_worker_busy",
|
||||
callbacks=[
|
||||
lambda options: [Observation(_busy)]
|
||||
],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_worker_capacity",
|
||||
callbacks=[
|
||||
lambda options: [Observation(1)]
|
||||
],
|
||||
)
|
||||
|
||||
if service_name == "messenger-dispatcher":
|
||||
meter.create_observable_gauge(
|
||||
"messenger_queue_depth",
|
||||
callbacks=[queue_observation("depth")],
|
||||
)
|
||||
|
||||
meter.create_observable_gauge(
|
||||
"messenger_queue_oldest_age_seconds",
|
||||
callbacks=[queue_observation("oldest")],
|
||||
)
|
||||
|
||||
_initialized = True
|
||||
@@ -1,87 +1,116 @@
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def read_secret(env_name: str) -> str:
|
||||
path = os.environ[env_name]
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"total_max_attempts": 1, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
S3_BUCKET = os.environ["S3_BUCKET"]
|
||||
|
||||
|
||||
async def put_object(key: str, body: bytes, content_type: str) -> None:
|
||||
await asyncio.to_thread(
|
||||
s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
|
||||
async def get_object(key: str) -> bytes:
|
||||
def download() -> bytes:
|
||||
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
stream = response["Body"]
|
||||
try:
|
||||
return stream.read()
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
return await asyncio.to_thread(download)
|
||||
|
||||
|
||||
async def delete_object(key: str) -> None:
|
||||
await asyncio.to_thread(
|
||||
s3_client.delete_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
|
||||
|
||||
async def ping_storage() -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_bucket,
|
||||
Bucket=S3_BUCKET,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def object_exists(key: str) -> bool:
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}:
|
||||
return False
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from contextlib import contextmanager
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
|
||||
@contextmanager
|
||||
def storage_span(operation):
|
||||
tracer = trace.get_tracer("messenger.storage")
|
||||
|
||||
with tracer.start_as_current_span(
|
||||
f"s3.{operation}",
|
||||
kind=SpanKind.CLIENT,
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
attributes={
|
||||
"rpc.system": "aws-api",
|
||||
"rpc.service": "S3",
|
||||
"rpc.method": operation,
|
||||
},
|
||||
) as span:
|
||||
try:
|
||||
yield
|
||||
span.set_status(Status(StatusCode.OK))
|
||||
except Exception:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
raise
|
||||
|
||||
|
||||
def read_secret(env_name: str) -> str:
|
||||
path = os.environ[env_name]
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
connect_timeout=2,
|
||||
read_timeout=3,
|
||||
retries={"total_max_attempts": 1, "mode": "standard"},
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
S3_BUCKET = os.environ["S3_BUCKET"]
|
||||
|
||||
|
||||
async def put_object(key: str, body: bytes, content_type: str) -> None:
|
||||
with storage_span("PutObject"):
|
||||
await asyncio.to_thread(
|
||||
s3_client.put_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
Body=body,
|
||||
ContentType=content_type,
|
||||
)
|
||||
|
||||
|
||||
async def get_object(key: str) -> bytes:
|
||||
with storage_span("GetObject"):
|
||||
def download() -> bytes:
|
||||
response = s3_client.get_object(Bucket=S3_BUCKET, Key=key)
|
||||
stream = response["Body"]
|
||||
try:
|
||||
return stream.read()
|
||||
finally:
|
||||
stream.close()
|
||||
|
||||
return await asyncio.to_thread(download)
|
||||
|
||||
|
||||
async def delete_object(key: str) -> None:
|
||||
with storage_span("DeleteObject"):
|
||||
await asyncio.to_thread(
|
||||
s3_client.delete_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
|
||||
|
||||
async def ping_storage() -> bool:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_bucket,
|
||||
Bucket=S3_BUCKET,
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
async def object_exists(key: str) -> bool:
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client.head_object,
|
||||
Bucket=S3_BUCKET,
|
||||
Key=key,
|
||||
)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
if exc.response["Error"]["Code"] in {"404", "NoSuchKey", "NotFound"}:
|
||||
return False
|
||||
raise
|
||||
@@ -5,11 +5,13 @@ import socket
|
||||
import time
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
@@ -19,6 +21,25 @@ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
|
||||
propagator = TraceContextTextMapPropagator()
|
||||
|
||||
|
||||
def capture_trace_context():
|
||||
carrier = {}
|
||||
propagator.inject(carrier)
|
||||
return carrier
|
||||
|
||||
|
||||
def restore_trace_context(carrier):
|
||||
headers = {
|
||||
key: value
|
||||
for key, value in (carrier or {}).items()
|
||||
if key in {"traceparent", "tracestate"}
|
||||
and isinstance(value, str)
|
||||
}
|
||||
return propagator.extract(headers)
|
||||
|
||||
|
||||
_initialized = False
|
||||
logger = logging.getLogger("messenger.telemetry")
|
||||
|
||||
@@ -89,6 +110,35 @@ def setup(service_name):
|
||||
MeterProvider(
|
||||
resource=resource,
|
||||
metric_readers=[reader],
|
||||
views=[
|
||||
View(
|
||||
instrument_name="messenger_http_request_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.005, 0.01, 0.025, 0.05, 0.1,
|
||||
0.25, 0.5, 1, 2.5, 5, 10, 30
|
||||
]
|
||||
),
|
||||
),
|
||||
View(
|
||||
instrument_name="messenger_job_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.01, 0.025, 0.05, 0.1, 0.25,
|
||||
0.5, 1, 2.5, 5, 10, 30, 60
|
||||
]
|
||||
),
|
||||
),
|
||||
View(
|
||||
instrument_name="messenger_attachment_ready_duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(
|
||||
boundaries=[
|
||||
0.1, 0.25, 0.5, 1, 2, 3, 5,
|
||||
10, 15, 30, 60, 120, 300
|
||||
]
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
@@ -117,6 +167,10 @@ def setup(service_name):
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
from src.runtime_metrics import setup_runtime_metrics
|
||||
|
||||
setup_runtime_metrics(service_name)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
@@ -198,7 +252,7 @@ class HTTPMetricsMiddleware:
|
||||
)
|
||||
|
||||
|
||||
async def observe_job(process, payload):
|
||||
async def observe_job(process, payload, headers=None):
|
||||
tracer = trace.get_tracer("messenger.worker")
|
||||
meter = metrics.get_meter("messenger.worker")
|
||||
|
||||
@@ -219,6 +273,7 @@ async def observe_job(process, payload):
|
||||
with tracer.start_as_current_span(
|
||||
"attachment.process",
|
||||
kind=SpanKind.CONSUMER,
|
||||
context=restore_trace_context(headers),
|
||||
record_exception=False,
|
||||
set_status_on_exception=False,
|
||||
) as span:
|
||||
@@ -237,6 +292,8 @@ async def observe_job(process, payload):
|
||||
|
||||
span.set_attribute("job.outcome", outcome)
|
||||
span.set_attribute("job.type", "attachment.process.v1")
|
||||
span.set_attribute("job.attempt", payload.get("attempt", 1))
|
||||
span.set_attribute("job.generation", payload.get("generation", 1))
|
||||
|
||||
if outcome in {"failed", "retry", "error", "unknown"}:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
|
||||
@@ -13,6 +13,8 @@ from sqlalchemy import text
|
||||
|
||||
from src.database import SessionFactory
|
||||
from src.telemetry import setup, observe_job
|
||||
from src.runtime_metrics import worker_started, worker_finished
|
||||
from opentelemetry import metrics
|
||||
from src.queue import QUEUE, connect
|
||||
from src.storage import get_object, put_object
|
||||
from src.images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES
|
||||
@@ -128,7 +130,7 @@ async def process(payload: dict):
|
||||
result = await session.execute(
|
||||
text("""
|
||||
SELECT j.status, j.attempt, j.generation,
|
||||
a.s3_key, a.content_type, a.chat_id
|
||||
a.s3_key, a.content_type, a.chat_id, j.created_at
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = :job_id
|
||||
@@ -173,6 +175,15 @@ async def process(payload: dict):
|
||||
)
|
||||
|
||||
try:
|
||||
retry_marker = "/tmp/lab6_retry_once"
|
||||
try:
|
||||
os.unlink(retry_marker)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
else:
|
||||
await asyncio.sleep(8)
|
||||
raise RuntimeError("controlled_temporary_failure")
|
||||
|
||||
body = await get_object(row.s3_key)
|
||||
validate_worker_image(body)
|
||||
thumbnail, width, height = await asyncio.to_thread(
|
||||
@@ -310,6 +321,19 @@ async def process(payload: dict):
|
||||
)
|
||||
|
||||
|
||||
meter = metrics.get_meter("messenger.worker")
|
||||
|
||||
end_to_end = meter.create_histogram(
|
||||
"messenger_attachment_ready_duration",
|
||||
unit="s",
|
||||
description="Time from durable acceptance to ready",
|
||||
)
|
||||
|
||||
end_to_end.record(
|
||||
max(0, time.time() - row.created_at.timestamp()),
|
||||
{"job_type": "attachment.process.v1"},
|
||||
)
|
||||
|
||||
return "success"
|
||||
|
||||
except Exception as exc:
|
||||
@@ -421,10 +445,16 @@ def main():
|
||||
asyncio.set_event_loop(loop)
|
||||
|
||||
def callback(ch, method, properties, body):
|
||||
|
||||
worker_started()
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
asyncio.wait_for(
|
||||
observe_job(process, json.loads(body)),
|
||||
observe_job(
|
||||
process,
|
||||
json.loads(body),
|
||||
properties.headers,
|
||||
),
|
||||
timeout=MAX_PROCESSING_SECONDS,
|
||||
)
|
||||
)
|
||||
@@ -437,6 +467,8 @@ def main():
|
||||
requeue=True,
|
||||
)
|
||||
time.sleep(2)
|
||||
finally:
|
||||
worker_finished()
|
||||
|
||||
channel.basic_consume(
|
||||
queue=QUEUE,
|
||||
|
||||