Add 6 lab code

This commit is contained in:
2026-11-25 12:55:15 +03:00
parent 20afc2c790
commit f6882a77b4
56 changed files with 3570 additions and 0 deletions
+716
View File
@@ -0,0 +1,716 @@
{
"uid": "messenger-lab6",
"title": "Messenger / Lab 6",
"schemaVersion": 41,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-30m",
"to": "now"
},
"tags": [
"lab6"
],
"panels": [
{
"id": 1,
"title": "API requests / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"description": "Business requests only; health probes are excluded.",
"targets": [
{
"refId": "A",
"expr": "sum by (method,route) (rate(http_requests_total{service_name=\"messenger-api\"}[2m]))",
"legendFormat": "{{method}} {{route}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 2,
"title": "API server error ratio",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"description": "5xx / all non-health requests, rolling 2m. 4xx are not server errors.",
"targets": [
{
"refId": "A",
"expr": "messenger:http_error_ratio:2m",
"legendFormat": "5xx / all"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 3,
"title": "API duration p50 / p95 / p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"description": "Quantiles from merged histogram buckets across API replicas. Never averages of per-instance percentiles.",
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 4,
"title": "Job attempts / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"description": "One count per claimed attempt; failed includes retryable failures, skipped is a fenced attempt.",
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(jobs_processed_total[2m]))",
"legendFormat": "{{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 5,
"title": "Worker processing duration p50 / p95 / p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"description": "Includes isolated image process and durable result check; excludes queue wait.",
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(job_duration_seconds_bucket[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(job_duration_seconds_bucket[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(job_duration_seconds_bucket[2m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 6,
"title": "Time from accepted upload to ready",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"description": "Database timestamps: durable attachment creation to ready update. Includes queue wait and retries; observed on successful attempts.",
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 7,
"title": "Durable queue depth",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"description": "PostgreSQL queued attachments, including unpublished outbox/retries; excludes processing jobs.",
"targets": [
{
"refId": "A",
"expr": "max(queue_depth)",
"legendFormat": "queued"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 8,
"title": "Oldest queued attachment age",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"description": "Age since acceptance. A stale sample is not zero; check queue sample age below.",
"targets": [
{
"refId": "A",
"expr": "max(queue_oldest_age_seconds)",
"legendFormat": "age"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 9,
"title": "DB pool used / acquiring",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"description": "Per long-lived process. Acquiring includes connection creation and pool wait; max pool size is 10.",
"targets": [
{
"refId": "A",
"expr": "db_pool_used",
"legendFormat": "{{service_name}} {{service_instance_id}} used"
},
{
"refId": "B",
"expr": "db_pool_waiting",
"legendFormat": "{{service_name}} {{service_instance_id}} acquiring"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 10,
"title": "Worker saturation",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"description": "Busy consumers / configured concurrency. Missing capacity after 30s indicates stopped worker.",
"targets": [
{
"refId": "A",
"expr": "sum(worker_busy)",
"legendFormat": "busy"
},
{
"refId": "B",
"expr": "sum(worker_capacity)",
"legendFormat": "capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 11,
"title": "Container memory (includes image children)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"description": "cgroup v2 memory.current. Includes child processes and charged cache.",
"targets": [
{
"refId": "A",
"expr": "container_memory_bytes",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 12,
"title": "Container CPU",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"description": "cgroup v2 CPU seconds / second; 1.0 is one fully used CPU core.",
"targets": [
{
"refId": "A",
"expr": "rate(container_cpu_seconds_total[2m])",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 13,
"title": "API availability SLI / SLO",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"description": "Target: >=99% non-5xx business requests in a rolling 30m window. No traffic is not evidence that SLO is met.",
"targets": [
{
"refId": "A",
"expr": "1 - ((sum(increase(http_requests_total{service_name=\"messenger-api\",status_class=\"5xx\"}[30m])) or vector(0)) / clamp_min(sum(increase(http_requests_total{service_name=\"messenger-api\"}[30m])), 1))",
"legendFormat": "SLI over 30m"
},
{
"refId": "B",
"expr": "vector(0.99)",
"legendFormat": "SLO"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 14,
"title": "Local alerts",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"description": "1 means pending/firing. Series disappears after resolution. Rules and runbooks are stored in infra/otel.",
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"ApiHighErrorRate|QueueLagHigh\"}",
"legendFormat": "{{alertname}} {{alertstate}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 15,
"title": "Collector memory",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"description": "",
"targets": [
{
"refId": "A",
"expr": "otelcol_process_memory_rss_bytes",
"legendFormat": "RSS"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 16,
"title": "Collector exporter queue / capacity",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"description": "Bounded queues: 32 batches per backend, up to 256 records per batch.",
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "{{exporter}} queued"
},
{
"refId": "B",
"expr": "otelcol_exporter_queue_capacity",
"legendFormat": "{{exporter}} capacity"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 17,
"title": "Collector failed sends / rejected enqueue",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"description": "Send failures may include retries, not unique lost spans. Exact experiment loss is measured by accepted/sent deltas after draining.",
"targets": [
{
"refId": "A",
"expr": "rate(otelcol_exporter_send_failed_spans_total[2m])",
"legendFormat": "{{exporter}} span send failures"
},
{
"refId": "B",
"expr": "rate(otelcol_exporter_send_failed_log_records_total[2m])",
"legendFormat": "{{exporter}} log send failures"
},
{
"refId": "C",
"expr": "rate(otelcol_exporter_enqueue_failed_spans_total[2m])",
"legendFormat": "{{exporter}} span queue rejections"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 18,
"title": "Queue sample age",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"description": "Above 15s: queue measurements are stale (e.g. DB outage).",
"targets": [
{
"refId": "A",
"expr": "time() - max(queue_sample_timestamp_seconds)",
"legendFormat": "seconds since DB sample"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
}
],
"links": [
{
"title": "Explore logs",
"url": "/explore?left=%7B%22datasource%22%3A%22loki%22%7D"
},
{
"title": "Explore traces",
"url": "/explore?left=%7B%22datasource%22%3A%22tempo%22%7D"
}
]
}
@@ -0,0 +1,7 @@
apiVersion: 1
providers:
- name: messenger
folder: Lab 6
type: file
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,41 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 5s
exemplarTraceIdDestinations:
- name: trace_id
datasourceUid: tempo
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
derivedFields:
- name: trace_id
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: '$${__value.raw}'
urlDisplayLabel: View trace
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: '-5m'
spanEndTimeShift: '5m'
tags: [{key: service.name, value: service_name}]
filterByTraceID: true
filterBySpanID: false
nodeGraph:
enabled: true
+38
View File
@@ -0,0 +1,38 @@
worker_processes 1;
worker_shutdown_timeout 8s;
events { worker_connections 1024; }
http {
upstream messenger {
zone messenger 64k;
include /etc/nginx/ready-backends.conf;
}
log_format upstream '$request_method $uri $status upstream=$upstream_addr '
'upstream_status=$upstream_status time=$request_time';
access_log /var/log/nginx/access.log upstream;
server {
listen 8080;
# API enforces the byte limit and returns the contracted JSON error.
client_max_body_size 0;
client_body_timeout 5s;
client_header_timeout 5s;
keepalive_timeout 5s;
location / {
proxy_pass http://messenger;
proxy_http_version 1.1;
proxy_request_buffering off;
proxy_buffering off;
proxy_set_header Host $host;
proxy_set_header Connection close;
proxy_connect_timeout 1s;
proxy_send_timeout 35s;
proxy_read_timeout 120s;
# A 503 is an API response (for example, S3 is unavailable), so
# preserve it for the client instead of marking every replica down.
proxy_next_upstream error timeout http_502 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 8s;
# Never transparently retry a POST already sent to an API.
# A client retries messages using the original Idempotency-Key.
}
}
}
+28
View File
@@ -0,0 +1,28 @@
groups:
- name: messenger
rules:
- record: messenger:http_error_ratio:2m
expr: |
(sum(rate(http_requests_total{service_name="messenger-api",status_class="5xx"}[2m])) or vector(0))
/ clamp_min(sum(rate(http_requests_total{service_name="messenger-api"}[2m])), 0.001)
- alert: ApiHighErrorRate
expr: messenger:http_error_ratio:2m > 0.05 and sum(increase(http_requests_total{service_name="messenger-api"}[2m])) >= 20
for: 20s
labels:
severity: warning
annotations:
summary: 'API: more than 5% server errors over 2 minutes'
description: 'SLI is 5xx / all non-health requests. At least 20 requests in the window.'
runbook: 'infra/otel/README.md#api-errors'
- alert: QueueLagHigh
expr: |
max(queue_oldest_age_seconds) > 30
and max(queue_depth) > 0
and time() - max(queue_sample_timestamp_seconds) < 15
for: 15s
labels:
severity: warning
annotations:
summary: 'Oldest queued attachment waits more than 30 seconds'
description: 'Check worker capacity/busy and job errors; backlog is sampled by dispatcher.'
runbook: 'infra/otel/README.md#queue-lag'
+69
View File
@@ -0,0 +1,69 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
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
enable_open_metrics: true
metric_expiration: 30s
translation_strategy: UnderscoreEscapingWithSuffixes
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
queue_size: 32
num_consumers: 2
block_on_overflow: false
retry_on_failure:
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 15s
otlphttp/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue:
queue_size: 32
num_consumers: 2
block_on_overflow: false
retry_on_failure:
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 15s
service:
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
+37
View File
@@ -0,0 +1,37 @@
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: 72h
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes: [service.name, deployment.environment.name]
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+12
View File
@@ -0,0 +1,12 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: messenger
static_configs:
- targets: ['otel-collector:8889']
- job_name: collector
static_configs:
- targets: ['otel-collector:8888']
+23
View File
@@ -0,0 +1,23 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
ingester:
trace_idle_period: 10s
max_block_duration: 5m
compactor:
compaction:
block_retention: 72h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+38
View File
@@ -0,0 +1,38 @@
#!/bin/sh
# Only ready API addresses enter the upstream, including at nginx startup.
update_backends() {
next=/etc/nginx/ready-backends.conf.next
: > "$next"
for address in $(getent ahostsv4 api | awk '{print $1}' | sort -u); do
if wget -q -T 1 -O /dev/null "http://$address:8080/health/ready"; then
echo "server $address:8080;" >> "$next"
fi
done
# If every running API temporarily loses a shared dependency (for example
# S3), retain the last addresses. The API can then return the contracted
# 503 instead of Nginx replacing it with a 502. At initial startup there
# is no previous healthy set, so use an inert placeholder.
if [ ! -s "$next" ]; then
if [ -s /etc/nginx/ready-backends.conf ] && ! grep -q '127.0.0.1:9 down' /etc/nginx/ready-backends.conf; then
rm -f "$next"
return
fi
echo 'server 127.0.0.1:9 down;' > "$next"
fi
if ! cmp -s "$next" /etc/nginx/ready-backends.conf; then
mv "$next" /etc/nginx/ready-backends.conf
if [ "${1:-}" = reload ] && [ -f /var/run/nginx.pid ]; then
nginx -s reload
fi
else
rm -f "$next"
fi
}
update_backends
(
while sleep 2; do
update_backends reload
done
) &
exec nginx -g 'daemon off;'
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
test "$MINIO_ROOT_USER" != "$S3_ACCESS_KEY_ID"
mc alias set local http://s3:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null
mc mb --ignore-existing local/messenger-attachments
mc anonymous set none local/messenger-attachments
mc admin user add local "$S3_ACCESS_KEY_ID" "$S3_SECRET_ACCESS_KEY" >/dev/null
mc admin policy info local attachments >/dev/null 2>&1 || mc admin policy create local attachments /policy.json
mc admin policy attach local attachments --user "$S3_ACCESS_KEY_ID"
+17
View File
@@ -0,0 +1,17 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::messenger-attachments"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/originals/*",
"arn:aws:s3:::messenger-attachments/staging/*",
"arn:aws:s3:::messenger-attachments/variants/*"]
}
]
}