Lab 6: span error status, trace-id error correlation, windowed 5xx share alert
This commit is contained in:
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