forked from mtusi2026/mtusi2026lab6
Grade 4
This commit is contained in:
@@ -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
|
||||
+137
-4
@@ -1,7 +1,140 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
# Лаба 6: запуск и диагностика
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
```sh
|
||||
cp .env.example .env
|
||||
# Задать локальные пароли в .env (в Git не добавлять).
|
||||
docker compose up -d --build
|
||||
python -X utf8 tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
python -X utf8 tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json
|
||||
python -X utf8 student-tests/observability.py --scenario all
|
||||
```
|
||||
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
Последняя команда создаёт синтетические данные и временно останавливает **только
|
||||
сервисы текущего Compose-проекта**. В `finally` запускает остановленные сервисы.
|
||||
Не запускать параллельно с другими проверками этого стенда. Volumes не удаляются.
|
||||
Санитизированные результаты сохраняются в `evidence/observability.json`.
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
Grafana: http://localhost:3000, пользователь `admin`, пароль `GRAFANA_ADMIN_PASSWORD`
|
||||
из `.env`. Dashboard **Lab 6 / Messenger / Lab 6** и три datasource загружаются
|
||||
автоматически. Prometheus: http://localhost:9090; Loki API: порт 3100; Tempo API:
|
||||
3200. Все опубликованные порты слушают только loopback, OTLP наружу не опубликован.
|
||||
|
||||
Collector принимает OTLP/HTTP от API, dispatcher и worker. Prometheus хранит
|
||||
метрики, Loki — логи, Tempo — трассы; Grafana обращается к этим хранилищам.
|
||||
История сохраняется в именованных volumes, retention — 72 часа.
|
||||
Версии закреплены в Compose и requirements.txt: OTel Python 1.38.0, semantic
|
||||
conventions 0.59b0 (зависимость SDK); наши имена метрик перечислены ниже.
|
||||
Это явная инструментация: auto-instrumentation, сбор SQL и HTTP headers отключены.
|
||||
|
||||
## Сигналы
|
||||
|
||||
| Prometheus name | Единицы и смысл |
|
||||
| --- | --- |
|
||||
| `http_requests_total` | Число бизнес-запросов; method, route template, status_class |
|
||||
| `http_duration_seconds` | Histogram полного HTTP-запроса, включая отдачу stream |
|
||||
| `jobs_processed_total` | Попытки обработки; job_type, outcome=ready/failed/skipped |
|
||||
| `job_duration_seconds` | Histogram времени попытки, без ожидания в очереди |
|
||||
| `attachment_time_to_ready_seconds` | Histogram от записи attachment до durable ready, включая retry |
|
||||
| `queue_depth` | Количество queued в PostgreSQL, включая outbox и отложенные retry |
|
||||
| `queue_oldest_age_seconds` | Возраст старейшего queued от момента приёма, не время обработки |
|
||||
| `queue_sample_timestamp_seconds` | Unix-время последнего успешного опроса очереди |
|
||||
| `db_pool_used`, `db_pool_waiting` | Занятые соединения / потоки, получающие соединение (ожидание + reconnect) |
|
||||
| `worker_busy`, `worker_capacity` | Число занятых consumer / лимит concurrency |
|
||||
| `process_memory_bytes`, `process_cpu_seconds_total` | RSS и CPU процесса |
|
||||
| `container_memory_bytes`, `container_cpu_seconds_total` | cgroup v2, включая дочерние процессы обработки |
|
||||
|
||||
Histogram buckets, секунды: .005, .01, .025, .05, .1, .25, .5, 1, 2, 3, 5, 10,
|
||||
30, 60, 120, 300, +Inf. Dashboard содержит PromQL, единицы и описания каждого
|
||||
графика. p50/p95/p99 считаются `histogram_quantile` по сумме buckets всех реплик.
|
||||
Метрики очереди отдаёт только dispatcher; это не длина Redis Stream (в нём
|
||||
ещё могут быть уже взятые сообщения). При недоступной БД sample становится
|
||||
устаревшим; возраст sample выведен отдельно, QueueLagHigh не использует stale data.
|
||||
|
||||
Resource: service.name, service.version=1.6.0, service.instance.id=hostname,
|
||||
deployment.environment.name=lab. API: messenger-api; worker и его дочерний
|
||||
процесс: messenger-worker; publisher: messenger-dispatcher. Дочерний процесс
|
||||
экспортирует только traces/logs, чтобы не создавать отдельные краткоживущие
|
||||
ряды метрик. Parent измеряет длительность попытки и результат после COMMIT.
|
||||
Метрики наблюдательные: авария после COMMIT до записи счётчика может потерять
|
||||
измерение, но не результат обработки. Предметных ID в labels метрик нет.
|
||||
|
||||
## Связь сигналов
|
||||
|
||||
SERVER span API → traceparent/tracestate в transactional outbox → PRODUCER span
|
||||
dispatcher → W3C context в JSON сообщения Redis → CONSUMER span worker → context
|
||||
через окружение изолированного image process → S3/DB CLIENT spans. Retry публикует
|
||||
новый producer/consumer в той же трассе, с `job.attempt`. Baggage не переносится.
|
||||
Context сохранён в миграции 008, поэтому рестарт API не разрывает причинную связь.
|
||||
|
||||
Логи содержат timestamp/severity/service.name/event и trace_id/span_id активного
|
||||
span. `http_request` содержит ограниченный `request_id`, совпадающий с
|
||||
X-Request-Id ответа. Loki сохраняет технические поля как structured metadata;
|
||||
индексирует только service.name и окружение. Для корреляции достаточно request_id,
|
||||
trace_id и номера попытки: имена файлов и предметные ID не экспортируются.
|
||||
|
||||
В Grafana Explore / Loki:
|
||||
|
||||
```logql
|
||||
{service_name="messenger-api"} | request_id="ЗНАЧЕНИЕ_X_REQUEST_ID"
|
||||
{service_name=~"messenger-.*"} | trace_id="TRACE_ID"
|
||||
```
|
||||
|
||||
Поле trace_id открывает Tempo; из Tempo доступен переход к логам. В трассе upload
|
||||
видны `POST /api/v1/chats/{chat_id}/attachments`, `attachment-jobs publish`,
|
||||
`attachment-jobs process`, `image.process`, `s3.GetObject`, `s3.PutObject`,
|
||||
`db.SELECT`/`db.UPDATE`. Исключения содержат только тип, без message/stack/SQL.
|
||||
|
||||
## SLI/SLO и alerts
|
||||
|
||||
SLI доступности = 1 − число 5xx / число всех бизнес-запросов за скользящие **30 минут**.
|
||||
SLO: **не менее 99%**. Health исключён из числителя и знаменателя; 4xx не считается
|
||||
отказом сервера. Без запросов SLI не оцениваем. Это учебное окно, а не месячный SLO.
|
||||
|
||||
`ApiHighErrorRate`: 5xx > 5% за 2 минуты, минимум 20 запросов, `for: 20s`.
|
||||
`QueueLagHigh`: queued > 0 и возраст > 30s, свежий sample, `for: 15s`.
|
||||
Пороги короткие для воспроизводимой локальной демонстрации; алерты не являются
|
||||
burn-rate исследованием. Rules вычисляет Prometheus; firing/pending видны в
|
||||
http://localhost:9090/alerts и на dashboard. После восстановления alert пропадает
|
||||
из instant `ALERTS`; история переходов остаётся в range query. Доставка наружу не настроена.
|
||||
|
||||
## Queue lag
|
||||
|
||||
1. Открыть queue depth/age и worker capacity/busy. Растущая очередь при отсутствии
|
||||
capacity означает остановку worker; свежий sample подтверждает доступность БД.
|
||||
2. В Loki найти `job_published`, затем открыть trace: producer есть, consumer ещё нет.
|
||||
3. `docker compose start worker`; дождаться `job_processed` outcome=ready, depth=0.
|
||||
4. Проверить, что QueueLagHigh больше не firing и в той же трассе появился consumer.
|
||||
|
||||
## API errors
|
||||
|
||||
1. При ApiHighErrorRate найти http_request со status_class=5xx и взять trace_id.
|
||||
2. В Tempo проверить `db.acquire`/`db.SELECT`: error.type и длительность покажут
|
||||
отказ подключения/БД. В Loki есть `db_error`/`operation_failed`. Медленный handler
|
||||
без отказа зависимости не имел бы ошибочного DB span. Посмотреть db_pool_waiting.
|
||||
3. Проверить PostgreSQL: `docker compose ps postgres`; восстановить
|
||||
`docker compose start postgres`, дождаться readiness и успешного бизнес-запроса.
|
||||
4. Через окно 2m error ratio снизится, alert перейдёт в resolved. Sample очереди
|
||||
тоже должен стать свежим. Сценарий проверки сохраняет трассу ошибочного запроса.
|
||||
|
||||
## Недоступность telemetry backend
|
||||
|
||||
SDK: очереди по 512 spans/logs, batch 64, HTTP timeout 1s; metric export каждые 5s.
|
||||
Отправка выполняется в фоновых потоках. Collector: memory limiter 192 MiB,
|
||||
spike 48 MiB, container limit 256 MiB; batch ≤256 записей; отдельная очередь
|
||||
32 batches / 2 consumers на Loki и Tempo; retry до 15s, timeout 2s, overflow
|
||||
не блокирует приём. Конечные ограничения защищают память, но допускают потерю
|
||||
телеметрии при длительном отказе. API и pipeline не зависят от готовности backend.
|
||||
|
||||
Сценарий `backend` останавливает Tempo, продолжает создавать сообщения и
|
||||
обрабатывать изображения, снимает RSS/очередь Collector, затем запускает Tempo
|
||||
и проверяет новую трассу. `send_failed_spans` может считать повторные попытки:
|
||||
его нельзя выдавать за число уникально потерянных spans. Для отдельного окна
|
||||
тест вычисляет accepted − sent после опустошения очереди (без рестартов Collector)
|
||||
и сохраняет эти дельты вместе с наблюдаемой памятью. Это потери уже принятых
|
||||
Collector spans; отброшенные до приёма SDK/receiver в этот счёт не входят.
|
||||
Prometheus всё это время
|
||||
работает, поэтому сохраняется история отказа и восстановления.
|
||||
|
||||
Первичные источники: [Collector](https://opentelemetry.io/docs/collector/configuration/),
|
||||
[native Loki OTLP](https://grafana.com/docs/loki/latest/send-data/otel/),
|
||||
[bounded exporter queues](https://github.com/open-telemetry/opentelemetry-collector/blob/v0.136.0/exporter/exporterhelper/README.md).
|
||||
|
||||
@@ -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'
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -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']
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user