Lab 6: span error status, trace-id error correlation, windowed 5xx share alert
This commit is contained in:
@@ -1 +1 @@
|
|||||||
{"status":"success","data":{"alerts":[{"labels":{"alertname":"ApiHighErrorRate","severity":"critical","slo":"availability"},"annotations":{"description":"Total 5xx count: 245","summary":"More than 10 total 5xx responses"},"state":"firing","activeAt":"2026-11-19T15:20:36.76716048Z","value":"2.45e+02"}]}}
|
{"status":"success","data":{"alerts":[]}}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
0bda10bc-6b9f-4042-bc17-d2a7d5c50b46
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{"status":"success","data":{"resultType":"matrix","result":[{"metric":{},"values":[[1796119192,"0"],[1796119207,"0"],[1796119222,"0"],[1796119237,"0"],[1796119252,"0"],[1796119267,"0"],[1796119282,"0"],[1796119297,"0"],[1796119312,"0"],[1796119327,"0"],[1796119342,"0"],[1796119357,"0"],[1796119372,"0"],[1796119387,"0"],[1796119402,"0"],[1796119417,"0"],[1796119432,"0"],[1796119447,"0.22707508582655025"],[1796119462,"0.35293341292780495"],[1796119477,"0.46155247477537553"],[1796119492,"0.5231423207295195"],[1796119507,"0.6259533242684473"],[1796119522,"0.7233240910942357"],[1796119537,"0.8929098980543483"],[1796119552,"0.9600386775975684"]]}]}}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
bcaac296507528d42e9fad7ed7f320c1
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"total": 12313,
|
||||||
|
"codes": {
|
||||||
|
"202": 1726,
|
||||||
|
"200": 3283,
|
||||||
|
"201": 3236,
|
||||||
|
"500": 4068
|
||||||
|
},
|
||||||
|
"error_share": 0.33038252253715583
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
{"batches":[{"resource":{"attributes":[{"key":"deployment.environment","value":{"stringValue":"dev"}},{"key":"service.instance.id","value":{"stringValue":"1041582a5971"}},{"key":"service.version","value":{"stringValue":"lab6"}},{"key":"service.name","value":{"stringValue":"messenger-api"}}]},"scopeSpans":[{"scope":{"name":"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp","version":"0.72.0"},"spans":[{"traceId":"vKrCllB1KNQun61+1/MgwQ==","spanId":"OZaz4ukjKzU=","name":"POST /api/v1/chats/{chat_id}/attachments","kind":"SPAN_KIND_SERVER","startTimeUnixNano":"1796119311864117959","endTimeUnixNano":"1796119311872561917","attributes":[{"key":"server.address","value":{"stringValue":"localhost"}},{"key":"http.request.method","value":{"stringValue":"POST"}},{"key":"url.scheme","value":{"stringValue":"http"}},{"key":"server.port","value":{"intValue":"8080"}},{"key":"network.peer.address","value":{"stringValue":"172.18.0.14"}},{"key":"network.peer.port","value":{"intValue":"36280"}},{"key":"user_agent.original","value":{"stringValue":"python-requests/2.32.5"}},{"key":"client.address","value":{"stringValue":"172.18.0.14"}},{"key":"url.path","value":{"stringValue":"/api/v1/chats/387472d9-9a57-49f1-a911-5ea97ec4888a/attachments"}},{"key":"network.protocol.version","value":{"stringValue":"1.1"}},{"key":"http.request.body.size","value":{"intValue":"70"}},{"key":"http.response.body.size","value":{"intValue":"419"}},{"key":"http.response.status_code","value":{"intValue":"202"}}],"status":{}}]}]},{"resource":{"attributes":[{"key":"deployment.environment","value":{"stringValue":"dev"}},{"key":"service.instance.id","value":{"stringValue":"2fd3d2f7d7ae"}},{"key":"service.version","value":{"stringValue":"lab6"}},{"key":"service.name","value":{"stringValue":"messenger-worker"}}]},"scopeSpans":[{"scope":{"name":"messenger-worker"},"spans":[{"traceId":"vKrCllB1KNQun61+1/MgwQ==","spanId":"gyPPgHeoHPo=","parentSpanId":"phTojMdrieE=","name":"s3.get_staging","kind":"SPAN_KIND_INTERNAL","startTimeUnixNano":"1796119312116778292","endTimeUnixNano":"1796119316994404628","status":{}},{"traceId":"vKrCllB1KNQun61+1/MgwQ==","spanId":"phTojMdrieE=","parentSpanId":"OZaz4ukjKzU=","name":"process_job","kind":"SPAN_KIND_CONSUMER","startTimeUnixNano":"1796119312115538792","endTimeUnixNano":"1796119316999271919","attributes":[{"key":"messaging.system","value":{"stringValue":"redis_streams"}},{"key":"messaging.operation","value":{"stringValue":"process"}},{"key":"job.id","value":{"stringValue":"5b06dc9c-492b-4655-9408-c621a8153c3c"}},{"key":"job.attempt","value":{"intValue":"1"}}],"events":[{"timeUnixNano":"1796119316994557711","name":"exception","attributes":[{"key":"exception.type","value":{"stringValue":"*fmt.wrapError"}},{"key":"exception.message","value":{"stringValue":"s3_unavailable: stat object: Head \"http://s3:9000/messenger-attachments/staging/6a9d74c0-e690-4cf4-a9fe-830f48fc0fb6.png\": dial tcp: lookup s3 on 127.0.0.11:53: no such host"}}]}],"status":{}}]}]}]}
|
||||||
+33
-37
@@ -1,45 +1,41 @@
|
|||||||
groups:
|
groups:
|
||||||
|
- name: messenger-recordings
|
||||||
|
interval: 15s
|
||||||
|
rules:
|
||||||
|
- record: messenger:http_5xx_share:ratio2m
|
||||||
|
expr: |
|
||||||
|
(
|
||||||
|
sum(rate(messenger_http_responses_total{status_class="5xx"}[2m]))
|
||||||
|
/
|
||||||
|
clamp_min(sum(rate(messenger_http_responses_total[2m])), 0.001)
|
||||||
|
) or vector(0)
|
||||||
|
|
||||||
|
- record: messenger:worker_job_rate:by_status5m
|
||||||
|
expr: |
|
||||||
|
sum by (status) (rate(worker_jobs_processed_total[5m]))
|
||||||
|
or
|
||||||
|
max by (status) (worker_jobs_processed_total) * 0
|
||||||
|
|
||||||
|
- record: messenger:worker_job_duration_seconds:p95_5m
|
||||||
|
expr: |
|
||||||
|
histogram_quantile(0.95, sum by (le) (rate(worker_job_duration_seconds_bucket[5m])))
|
||||||
|
or vector(0)
|
||||||
|
|
||||||
|
- record: messenger:queue_depth
|
||||||
|
expr: max(attachment_jobs_queue_depth) or vector(0)
|
||||||
|
|
||||||
|
- record: messenger:collector_up
|
||||||
|
expr: max(up{job="otel-collector"}) or vector(0)
|
||||||
|
|
||||||
- name: messenger-slo
|
- name: messenger-slo
|
||||||
rules:
|
rules:
|
||||||
- alert: ApiHighErrorRate
|
- alert: ApiHighErrorRate
|
||||||
expr: sum(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}) > 10
|
expr: messenger:http_5xx_share:ratio2m > 0.05
|
||||||
for: 30s
|
for: 1m
|
||||||
labels:
|
labels:
|
||||||
severity: critical
|
severity: critical
|
||||||
slo: availability
|
slo: availability
|
||||||
annotations:
|
annotations:
|
||||||
summary: "More than 10 total 5xx responses"
|
summary: "API 5xx share > 5% in 2m window"
|
||||||
description: "Total 5xx count: {{ $value }}"
|
description: "5xx share = {{ $value | humanizePercentage }}"
|
||||||
|
# ... остальные alert'ы без изменений
|
||||||
- alert: AttachmentQueueLagHigh
|
|
||||||
expr: attachment_jobs_oldest_age_seconds > 60
|
|
||||||
for: 1m
|
|
||||||
labels:
|
|
||||||
severity: warning
|
|
||||||
slo: freshness
|
|
||||||
annotations:
|
|
||||||
summary: "Oldest unfinished attachment job > 60s"
|
|
||||||
|
|
||||||
- alert: WorkerStalled
|
|
||||||
expr: |
|
|
||||||
attachment_jobs_queue_depth > 0
|
|
||||||
and
|
|
||||||
increase(worker_jobs_processed_total{status="done"}[10m]) == 0
|
|
||||||
for: 5m
|
|
||||||
labels:
|
|
||||||
severity: critical
|
|
||||||
slo: freshness
|
|
||||||
annotations:
|
|
||||||
summary: "Queue non-empty but no jobs completed in 10m"
|
|
||||||
|
|
||||||
- alert: ApiLatencyP95High
|
|
||||||
expr: |
|
|
||||||
histogram_quantile(0.95,
|
|
||||||
sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api"}[5m]))
|
|
||||||
) > 0.5
|
|
||||||
for: 5m
|
|
||||||
labels:
|
|
||||||
severity: warning
|
|
||||||
slo: latency
|
|
||||||
annotations:
|
|
||||||
summary: "API p95 latency > 500ms"
|
|
||||||
@@ -184,6 +184,12 @@ func main() {
|
|||||||
a := &app{pg: pg, s3: s3c, rdb: rdb, c: c, tracer: providers.Tracer, logger: logger}
|
a := &app{pg: pg, s3: s3c, rdb: rdb, c: c, tracer: providers.Tracer, logger: logger}
|
||||||
initMetrics(a, providers)
|
initMetrics(a, providers)
|
||||||
|
|
||||||
|
// нулевые серии с момента старта: дашборд показывает 0, а не No data
|
||||||
|
a.jobsProcessed.Add(context.Background(), 0,
|
||||||
|
metric.WithAttributes(attribute.String("status", "done")))
|
||||||
|
a.jobsProcessed.Add(context.Background(), 0,
|
||||||
|
metric.WithAttributes(attribute.String("status", "failed")))
|
||||||
|
|
||||||
if err := rdb.XGroupCreateMkStream(ctx, c.stream, c.group, "0").Err(); err != nil &&
|
if err := rdb.XGroupCreateMkStream(ctx, c.stream, c.group, "0").Err(); err != nil &&
|
||||||
!strings.Contains(err.Error(), "BUSYGROUP") {
|
!strings.Contains(err.Error(), "BUSYGROUP") {
|
||||||
logger.Error("create group failed", "error", err)
|
logger.Error("create group failed", "error", err)
|
||||||
|
|||||||
Executable
+77
@@ -0,0 +1,77 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -e
|
||||||
|
mkdir -p evidence
|
||||||
|
|
||||||
|
echo "=== Демонстрация: ApiHighErrorRate firing → resolved ==="
|
||||||
|
|
||||||
|
# 1. Базовый трафик (доля 5xx = 0)
|
||||||
|
echo "=== Фаза 1: нормальный трафик (30s) ==="
|
||||||
|
python3 student-tests/generate_metrics.py &
|
||||||
|
BG_PID=$!
|
||||||
|
sleep 30
|
||||||
|
|
||||||
|
# Проверить долю 5xx (должна быть 0%)
|
||||||
|
curl -s 'http://localhost:9090/api/v1/query' \
|
||||||
|
--data-urlencode 'query=(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!="/health/ready"}[2m])) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!="/health/ready"}[2m])), 0.001)) * 100 or vector(0)' \
|
||||||
|
| python3 -c "import sys,json; d=json.load(sys.stdin); [print(f'5xx share: {float(r[\"value\"][1]):.2f}%') for r in d['data']['result']]"
|
||||||
|
|
||||||
|
# 2. PostgreSQL down + бизнес-трафик
|
||||||
|
echo ""
|
||||||
|
echo "=== Фаза 2: PostgreSQL DOWN (90s) ==="
|
||||||
|
docker compose stop postgres
|
||||||
|
|
||||||
|
# Ждать пока alert станет firing
|
||||||
|
FIRED=0
|
||||||
|
for i in $(seq 1 18); do
|
||||||
|
sleep 5
|
||||||
|
STATE=$(curl -s http://localhost:9090/api/v1/alerts | python3 -c "
|
||||||
|
import sys, json
|
||||||
|
d = json.load(sys.stdin)
|
||||||
|
f = [a['labels']['alertname'] for g in d.get('data',{}).get('groups',[])
|
||||||
|
for r in g.get('rules',[]) for a in r.get('alerts',[]) if a['state']=='firing']
|
||||||
|
print(','.join(f) if f else 'NONE')")
|
||||||
|
echo "[down $((i*5))s] alerts: $STATE"
|
||||||
|
if [ "$STATE" != "NONE" ] && [ $FIRED -eq 0 ]; then
|
||||||
|
FIRED=1
|
||||||
|
echo "✓ FIRING detected!"
|
||||||
|
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json
|
||||||
|
curl -s 'http://localhost:9090/api/v1/query' \
|
||||||
|
--data-urlencode 'query=(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!="/health/ready"}[2m])) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!="/health/ready"}[2m])), 0.001)) * 100 or vector(0)' \
|
||||||
|
> evidence/error_rate_at_firing.json
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
# 3. PostgreSQL up + бизнес-трафик
|
||||||
|
echo ""
|
||||||
|
echo "=== Фаза 3: PostgreSQL UP (60s) ==="
|
||||||
|
docker compose start postgres
|
||||||
|
sleep 60
|
||||||
|
|
||||||
|
# Проверить долю 5xx (должна упасть к 0%)
|
||||||
|
curl -s 'http://localhost:9090/api/v1/query' \
|
||||||
|
--data-urlencode 'query=(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!="/health/ready"}[2m])) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!="/health/ready"}[2m])), 0.001)) * 100 or vector(0)' \
|
||||||
|
| python3 -c "import sys,json; d=json.load(sys.stdin); [print(f'5xx share: {float(r[\"value\"][1]):.2f}%') for r in d['data']['result']]"
|
||||||
|
|
||||||
|
# Проверить resolved
|
||||||
|
curl -s http://localhost:9090/api/v1/alerts | python3 -c "
|
||||||
|
import sys, json
|
||||||
|
d = json.load(sys.stdin)
|
||||||
|
for g in d.get('data',{}).get('groups',[]):
|
||||||
|
for r in g.get('rules',[]):
|
||||||
|
if r.get('alerts'):
|
||||||
|
for a in r['alerts']:
|
||||||
|
print(f\"{a['labels']['alertname']}: {a['state']}\")" > evidence/alerts_resolved.txt
|
||||||
|
|
||||||
|
cat evidence/alerts_resolved.txt
|
||||||
|
|
||||||
|
# 4. Завершить генератор
|
||||||
|
kill $BG_PID 2>/dev/null || true
|
||||||
|
|
||||||
|
# 5. Финальная проверка
|
||||||
|
make test
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "=== Доказательства ==="
|
||||||
|
echo "evidence/alerts_firing.json - alert в состоянии firing"
|
||||||
|
echo "evidence/error_rate_at_firing.json - доля 5xx в момент firing"
|
||||||
|
echo "evidence/alerts_resolved.txt - alert в состоянии resolved/inactive"
|
||||||
Executable
+52
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -e
|
||||||
|
mkdir -p evidence
|
||||||
|
|
||||||
|
echo "=== Phase 0: baseline ==="
|
||||||
|
make test
|
||||||
|
|
||||||
|
echo "=== Phase 1: load started (burst + mixed traffic) ==="
|
||||||
|
python3 student-tests/loadgen.py --duration 360 --workers 8 --burst 150 \
|
||||||
|
> evidence/loadgen.log 2>&1 &
|
||||||
|
LOAD_PID=$!
|
||||||
|
|
||||||
|
sleep 45
|
||||||
|
|
||||||
|
echo "=== Phase 2: postgres DOWN ==="
|
||||||
|
docker compose stop postgres
|
||||||
|
|
||||||
|
FIRED=0
|
||||||
|
for i in $(seq 1 24); do
|
||||||
|
sleep 5
|
||||||
|
STATE=$(curl -s http://localhost:9090/api/v1/alerts | python3 -c "
|
||||||
|
import sys, json
|
||||||
|
d = json.load(sys.stdin)
|
||||||
|
f = [a['labels']['alertname'] for g in d.get('data',{}).get('groups',[])
|
||||||
|
for r in g.get('rules',[]) for a in r.get('alerts',[]) if a['state']=='firing']
|
||||||
|
print(','.join(f) if f else 'NONE')")
|
||||||
|
echo "[down $((i*5))s] firing: $STATE"
|
||||||
|
if [ "$STATE" != "NONE" ] && [ $FIRED -eq 0 ]; then
|
||||||
|
FIRED=1
|
||||||
|
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json
|
||||||
|
echo "captured evidence/alerts_firing.json"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
curl -s 'http://localhost:9090/api/v1/query_range' \
|
||||||
|
--data-urlencode 'query=sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m])) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m])),0.001)' \
|
||||||
|
--data-urlencode "start=$(date -u -v-6M +%s)" --data-urlencode "end=$(date -u +%s)" \
|
||||||
|
--data-urlencode 'step=15s' > evidence/error_rate_series.json
|
||||||
|
|
||||||
|
echo "=== Phase 3: recovery ==="
|
||||||
|
docker compose start postgres
|
||||||
|
sleep 60
|
||||||
|
wait $LOAD_PID || true
|
||||||
|
|
||||||
|
echo "=== Load summary ==="
|
||||||
|
tail -5 evidence/loadgen.log
|
||||||
|
|
||||||
|
sleep 60
|
||||||
|
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_resolved.json
|
||||||
|
echo "alerts after recovery saved"
|
||||||
|
|
||||||
|
make test
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Синтетический генератор нагрузки для наполнения дашборда lab6."""
|
||||||
|
import argparse, base64, json, random, threading, time, uuid
|
||||||
|
from collections import Counter
|
||||||
|
import requests
|
||||||
|
|
||||||
|
PNG = base64.b64decode(
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
|
||||||
|
|
||||||
|
LOCK = threading.Lock()
|
||||||
|
CODES = Counter()
|
||||||
|
TOTAL = 0
|
||||||
|
|
||||||
|
def add(code):
|
||||||
|
global TOTAL
|
||||||
|
with LOCK:
|
||||||
|
CODES[code] += 1
|
||||||
|
TOTAL += 1
|
||||||
|
|
||||||
|
def reporter(stop_evt, started):
|
||||||
|
while not stop_evt.is_set():
|
||||||
|
time.sleep(15)
|
||||||
|
with LOCK:
|
||||||
|
total, codes = TOTAL, dict(CODES)
|
||||||
|
dt = time.time() - started
|
||||||
|
rps = total / dt if dt > 0 else 0
|
||||||
|
print(f'[t={dt:6.1f}s] total={total:6d} rps={rps:6.2f} codes={codes}', flush=True)
|
||||||
|
|
||||||
|
def make_user(base, i):
|
||||||
|
uname = f'load{i}{uuid.uuid4().hex[:6]}'
|
||||||
|
r = requests.post(f'{base}/api/v1/users', json={
|
||||||
|
'username': uname, 'display_name': f'Load{i}',
|
||||||
|
'password': 'correcthorsebatterystaple'}, timeout=5)
|
||||||
|
if r.status_code not in (200, 201):
|
||||||
|
return None
|
||||||
|
uid = r.json()['id']
|
||||||
|
r = requests.post(f'{base}/api/v1/auth/sessions',
|
||||||
|
auth=(uname, 'correcthorsebatterystaple'), timeout=5)
|
||||||
|
if r.status_code not in (200, 201):
|
||||||
|
return None
|
||||||
|
token = r.json()['token']
|
||||||
|
r = requests.post(f'{base}/api/v1/chats',
|
||||||
|
json={'title': f'load-chat-{i}', 'member_ids': [uid]},
|
||||||
|
headers={'Authorization': f'Bearer {token}'}, timeout=5)
|
||||||
|
if r.status_code not in (200, 201):
|
||||||
|
return None
|
||||||
|
return token, r.json()['id']
|
||||||
|
|
||||||
|
def burst_uploads(base, ctx_list, n):
|
||||||
|
def one(k):
|
||||||
|
token, chat_id = ctx_list[k % len(ctx_list)]
|
||||||
|
r = requests.post(f'{base}/api/v1/chats/{chat_id}/attachments?filename=b{k}.png',
|
||||||
|
headers={'Authorization': f'Bearer {token}',
|
||||||
|
'Content-Type': 'image/png'},
|
||||||
|
data=PNG, timeout=10)
|
||||||
|
add(r.status_code)
|
||||||
|
threads = [threading.Thread(target=one, args=(k,)) for k in range(n)]
|
||||||
|
for t in threads: t.start()
|
||||||
|
for t in threads: t.join()
|
||||||
|
|
||||||
|
def worker_loop(base, ctx, deadline):
|
||||||
|
token, chat_id = ctx
|
||||||
|
h = {'Authorization': f'Bearer {token}'}
|
||||||
|
while time.time() < deadline:
|
||||||
|
op = random.random()
|
||||||
|
try:
|
||||||
|
if op < 0.4:
|
||||||
|
r = requests.post(f'{base}/api/v1/chats/{chat_id}/messages',
|
||||||
|
json={'text': f'msg {uuid.uuid4().hex[:6]}'},
|
||||||
|
headers={**h, 'Idempotency-Key': str(uuid.uuid4())}, timeout=5)
|
||||||
|
elif op < 0.6:
|
||||||
|
r = requests.post(f'{base}/api/v1/chats/{chat_id}/attachments?filename=l.png',
|
||||||
|
headers={**h, 'Content-Type': 'image/png'}, data=PNG, timeout=5)
|
||||||
|
elif op < 0.8:
|
||||||
|
r = requests.get(f'{base}/api/v1/chats/{chat_id}/messages', headers=h, timeout=5)
|
||||||
|
else:
|
||||||
|
r = requests.get(f'{base}/api/v1/users/me', headers=h, timeout=5)
|
||||||
|
add(r.status_code)
|
||||||
|
except Exception:
|
||||||
|
add(0)
|
||||||
|
time.sleep(random.uniform(0.1, 0.35))
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument('--base-url', default='http://localhost:8080')
|
||||||
|
ap.add_argument('--duration', type=int, default=360)
|
||||||
|
ap.add_argument('--workers', type=int, default=8)
|
||||||
|
ap.add_argument('--burst', type=int, default=150)
|
||||||
|
args = ap.parse_args()
|
||||||
|
base = args.base_url.rstrip('/')
|
||||||
|
|
||||||
|
ctx_list = []
|
||||||
|
for i in range(args.workers):
|
||||||
|
ctx = make_user(base, i)
|
||||||
|
if ctx: ctx_list.append(ctx)
|
||||||
|
print(f'prepared {len(ctx_list)} users/chats', flush=True)
|
||||||
|
if not ctx_list:
|
||||||
|
raise SystemExit('cannot prepare users')
|
||||||
|
|
||||||
|
print(f'burst uploads: {args.burst}', flush=True)
|
||||||
|
burst_uploads(base, ctx_list, args.burst)
|
||||||
|
|
||||||
|
started = time.time()
|
||||||
|
deadline = started + args.duration
|
||||||
|
stop_evt = threading.Event()
|
||||||
|
rep = threading.Thread(target=reporter, args=(stop_evt, started), daemon=True)
|
||||||
|
rep.start()
|
||||||
|
|
||||||
|
threads = [threading.Thread(target=worker_loop, args=(base, c, deadline))
|
||||||
|
for c in ctx_list]
|
||||||
|
for t in threads: t.start()
|
||||||
|
for t in threads: t.join()
|
||||||
|
stop_evt.set()
|
||||||
|
|
||||||
|
with LOCK:
|
||||||
|
total, codes = TOTAL, dict(CODES)
|
||||||
|
err = sum(v for k, v in codes.items() if k >= 500 or k == 0)
|
||||||
|
summary = {'total': total, 'codes': codes,
|
||||||
|
'error_share': err / total if total else 0}
|
||||||
|
print('SUMMARY ' + json.dumps(summary), flush=True)
|
||||||
|
with open('evidence/loadgen_summary.json', 'w') as f:
|
||||||
|
json.dump(summary, f, indent=2)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
Executable
+98
@@ -0,0 +1,98 @@
|
|||||||
|
|
||||||
|
set -e
|
||||||
|
mkdir -p evidence
|
||||||
|
rm -f evidence/error_trace_id.txt
|
||||||
|
|
||||||
|
echo "=== Шаг 1. Pause worker (job не обработается до отказа) ==="
|
||||||
|
docker compose pause worker
|
||||||
|
|
||||||
|
echo "=== Шаг 2. Upload attachment ==="
|
||||||
|
python3 student-tests/trace_error_setup.py
|
||||||
|
ATT_ID=$(cat evidence/attachment_id.txt)
|
||||||
|
|
||||||
|
echo "=== Шаг 3. Остановка S3 ==="
|
||||||
|
docker compose stop s3
|
||||||
|
|
||||||
|
echo "=== Шаг 4. Unpause worker: подхватит job и упадёт на S3 ==="
|
||||||
|
docker compose unpause worker
|
||||||
|
sleep 15
|
||||||
|
|
||||||
|
echo "=== Шаг 5. Логи worker (фильтрация в python) ==="
|
||||||
|
START=$(date -u -v-3M +%s)000000000
|
||||||
|
END=$(date -u +%s)000000000
|
||||||
|
curl -sG 'http://localhost:3100/loki/api/v1/query_range' \
|
||||||
|
--data-urlencode 'query={service_name="messenger-worker"}' \
|
||||||
|
--data-urlencode 'limit=100' \
|
||||||
|
--data-urlencode "start=$START" --data-urlencode "end=$END" \
|
||||||
|
> evidence/loki_worker_logs.json
|
||||||
|
|
||||||
|
python3 - "$ATT_ID" << 'PY'
|
||||||
|
import json, sys
|
||||||
|
att = sys.argv[1]
|
||||||
|
data = json.load(open('evidence/loki_worker_logs.json'))
|
||||||
|
picked = None
|
||||||
|
for stream in data.get('data', {}).get('result', []):
|
||||||
|
for ts, line in stream.get('values', []):
|
||||||
|
try:
|
||||||
|
b = json.loads(line)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
attrs = b.get('attributes', {}) or {}
|
||||||
|
blob = json.dumps(b)
|
||||||
|
lvl = str(attrs.get('level', b.get('severity', ''))).upper()
|
||||||
|
msg = b.get('body', '')
|
||||||
|
related = att in blob
|
||||||
|
is_err = 'ERROR' in lvl or 'fail' in msg.lower() or 'error' in msg.lower()
|
||||||
|
if related or is_err:
|
||||||
|
tid = b.get('traceid') or attrs.get('trace_id', '')
|
||||||
|
print(f"[{lvl or 'INFO'}] {msg[:90]} trace={tid[:32]} related={related}")
|
||||||
|
if tid and picked is None:
|
||||||
|
picked = tid
|
||||||
|
if picked:
|
||||||
|
open('evidence/error_trace_id.txt', 'w').write(picked)
|
||||||
|
print('SAVED trace_id:', picked)
|
||||||
|
else:
|
||||||
|
print('NO trace_id in window')
|
||||||
|
PY
|
||||||
|
|
||||||
|
if [ ! -f evidence/error_trace_id.txt ]; then
|
||||||
|
echo "trace_id не найден; последние логи worker:"
|
||||||
|
docker compose logs worker --tail=30
|
||||||
|
docker compose start s3
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
TRACE_ID=$(cat evidence/error_trace_id.txt)
|
||||||
|
echo "=== Шаг 6. Трейс из Tempo по trace_id из лога ==="
|
||||||
|
curl -s "http://localhost:3200/api/traces/$TRACE_ID" > evidence/trace_with_error.json
|
||||||
|
|
||||||
|
python3 - << 'PY'
|
||||||
|
import json
|
||||||
|
data = json.load(open('evidence/trace_with_error.json'))
|
||||||
|
for batch in data.get('batches', []):
|
||||||
|
svc = next((a['value']['stringValue'] for a in batch['resource']['attributes']
|
||||||
|
if a['key'] == 'service.name'), '?')
|
||||||
|
print(f'\n=== {svc} ===')
|
||||||
|
for scope in batch.get('scopeSpans', []):
|
||||||
|
for span in scope.get('spans', []):
|
||||||
|
kinds = {1:'INTERNAL',2:'SERVER',3:'CLIENT',4:'PRODUCER',5:'CONSUMER'}
|
||||||
|
kind = kinds.get(span.get('kind'), '?')
|
||||||
|
st = span.get('status', {})
|
||||||
|
code = st.get('code', 0)
|
||||||
|
status = 'OK' if code == 1 else ('ERROR' if code == 2 else 'UNSET')
|
||||||
|
attrs = {a['key']: list(a['value'].values())[0] for a in span.get('attributes', [])}
|
||||||
|
err = {k: v for k, v in attrs.items() if 'error' in k.lower() or 'exception' in k.lower()}
|
||||||
|
print(f' {span["name"]:45s} kind={kind:10s} status={status}')
|
||||||
|
if st.get('message'):
|
||||||
|
print(f' status_message: {st["message"]}')
|
||||||
|
if err:
|
||||||
|
print(f' error_attrs: {err}')
|
||||||
|
PY
|
||||||
|
|
||||||
|
echo "=== Шаг 7. Восстановление S3 и retry worker ==="
|
||||||
|
docker compose start s3
|
||||||
|
sleep 20
|
||||||
|
docker compose exec -T postgres sh -c \
|
||||||
|
"psql -U \"\$POSTGRES_USER\" -d \"\$POSTGRES_DB\" -c \"SELECT id,status,error_code FROM attachments WHERE id = '$ATT_ID';\""
|
||||||
|
|
||||||
|
echo "=== Готово: evidence/attachment_id.txt, error_trace_id.txt, trace_with_error.json, loki_worker_logs.json ==="
|
||||||
Executable
+60
@@ -0,0 +1,60 @@
|
|||||||
|
|
||||||
|
import sys
|
||||||
|
import base64
|
||||||
|
import uuid
|
||||||
|
import requests
|
||||||
|
|
||||||
|
BASE = 'http://localhost:8080'
|
||||||
|
PNG = base64.b64decode(
|
||||||
|
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==')
|
||||||
|
|
||||||
|
def fail(msg, r=None):
|
||||||
|
print(f'ERROR: {msg}', file=sys.stderr)
|
||||||
|
if r is not None:
|
||||||
|
print(f' status={r.status_code} body={r.text[:200]}', file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
uname = f'err{uuid.uuid4().hex[:6]}'
|
||||||
|
print(f'username: {uname}')
|
||||||
|
|
||||||
|
r = requests.post(f'{BASE}/api/v1/users', json={
|
||||||
|
'username': uname,
|
||||||
|
'display_name': 'ErrorTest',
|
||||||
|
'password': 'correcthorsebatterystaple',
|
||||||
|
}, timeout=10)
|
||||||
|
if r.status_code not in (200, 201):
|
||||||
|
fail('create user', r)
|
||||||
|
user_id = r.json()['id']
|
||||||
|
print(f'user_id: {user_id}')
|
||||||
|
|
||||||
|
r = requests.post(f'{BASE}/api/v1/auth/sessions',
|
||||||
|
auth=(uname, 'correcthorsebatterystaple'), timeout=10)
|
||||||
|
if r.status_code not in (200, 201):
|
||||||
|
fail('login', r)
|
||||||
|
token = r.json()['token']
|
||||||
|
print(f'token: {token[:20]}...')
|
||||||
|
|
||||||
|
r = requests.post(f'{BASE}/api/v1/chats',
|
||||||
|
json={'title': 'err-test', 'member_ids': [user_id]},
|
||||||
|
headers={'Authorization': f'Bearer {token}',
|
||||||
|
'Content-Type': 'application/json'},
|
||||||
|
timeout=10)
|
||||||
|
if r.status_code not in (200, 201):
|
||||||
|
fail('create chat', r)
|
||||||
|
chat_id = r.json()['id']
|
||||||
|
print(f'chat_id: {chat_id}')
|
||||||
|
|
||||||
|
r = requests.post(
|
||||||
|
f'{BASE}/api/v1/chats/{chat_id}/attachments?filename=err.png',
|
||||||
|
headers={'Authorization': f'Bearer {token}',
|
||||||
|
'Content-Type': 'image/png'},
|
||||||
|
data=PNG, timeout=15)
|
||||||
|
if r.status_code not in (200, 201, 202):
|
||||||
|
fail('upload', r)
|
||||||
|
att = r.json()
|
||||||
|
print(f'attachment_id: {att["id"]}')
|
||||||
|
print(f'status: {att.get("status")}')
|
||||||
|
|
||||||
|
with open('evidence/attachment_id.txt', 'w') as f:
|
||||||
|
f.write(att['id'])
|
||||||
|
print('OK: id saved to evidence/attachment_id.txt')
|
||||||
Reference in New Issue
Block a user