Files
mtusi2026lab6/student-tests/capture_firing_alert.sh
T
2026-11-19 18:40:32 +03:00

77 lines
2.2 KiB
Bash
Executable File

#!/usr/bin/env bash
set -e
mkdir -p evidence
echo " Запуск эксперимента с polling alerts "
docker compose stop postgres
sleep 3
python3 student-tests/trigger_error_rate.py &
BG_PID=$!
echo "Polling alerts каждые 3 секунды..."
FIRED=0
for i in $(seq 1 60); do
sleep 3
STATE=$(curl -s http://localhost:9090/api/v1/alerts | python3 -c "
import sys, json
try:
data = json.load(sys.stdin)
firing = []
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
if alert['state'] == 'firing':
firing.append(alert['labels']['alertname'])
if firing:
print('FIRING:' + ','.join(firing))
else:
print('NONE')
except:
print('ERROR')
")
echo "[$((i*3))s] alerts: $STATE"
if [[ "$STATE" == FIRING:* ]]; then
echo ""
echo " ALERT 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(increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m]))' \
> evidence/error_rate_metric.json
FIRED=1
break
fi
done
kill $BG_PID 2>/dev/null || true
docker compose start postgres
sleep 15
if [ $FIRED -eq 1 ]; then
echo ""
echo "FIRING ALERT ЗАФИКСИРОВАН "
echo ""
python3 -c "
import json
with open('evidence/alerts_firing.json') as f:
data = json.load(f)
for group in data.get('data',{}).get('groups',[]):
for rule in group.get('rules',[]):
if rule.get('alerts'):
for alert in rule['alerts']:
if alert['state'] == 'firing':
print(f\"✓ {alert['labels']['alertname']}: FIRING\")
print(f\" Summary: {alert.get('annotations',{}).get('summary','')}\")
print(f\" Active since: {alert.get('activeAt','?')}\")
"
else
echo ""
echo "✗ Alert не сработал за 3 минуты"
fi
make test