Files
mtusi2026lab6/student-tests/five_xx_demo.sh
T

51 lines
2.3 KiB
Bash
Executable File

#!/usr/bin/env bash
set -e
mkdir -p evidence
Q5='sum by (http_route,http_response_status_code) (increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[5m]))'
QS='messenger:http_5xx_share:ratio2m'
share() {
curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$QS" \
| python3 -c "import sys,json; r=json.load(sys.stdin)['data']['result']; print(round(float(r[0]['value'][1])*100,1) if r else -1)"
}
echo "=== baseline: 5xx by route ==="
curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$Q5" | python3 -m json.tool | head -30
echo "=== stop postgres ==="
docker compose stop postgres
python3 - << 'PY' &
import requests, time
for i in range(150):
try:
requests.get('http://localhost:8080/api/v1/users/me', headers={'Authorization':'Bearer invalid'}, timeout=2)
except Exception:
pass
time.sleep(1)
PY
GEN=$!
FIRED=0
for i in $(seq 1 30); 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 a in d['data'].get('alerts',[]) if a['state']=='firing']; print(','.join(f) or 'NONE')")
echo "[down $((i*5))s] 5xx share=$(share)% firing=$STATE"
if [ "$STATE" != "NONE" ] && [ $FIRED -eq 0 ]; then
FIRED=1
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json
curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$Q5" > evidence/five_xx_by_route.json
echo "captured firing + 5xx by route"
fi
done
echo "=== start postgres ==="
docker compose start postgres
wait $GEN || true
for i in $(seq 1 24); do
sleep 5
curl -s -o /dev/null http://localhost:8080/api/v1/users/me -H "Authorization: Bearer invalid"
echo "[up $((i*5))s] 5xx share=$(share)%"
done
curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_resolved.json
curl -s -G http://localhost:9090/api/v1/query_range --data-urlencode "query=$QS" \
--data-urlencode "start=$(date -u -v-8M +%s)" --data-urlencode "end=$(date -u +%s)" \
--data-urlencode 'step=15s' > evidence/five_xx_share_series.json
echo "=== final: 5xx by route ==="
curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$Q5" | python3 -m json.tool | head -30
make test