forked from mtusi2026/mtusi2026lab7
chore: import lab6 baseline
This commit is contained in:
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
env_file=${ENV_FILE:-lab6.env.example}
|
||||
base_url=${BASE_URL:-http://127.0.0.1:8080}
|
||||
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
|
||||
tempo_url=${TEMPO_URL:-http://127.0.0.1:3200}
|
||||
loki_url=${LOKI_URL:-http://127.0.0.1:3100}
|
||||
evidence_root=${EVIDENCE_DIR:-evidence/runtime}
|
||||
outage_seconds=${DB_OUTAGE_SECONDS:-75}
|
||||
require_alerts=${REQUIRE_ALERT_TRANSITIONS:-1}
|
||||
api_alert_name=${API_ALERT_NAME:-MessengerAPIBusiness5xxHigh}
|
||||
burn_alert_name=${API_BURN_ALERT_NAME:-MessengerAPIHighErrorBudgetBurnFast}
|
||||
run_id=$(date -u +%Y%m%dT%H%M%SZ)
|
||||
output_dir="$evidence_root/database-$run_id"
|
||||
mkdir -p "$output_dir"
|
||||
load_pid=
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "$env_file" "$@"
|
||||
}
|
||||
|
||||
restore() {
|
||||
if [ -n "$load_pid" ]; then
|
||||
kill "$load_pid" >/dev/null 2>&1 || true
|
||||
fi
|
||||
compose up -d postgres migrate api nginx >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap restore EXIT INT TERM
|
||||
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase baseline --output "$output_dir/baseline.json" >/dev/null
|
||||
python3 scripts/lab6-traffic.py \
|
||||
--base-url "$base_url" \
|
||||
--mode messages \
|
||||
--duration "$((outage_seconds + 20))" \
|
||||
--concurrency 4 \
|
||||
--rate "${DB_LOAD_RATE:-20}" \
|
||||
--started-file "$output_dir/load-started" \
|
||||
--output "$output_dir/traffic.json" >/dev/null &
|
||||
load_pid=$!
|
||||
remaining=60
|
||||
while [ ! -f "$output_dir/load-started" ] && [ "$remaining" -gt 0 ]; do
|
||||
sleep 0.5
|
||||
remaining=$((remaining - 1))
|
||||
done
|
||||
test -f "$output_dir/load-started"
|
||||
sleep 2
|
||||
started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
compose stop postgres >/dev/null
|
||||
sleep "$outage_seconds"
|
||||
if [ "$require_alerts" = "1" ]; then
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name "$api_alert_name" --state firing --timeout "${ALERT_WAIT_SECONDS:-90}" --output "$output_dir/alert-firing.json" >/dev/null
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name "$burn_alert_name" --state firing --timeout "${ALERT_WAIT_SECONDS:-90}" --output "$output_dir/burn-alert-firing.json" >/dev/null
|
||||
fi
|
||||
python3 scripts/lab6-correlation.py --mode database --tempo-url "$tempo_url" --loki-url "$loki_url" --output "$output_dir/database-correlation.json" --require >/dev/null
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase degraded --output "$output_dir/degraded.json" >/dev/null
|
||||
recovery_started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
compose up -d --wait --wait-timeout 90 postgres migrate api nginx >/dev/null
|
||||
wait "$load_pid" || true
|
||||
load_pid=
|
||||
if [ "$require_alerts" = "1" ]; then
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name "$api_alert_name" --state resolved --timeout "${ALERT_RESOLVE_SECONDS:-180}" --output "$output_dir/alert-resolved.json" >/dev/null
|
||||
fi
|
||||
sleep "${RECOVERY_OBSERVATION_SECONDS:-20}"
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase recovered --output "$output_dir/recovered.json" >/dev/null
|
||||
recovered_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
python3 - "$output_dir/summary.json" "$started_at" "$recovery_started_at" "$recovered_at" "$outage_seconds" <<'PY'
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
output, started, recovery_started, recovered, duration = sys.argv[1:]
|
||||
parse = lambda value: datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"incident": "postgres_unavailable",
|
||||
"started_at": started,
|
||||
"recovery_started_at": recovery_started,
|
||||
"recovered_at": recovered,
|
||||
"planned_injection_seconds": int(duration),
|
||||
"injected_duration_seconds": int((parse(recovery_started) - parse(started)).total_seconds()),
|
||||
"recovery_observation_seconds": int((parse(recovered) - parse(recovery_started)).total_seconds()),
|
||||
"artifacts": ["baseline.json", "degraded.json", "recovered.json", "traffic.json", "database-correlation.json", "alert-firing.json", "alert-resolved.json", "burn-alert-firing.json"],
|
||||
}
|
||||
pathlib.Path(output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
PY
|
||||
trap - EXIT INT TERM
|
||||
printf '%s\n' "$output_dir"
|
||||
Executable
+73
@@ -0,0 +1,73 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
env_file=${ENV_FILE:-lab6.env.example}
|
||||
base_url=${BASE_URL:-http://127.0.0.1:8080}
|
||||
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
|
||||
evidence_root=${EVIDENCE_DIR:-evidence/runtime}
|
||||
outage_seconds=${TELEMETRY_OUTAGE_SECONDS:-30}
|
||||
run_id=$(date -u +%Y%m%dT%H%M%SZ)
|
||||
output_dir="$evidence_root/telemetry-$run_id"
|
||||
mkdir -p "$output_dir"
|
||||
load_pid=
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "$env_file" "$@"
|
||||
}
|
||||
|
||||
restore() {
|
||||
if [ -n "$load_pid" ]; then
|
||||
kill "$load_pid" >/dev/null 2>&1 || true
|
||||
fi
|
||||
compose up -d tempo loki >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap restore EXIT INT TERM
|
||||
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase baseline --output "$output_dir/baseline.json" >/dev/null
|
||||
started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
compose stop tempo loki >/dev/null
|
||||
python3 scripts/lab6-traffic.py \
|
||||
--base-url "$base_url" \
|
||||
--mode mixed \
|
||||
--duration "$outage_seconds" \
|
||||
--concurrency 4 \
|
||||
--rate "${TELEMETRY_LOAD_RATE:-10}" \
|
||||
--wait-ready \
|
||||
--ready-timeout 120 \
|
||||
--output "$output_dir/traffic.json" >/dev/null &
|
||||
load_pid=$!
|
||||
sleep "$outage_seconds"
|
||||
wait "$load_pid"
|
||||
load_pid=
|
||||
health_code=$(curl --silent --output /dev/null --write-out '%{http_code}' "$base_url/health/ready")
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase degraded --output "$output_dir/degraded.json" >/dev/null
|
||||
recovery_started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
compose up -d --wait --wait-timeout 90 tempo loki >/dev/null
|
||||
sleep "${RECOVERY_OBSERVATION_SECONDS:-20}"
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase recovered --output "$output_dir/recovered.json" >/dev/null
|
||||
recovered_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
python3 - "$output_dir/summary.json" "$started_at" "$recovery_started_at" "$recovered_at" "$outage_seconds" "$health_code" <<'PY'
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
output, started, recovery_started, recovered, duration, health_code = sys.argv[1:]
|
||||
parse = lambda value: datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"incident": "telemetry_backends_unavailable",
|
||||
"started_at": started,
|
||||
"recovery_started_at": recovery_started,
|
||||
"recovered_at": recovered,
|
||||
"injected_duration_seconds": int(duration),
|
||||
"api_ready_http_status_during_outage": int(health_code),
|
||||
"recovery_observation_seconds": int((parse(recovered) - parse(recovery_started)).total_seconds()),
|
||||
"artifacts": ["baseline.json", "degraded.json", "recovered.json", "traffic.json"],
|
||||
}
|
||||
pathlib.Path(output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
PY
|
||||
trap - EXIT INT TERM
|
||||
printf '%s\n' "$output_dir"
|
||||
Executable
+107
@@ -0,0 +1,107 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
mode=${1:-short}
|
||||
env_file=${ENV_FILE:-lab6.env.example}
|
||||
base_url=${BASE_URL:-http://127.0.0.1:8080}
|
||||
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
|
||||
evidence_root=${EVIDENCE_DIR:-evidence/runtime}
|
||||
require_alerts=${REQUIRE_ALERT_TRANSITIONS:-1}
|
||||
case "$mode" in
|
||||
short)
|
||||
incident_seconds=${SHORT_WORKER_OUTAGE_SECONDS:-75}
|
||||
load_seconds=${SHORT_WORKER_LOAD_SECONDS:-60}
|
||||
requests=${SHORT_WORKER_REQUESTS:-300}
|
||||
default_alert=AttachmentWorkerUnavailable
|
||||
;;
|
||||
long)
|
||||
incident_seconds=${LONG_WORKER_OUTAGE_SECONDS:-180}
|
||||
load_seconds=${LONG_WORKER_LOAD_SECONDS:-120}
|
||||
requests=${LONG_WORKER_REQUESTS:-1000}
|
||||
default_alert=AttachmentQueueBacklogGrowing
|
||||
;;
|
||||
*)
|
||||
echo "usage: $0 [short|long]" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
worker_alert_name=${WORKER_ALERT_NAME:-$default_alert}
|
||||
|
||||
run_id=$(date -u +%Y%m%dT%H%M%SZ)
|
||||
output_dir="$evidence_root/worker-$mode-$run_id"
|
||||
mkdir -p "$output_dir"
|
||||
load_pid=
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "$env_file" "$@"
|
||||
}
|
||||
|
||||
restore() {
|
||||
if [ -n "$load_pid" ]; then
|
||||
kill "$load_pid" >/dev/null 2>&1 || true
|
||||
fi
|
||||
compose up -d worker >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap restore EXIT INT TERM
|
||||
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase baseline --output "$output_dir/baseline.json" >/dev/null
|
||||
started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
compose stop worker >/dev/null
|
||||
python3 scripts/lab6-traffic.py \
|
||||
--base-url "$base_url" \
|
||||
--mode attachments \
|
||||
--duration "$load_seconds" \
|
||||
--requests "$requests" \
|
||||
--concurrency 4 \
|
||||
--rate "${WORKER_LOAD_RATE:-5}" \
|
||||
--wait-ready \
|
||||
--ready-timeout 480 \
|
||||
--output "$output_dir/traffic.json" >/dev/null &
|
||||
load_pid=$!
|
||||
sleep "$incident_seconds"
|
||||
if [ "$require_alerts" = "1" ]; then
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name "$worker_alert_name" --state firing --timeout "${ALERT_WAIT_SECONDS:-90}" --output "$output_dir/alert-firing.json" >/dev/null
|
||||
fi
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase degraded --output "$output_dir/degraded.json" >/dev/null
|
||||
recovery_started_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
compose up -d --wait --wait-timeout 90 worker >/dev/null
|
||||
wait "$load_pid"
|
||||
load_pid=
|
||||
if [ "$require_alerts" = "1" ]; then
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name "$worker_alert_name" --state resolved --timeout "${ALERT_RESOLVE_SECONDS:-180}" --output "$output_dir/alert-resolved.json" >/dev/null
|
||||
if [ "$mode" = "long" ]; then
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name AttachmentReadyHighErrorBudgetBurnFast --state firing --timeout "${ALERT_WAIT_SECONDS:-90}" --output "$output_dir/burn-fast-firing.json" >/dev/null
|
||||
python3 scripts/lab6-alert.py --prometheus-url "$prometheus_url" --name AttachmentReadyHighErrorBudgetBurnSlow --state firing --timeout "${ALERT_WAIT_SECONDS:-90}" --output "$output_dir/burn-slow-firing.json" >/dev/null
|
||||
fi
|
||||
fi
|
||||
sleep "${RECOVERY_OBSERVATION_SECONDS:-20}"
|
||||
python3 scripts/lab6-observe.py --prometheus-url "$prometheus_url" --phase recovered --output "$output_dir/recovered.json" >/dev/null
|
||||
recovered_at=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
python3 - "$output_dir/summary.json" "$mode" "$started_at" "$recovery_started_at" "$recovered_at" "$incident_seconds" <<'PY'
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
output, mode, started, recovery_started, recovered, duration = sys.argv[1:]
|
||||
parse = lambda value: datetime.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"incident": "worker_unavailable",
|
||||
"profile": mode,
|
||||
"started_at": started,
|
||||
"recovery_started_at": recovery_started,
|
||||
"recovered_at": recovered,
|
||||
"planned_injection_seconds": int(duration),
|
||||
"injected_duration_seconds": int((parse(recovery_started) - parse(started)).total_seconds()),
|
||||
"recovery_observation_seconds": int((parse(recovered) - parse(recovery_started)).total_seconds()),
|
||||
"artifacts": ["baseline.json", "degraded.json", "recovered.json", "traffic.json", "alert-firing.json", "alert-resolved.json"],
|
||||
}
|
||||
if mode == "long":
|
||||
report["artifacts"].extend(["burn-fast-firing.json", "burn-slow-firing.json"])
|
||||
pathlib.Path(output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
PY
|
||||
trap - EXIT INT TERM
|
||||
printf '%s\n' "$output_dir"
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
def fetch(prometheus_url):
|
||||
url = prometheus_url.rstrip("/") + "/api/v1/alerts"
|
||||
with urllib.request.urlopen(url, timeout=10) as response:
|
||||
payload = json.loads(response.read(4 << 20).decode("utf-8"))
|
||||
return payload.get("data", {}).get("alerts", [])
|
||||
|
||||
|
||||
def matching(alerts, name):
|
||||
return [alert for alert in alerts if alert.get("labels", {}).get("alertname") == name]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Wait for a Prometheus alert transition")
|
||||
parser.add_argument("--prometheus-url", default="http://127.0.0.1:9090")
|
||||
parser.add_argument("--name", required=True)
|
||||
parser.add_argument("--state", choices=("firing", "resolved"), required=True)
|
||||
parser.add_argument("--timeout", type=float, default=120)
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
deadline = time.monotonic() + args.timeout
|
||||
last = []
|
||||
error = None
|
||||
observed = False
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
last = matching(fetch(args.prometheus_url), args.name)
|
||||
error = None
|
||||
if args.state == "firing" and any(item.get("state") == "firing" for item in last):
|
||||
observed = True
|
||||
break
|
||||
if args.state == "resolved" and not any(item.get("state") in ("pending", "firing") for item in last):
|
||||
observed = True
|
||||
break
|
||||
except (urllib.error.URLError, json.JSONDecodeError) as current_error:
|
||||
error = str(current_error)
|
||||
time.sleep(2)
|
||||
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"alert": args.name,
|
||||
"expected_state": args.state,
|
||||
"observed": observed,
|
||||
"observed_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"last_states": sorted({item.get("state", "") for item in last}),
|
||||
"error": error,
|
||||
}
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
if not observed:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+148
@@ -0,0 +1,148 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
TRACE_ID = re.compile(r'(?i)\b[0-9a-f]{32}\b')
|
||||
SERVICES = ("messenger-api", "messenger-worker", "messenger-dispatcher")
|
||||
|
||||
|
||||
def get_json(url):
|
||||
with urllib.request.urlopen(url, timeout=10) as response:
|
||||
return json.loads(response.read(8 << 20).decode("utf-8"))
|
||||
|
||||
|
||||
def tempo_query(base_url, query):
|
||||
url = base_url.rstrip("/") + "/api/search?" + urllib.parse.urlencode({"q": query, "limit": 100})
|
||||
payload = get_json(url)
|
||||
return {item.get("traceID") for item in payload.get("traces", []) if item.get("traceID")}
|
||||
|
||||
|
||||
def extract_trace_ids(payload):
|
||||
result = set()
|
||||
for stream in payload.get("data", {}).get("result", []):
|
||||
for value in stream.get("values", []):
|
||||
candidates = [stream.get("stream", {}), value[1] if len(value) > 1 else ""]
|
||||
if len(value) > 2:
|
||||
candidates.append(value[2])
|
||||
for candidate in candidates:
|
||||
if isinstance(candidate, dict):
|
||||
trace_id = candidate.get("trace_id") or candidate.get("traceid")
|
||||
if trace_id:
|
||||
result.add(str(trace_id))
|
||||
candidate = json.dumps(candidate)
|
||||
result.update(match.group(0).lower() for match in TRACE_ID.finditer(str(candidate)))
|
||||
return result
|
||||
|
||||
|
||||
def loki_logs(base_url, service, start_ns):
|
||||
query = '{service_name="' + service + '"}'
|
||||
url = base_url.rstrip("/") + "/loki/api/v1/query_range?" + urllib.parse.urlencode({
|
||||
"query": query,
|
||||
"start": str(start_ns),
|
||||
"limit": 5000,
|
||||
"direction": "backward",
|
||||
})
|
||||
payload = get_json(url)
|
||||
count = sum(len(stream.get("values", [])) for stream in payload.get("data", {}).get("result", []))
|
||||
return count, extract_trace_ids(payload)
|
||||
|
||||
|
||||
def capture(tempo_url, loki_url, lookback_seconds):
|
||||
start_ns = int((time.time() - lookback_seconds) * 1_000_000_000)
|
||||
traces = {service: tempo_query(tempo_url, '{ resource.service.name = "' + service + '" }') for service in SERVICES}
|
||||
logs = {}
|
||||
log_trace_ids = {}
|
||||
for service in SERVICES:
|
||||
count, ids = loki_logs(loki_url, service, start_ns)
|
||||
logs[service] = count
|
||||
log_trace_ids[service] = ids
|
||||
api_worker = traces["messenger-api"] & traces["messenger-worker"]
|
||||
all_trace_ids = set().union(*traces.values())
|
||||
all_log_trace_ids = set().union(*log_trace_ids.values())
|
||||
return {
|
||||
"traces_by_service": {service: len(ids) for service, ids in traces.items()},
|
||||
"logs_by_service": logs,
|
||||
"api_worker_shared_traces": len(api_worker),
|
||||
"traces_with_correlated_logs": len(all_trace_ids & all_log_trace_ids),
|
||||
}
|
||||
|
||||
|
||||
def capture_database(tempo_url, loki_url, lookback_seconds):
|
||||
start_ns = int((time.time() - lookback_seconds) * 1_000_000_000)
|
||||
traces = tempo_query(
|
||||
tempo_url,
|
||||
'{ resource.service.name = "messenger-api" && span.db.system = "postgresql" && status = error }',
|
||||
)
|
||||
log_count, log_trace_ids = loki_logs(loki_url, "messenger-api", start_ns)
|
||||
return {
|
||||
"database_error_traces": len(traces),
|
||||
"api_logs": log_count,
|
||||
"database_error_traces_with_logs": len(traces & log_trace_ids),
|
||||
}
|
||||
|
||||
|
||||
def complete(report):
|
||||
return (
|
||||
report["traces_by_service"]["messenger-api"] > 0
|
||||
and report["traces_by_service"]["messenger-worker"] > 0
|
||||
and report["logs_by_service"]["messenger-api"] > 0
|
||||
and report["logs_by_service"]["messenger-worker"] > 0
|
||||
and report["api_worker_shared_traces"] > 0
|
||||
and report["traces_with_correlated_logs"] > 0
|
||||
)
|
||||
|
||||
|
||||
def database_complete(report):
|
||||
return report["database_error_traces"] > 0 and report["database_error_traces_with_logs"] > 0
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Verify trace and log correlation in Tempo and Loki")
|
||||
parser.add_argument("--tempo-url", default="http://127.0.0.1:3200")
|
||||
parser.add_argument("--loki-url", default="http://127.0.0.1:3100")
|
||||
parser.add_argument("--lookback", type=float, default=900)
|
||||
parser.add_argument("--wait", type=float, default=45)
|
||||
parser.add_argument("--output", required=True)
|
||||
parser.add_argument("--require", action="store_true")
|
||||
parser.add_argument("--mode", choices=("baseline", "database"), default="baseline")
|
||||
args = parser.parse_args()
|
||||
|
||||
deadline = time.monotonic() + args.wait
|
||||
error = None
|
||||
report = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
report = capture_database(args.tempo_url, args.loki_url, args.lookback) if args.mode == "database" else capture(args.tempo_url, args.loki_url, args.lookback)
|
||||
error = None
|
||||
if database_complete(report) if args.mode == "database" else complete(report):
|
||||
break
|
||||
except (urllib.error.URLError, json.JSONDecodeError, KeyError) as current_error:
|
||||
error = str(current_error)
|
||||
time.sleep(2)
|
||||
|
||||
result = {
|
||||
"schema_version": 1,
|
||||
"captured_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"lookback_seconds": args.lookback,
|
||||
"signals": report,
|
||||
"mode": args.mode,
|
||||
"complete": bool(report and (database_complete(report) if args.mode == "database" else complete(report))),
|
||||
"error": error,
|
||||
}
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
if args.require and not result["complete"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
QUERIES = {
|
||||
"api_error_ratio_1m": 'sum(rate(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total{route!~"/health/.*"}[1m])), 1)',
|
||||
"api_request_rate_1m": 'sum(rate(messenger_http_requests_total{route!~"/health/.*"}[1m]))',
|
||||
"queued_jobs": 'sum(messenger_attachment_jobs_count{status="queued"})',
|
||||
"processing_jobs": 'sum(messenger_attachment_jobs_count{status="processing"})',
|
||||
"oldest_queued_job_seconds": 'max(messenger_attachment_jobs_oldest_age_seconds{status="queued"})',
|
||||
"worker_jobs_in_flight": 'sum(messenger_attachment_worker_jobs_in_flight)',
|
||||
"worker_capacity": 'sum(messenger_attachment_worker_capacity)',
|
||||
"pending_outbox": 'sum(messenger_outbox_pending)',
|
||||
"worker_up": 'min(up{job="attachment-worker"})',
|
||||
"collector_export_failures_5m": 'sum(increase(otelcol_exporter_send_failed_spans_total[5m])) + sum(increase(otelcol_exporter_send_failed_log_records_total[5m]))',
|
||||
}
|
||||
|
||||
|
||||
def get_json(url):
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=10) as response:
|
||||
return json.loads(response.read(4 << 20).decode("utf-8")), None
|
||||
except (urllib.error.URLError, json.JSONDecodeError) as error:
|
||||
return None, str(error)
|
||||
|
||||
|
||||
def query(prometheus_url, expression):
|
||||
url = prometheus_url.rstrip("/") + "/api/v1/query?" + urllib.parse.urlencode({"query": expression})
|
||||
payload, error = get_json(url)
|
||||
if error:
|
||||
return {"error": error}
|
||||
if payload.get("status") != "success":
|
||||
return {"error": payload.get("error", "query failed")}
|
||||
rows = payload.get("data", {}).get("result", [])
|
||||
return {
|
||||
"series": [
|
||||
{"labels": row.get("metric", {}), "value": row.get("value", [None, None])[1]}
|
||||
for row in rows
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def alerts(prometheus_url):
|
||||
payload, error = get_json(prometheus_url.rstrip("/") + "/api/v1/alerts")
|
||||
if error:
|
||||
return {"error": error, "items": []}
|
||||
items = []
|
||||
for alert in payload.get("data", {}).get("alerts", []):
|
||||
labels = alert.get("labels", {})
|
||||
items.append({
|
||||
"name": labels.get("alertname", ""),
|
||||
"state": alert.get("state", ""),
|
||||
"severity": labels.get("severity", ""),
|
||||
"active_at": alert.get("activeAt", ""),
|
||||
})
|
||||
return {"items": sorted(items, key=lambda item: (item["name"], item["state"]))}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Capture a bounded Prometheus snapshot for Lab 6 evidence")
|
||||
parser.add_argument("--prometheus-url", default="http://127.0.0.1:9090")
|
||||
parser.add_argument("--phase", required=True)
|
||||
parser.add_argument("--output", required=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"captured_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"phase": args.phase,
|
||||
"queries": {name: query(args.prometheus_url, expression) for name, expression in QUERIES.items()},
|
||||
"alerts": alerts(args.prometheus_url),
|
||||
}
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+261
@@ -0,0 +1,261 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import struct
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import zlib
|
||||
|
||||
MAX_RESPONSE_BYTES = 1 << 20
|
||||
|
||||
|
||||
def png_fixture(width=96, height=64):
|
||||
rows = []
|
||||
for y in range(height):
|
||||
pixels = bytearray()
|
||||
for x in range(width):
|
||||
pixels.extend(((x * 3) % 256, (y * 5) % 256, (x + y) % 256))
|
||||
rows.append(b"\x00" + bytes(pixels))
|
||||
raw = b"".join(rows)
|
||||
|
||||
def chunk(name, payload):
|
||||
return struct.pack(">I", len(payload)) + name + payload + struct.pack(">I", zlib.crc32(name + payload) & 0xFFFFFFFF)
|
||||
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IDAT", zlib.compress(raw, 6)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def request(method, url, body=None, headers=None, timeout=10):
|
||||
req = urllib.request.Request(url, data=body, method=method, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
payload = response.read(MAX_RESPONSE_BYTES)
|
||||
return response.status, payload
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read(MAX_RESPONSE_BYTES)
|
||||
except urllib.error.URLError:
|
||||
return 0, b""
|
||||
|
||||
|
||||
def decode_json(payload):
|
||||
return json.loads(payload.decode("utf-8"))
|
||||
|
||||
|
||||
def json_request(method, url, value=None, token=None, headers=None):
|
||||
request_headers = {"Accept": "application/json"}
|
||||
body = None
|
||||
if value is not None:
|
||||
body = json.dumps(value, separators=(",", ":")).encode("utf-8")
|
||||
request_headers["Content-Type"] = "application/json"
|
||||
if token:
|
||||
request_headers["Authorization"] = "Bearer " + token
|
||||
if headers:
|
||||
request_headers.update(headers)
|
||||
status, payload = request(method, url, body, request_headers)
|
||||
return status, decode_json(payload) if payload else {}
|
||||
|
||||
|
||||
def bootstrap(base_url):
|
||||
suffix = secrets.token_hex(6)
|
||||
password = "Lab6-" + secrets.token_urlsafe(18)
|
||||
users = []
|
||||
for prefix in ("telemetry_a_", "telemetry_b_"):
|
||||
username = prefix + suffix
|
||||
status, user = json_request("POST", base_url + "/api/v1/users", {
|
||||
"username": username,
|
||||
"display_name": "Synthetic telemetry load",
|
||||
"password": password,
|
||||
})
|
||||
if status != 201:
|
||||
raise RuntimeError("register user returned HTTP %d" % status)
|
||||
users.append((username, user["id"]))
|
||||
|
||||
credentials = base64.b64encode((users[0][0] + ":" + password).encode("utf-8")).decode("ascii")
|
||||
status, payload = request("POST", base_url + "/api/v1/auth/sessions", headers={
|
||||
"Authorization": "Basic " + credentials,
|
||||
"Accept": "application/json",
|
||||
})
|
||||
if status != 201:
|
||||
raise RuntimeError("create session returned HTTP %d" % status)
|
||||
token = decode_json(payload)["token"]
|
||||
|
||||
status, chat = json_request("POST", base_url + "/api/v1/chats", {
|
||||
"title": "Lab 6 synthetic telemetry",
|
||||
"member_ids": [users[0][1], users[1][1]],
|
||||
}, token)
|
||||
if status != 201:
|
||||
raise RuntimeError("create chat returned HTTP %d" % status)
|
||||
return token, chat["id"]
|
||||
|
||||
|
||||
class Results:
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.latencies = []
|
||||
self.statuses = {}
|
||||
self.attachment_ids = []
|
||||
|
||||
def record(self, status, elapsed, attachment_id=None):
|
||||
with self.lock:
|
||||
self.latencies.append(elapsed)
|
||||
key = str(status)
|
||||
self.statuses[key] = self.statuses.get(key, 0) + 1
|
||||
if attachment_id:
|
||||
self.attachment_ids.append(attachment_id)
|
||||
|
||||
|
||||
def percentile(values, quantile):
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
index = max(0, math.ceil(quantile * len(ordered)) - 1)
|
||||
return round(ordered[index] * 1000, 3)
|
||||
|
||||
|
||||
def run_request(base_url, token, chat_id, mode, sequence, fixture):
|
||||
if mode == "mixed":
|
||||
mode = "attachments" if sequence % 3 == 0 else "messages"
|
||||
started = time.monotonic()
|
||||
if mode == "messages":
|
||||
status, _ = json_request("POST", base_url + "/api/v1/chats/" + chat_id + "/messages", {
|
||||
"text": "synthetic telemetry event",
|
||||
"attachment_ids": [],
|
||||
}, token, {"Idempotency-Key": secrets.token_hex(16)})
|
||||
return status, time.monotonic() - started, None
|
||||
|
||||
upload_url = base_url + "/api/v1/chats/" + chat_id + "/attachments?" + urllib.parse.urlencode({
|
||||
"filename": "synthetic.png",
|
||||
})
|
||||
status, payload = request("POST", upload_url, fixture, {
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "image/png",
|
||||
"Accept": "application/json",
|
||||
})
|
||||
attachment_id = None
|
||||
if status == 202:
|
||||
attachment_id = decode_json(payload).get("id")
|
||||
return status, time.monotonic() - started, attachment_id
|
||||
|
||||
|
||||
def wait_for_attachments(base_url, token, attachment_ids, timeout):
|
||||
remaining = set(attachment_ids)
|
||||
states = {"ready": 0, "failed": 0, "timeout": 0}
|
||||
deadline = time.monotonic() + timeout
|
||||
while remaining and time.monotonic() < deadline:
|
||||
for attachment_id in list(remaining):
|
||||
status, metadata = json_request("GET", base_url + "/api/v1/attachments/" + attachment_id, token=token)
|
||||
if status != 200:
|
||||
continue
|
||||
state = metadata.get("status")
|
||||
if state in ("ready", "failed"):
|
||||
states[state] += 1
|
||||
remaining.remove(attachment_id)
|
||||
if remaining:
|
||||
time.sleep(0.25)
|
||||
states["timeout"] = len(remaining)
|
||||
return states
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Bounded synthetic load for Lab 6 telemetry and incidents")
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
|
||||
parser.add_argument("--mode", choices=("messages", "attachments", "mixed"), default="mixed")
|
||||
parser.add_argument("--duration", type=float, default=30)
|
||||
parser.add_argument("--requests", type=int, default=0, help="Maximum requests; zero means duration only")
|
||||
parser.add_argument("--concurrency", type=int, default=4)
|
||||
parser.add_argument("--rate", type=float, default=0, help="Approximate aggregate request rate; zero is unthrottled")
|
||||
parser.add_argument("--wait-ready", action="store_true")
|
||||
parser.add_argument("--ready-timeout", type=float, default=120)
|
||||
parser.add_argument("--output")
|
||||
parser.add_argument("--started-file", help="Touch after synthetic session and chat are ready")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.duration <= 0 or args.duration > 1800:
|
||||
parser.error("duration must be in (0, 1800]")
|
||||
if args.requests < 0:
|
||||
parser.error("requests must be non-negative")
|
||||
if args.concurrency < 1 or args.concurrency > 64:
|
||||
parser.error("concurrency must be in [1, 64]")
|
||||
if args.rate < 0 or args.rate > 1000:
|
||||
parser.error("rate must be in [0, 1000]")
|
||||
|
||||
base_url = args.base_url.rstrip("/")
|
||||
token, chat_id = bootstrap(base_url)
|
||||
if args.started_file:
|
||||
started_file = Path(args.started_file)
|
||||
started_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
started_file.touch()
|
||||
fixture = png_fixture()
|
||||
results = Results()
|
||||
next_sequence = 0
|
||||
sequence_lock = threading.Lock()
|
||||
deadline = time.monotonic() + args.duration
|
||||
|
||||
def worker():
|
||||
nonlocal next_sequence
|
||||
while time.monotonic() < deadline:
|
||||
with sequence_lock:
|
||||
if args.requests and next_sequence >= args.requests:
|
||||
return
|
||||
sequence = next_sequence
|
||||
next_sequence += 1
|
||||
status, elapsed, attachment_id = run_request(base_url, token, chat_id, args.mode, sequence, fixture)
|
||||
results.record(status, elapsed, attachment_id)
|
||||
if args.rate:
|
||||
delay = args.concurrency / args.rate - elapsed
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
futures = [pool.submit(worker) for _ in range(args.concurrency)]
|
||||
for future in futures:
|
||||
future.result()
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
attachment_states = None
|
||||
if args.wait_ready and results.attachment_ids:
|
||||
attachment_states = wait_for_attachments(base_url, token, results.attachment_ids, args.ready_timeout)
|
||||
|
||||
total = len(results.latencies)
|
||||
successes = sum(count for status, count in results.statuses.items() if status.startswith("2"))
|
||||
report = {
|
||||
"schema_version": 1,
|
||||
"workload": args.mode,
|
||||
"started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() - elapsed)),
|
||||
"duration_seconds": round(elapsed, 3),
|
||||
"concurrency": args.concurrency,
|
||||
"requested_rate": args.rate or None,
|
||||
"requests": total,
|
||||
"successful_requests": successes,
|
||||
"request_rate": round(total / elapsed, 3) if elapsed else None,
|
||||
"status_counts": dict(sorted(results.statuses.items())),
|
||||
"latency_ms": {
|
||||
"p50": percentile(results.latencies, 0.50),
|
||||
"p95": percentile(results.latencies, 0.95),
|
||||
"p99": percentile(results.latencies, 0.99),
|
||||
},
|
||||
"attachments_accepted": len(results.attachment_ids),
|
||||
"attachment_terminal_states": attachment_states,
|
||||
}
|
||||
encoded = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
|
||||
if args.output:
|
||||
destination = Path(args.output)
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(encoded, encoding="utf-8")
|
||||
print(encoded, end="")
|
||||
if not total:
|
||||
raise SystemExit("no requests were sent")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
docker compose stop nginx api worker dispatcher redis-broker valkey postgres s3
|
||||
docker compose start postgres valkey redis-broker s3
|
||||
docker compose run --rm s3-bootstrap
|
||||
docker compose run --rm migrate
|
||||
docker compose up -d --wait --wait-timeout 90
|
||||
Executable
+223
@@ -0,0 +1,223 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
if [ "$#" -ne 1 ] || [ ! -f "$1" ]; then
|
||||
printf 'usage: %s <image-manifest>\n' "$0" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
manifest=$1
|
||||
deploy_dir=${DEPLOY_STATE_DIR:-"$HOME/.local/state/mtusi2026lab5"}
|
||||
current_manifest=$deploy_dir/current-images.env
|
||||
active_containers=$deploy_dir/active-api-containers
|
||||
previous_containers=$deploy_dir/previous-api-containers
|
||||
upstream_file=$deploy_dir/upstream.conf
|
||||
upstream_backup=$deploy_dir/upstream.previous.conf
|
||||
candidate_file=$deploy_dir/candidate-api-containers
|
||||
replicas=${API_REPLICAS:-2}
|
||||
project=${COMPOSE_PROJECT_NAME:-mtusi2026lab5}
|
||||
switched=false
|
||||
nginx_created=false
|
||||
upstream_changed=false
|
||||
old_pool=""
|
||||
|
||||
mkdir -p "$deploy_dir"
|
||||
: > "$candidate_file"
|
||||
export NGINX_UPSTREAM_FILE=$upstream_file
|
||||
|
||||
load_manifest() {
|
||||
set -a
|
||||
# shellcheck disable=SC1090
|
||||
. "$1"
|
||||
set +a
|
||||
}
|
||||
|
||||
compose() {
|
||||
docker compose -f compose.yaml -f deploy/compose.images.yaml -f deploy/compose.runtime.yaml "$@"
|
||||
}
|
||||
|
||||
container_name() {
|
||||
name=$(docker inspect --format '{{.Name}}' "$1")
|
||||
printf '%s\n' "${name#/}"
|
||||
}
|
||||
|
||||
running_container() {
|
||||
[ "$(docker inspect --format '{{.State.Running}}' "$1" 2>/dev/null || true)" = true ]
|
||||
}
|
||||
|
||||
write_upstream() {
|
||||
output=$1
|
||||
containers=$2
|
||||
: > "$output"
|
||||
for container in $containers; do
|
||||
name=$(container_name "$container")
|
||||
printf 'server %s:8080 resolve max_fails=1 fail_timeout=3s;\n' "$name" >> "$output"
|
||||
done
|
||||
}
|
||||
|
||||
wait_for_containers() {
|
||||
containers=$1
|
||||
deadline=$(($(date +%s) + 120))
|
||||
|
||||
while [ "$(date +%s)" -lt "$deadline" ]; do
|
||||
count=0
|
||||
healthy=0
|
||||
for container in $containers; do
|
||||
count=$((count + 1))
|
||||
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container")
|
||||
if [ "$status" = healthy ]; then
|
||||
healthy=$((healthy + 1))
|
||||
fi
|
||||
done
|
||||
if [ "$count" -eq "$replicas" ] && [ "$healthy" -eq "$replicas" ]; then
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'candidate API pool did not become healthy: expected %s\n' "$replicas" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
smoke_check() {
|
||||
compose exec -T nginx wget -q -O /dev/null http://127.0.0.1:8080/health/ready
|
||||
}
|
||||
|
||||
remove_containers() {
|
||||
containers=$1
|
||||
for container in $containers; do
|
||||
docker rm -f "$container" >/dev/null 2>&1 || true
|
||||
done
|
||||
}
|
||||
|
||||
restore_upstream() {
|
||||
if [ -s "$upstream_backup" ]; then
|
||||
cp "$upstream_backup" "$upstream_file"
|
||||
compose exec -T nginx nginx -t
|
||||
compose exec -T nginx nginx -s reload
|
||||
fi
|
||||
}
|
||||
|
||||
rollback() {
|
||||
status=$?
|
||||
trap - EXIT INT TERM
|
||||
candidates=$(cat "$candidate_file" 2>/dev/null || true)
|
||||
|
||||
if [ "$upstream_changed" = true ] && [ -n "$old_pool" ]; then
|
||||
printf '%s\n' 'Deployment failed; switching Nginx back to the previous API pool.' >&2
|
||||
restore_upstream || true
|
||||
if [ "$switched" = true ]; then
|
||||
smoke_check || true
|
||||
fi
|
||||
elif [ "$nginx_created" = true ]; then
|
||||
compose stop nginx >/dev/null 2>&1 || true
|
||||
fi
|
||||
remove_containers "$candidates"
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap rollback EXIT
|
||||
trap 'exit 130' INT
|
||||
trap 'exit 143' TERM
|
||||
|
||||
load_manifest "$manifest"
|
||||
new_api_image=$API_IMAGE
|
||||
|
||||
if [ -f "$previous_containers" ]; then
|
||||
remove_containers "$(cat "$previous_containers")"
|
||||
rm -f "$previous_containers"
|
||||
fi
|
||||
|
||||
if [ -s "$active_containers" ]; then
|
||||
for container in $(cat "$active_containers"); do
|
||||
if running_container "$container"; then
|
||||
old_pool="$old_pool $container"
|
||||
fi
|
||||
done
|
||||
fi
|
||||
if [ -z "$old_pool" ]; then
|
||||
old_pool=$(compose ps -q api)
|
||||
fi
|
||||
|
||||
if [ -s "$upstream_file" ]; then
|
||||
:
|
||||
elif [ -n "$old_pool" ]; then
|
||||
write_upstream "$upstream_file" "$old_pool"
|
||||
else
|
||||
cp nginx/upstream.conf "$upstream_file"
|
||||
fi
|
||||
cp "$upstream_file" "$upstream_backup"
|
||||
|
||||
compose pull api nginx swagger prometheus grafana s3 s3-bootstrap
|
||||
compose up -d --no-build --wait --wait-timeout 120 postgres valkey redis-broker s3
|
||||
compose run --rm --no-deps s3-bootstrap
|
||||
compose run --rm --no-deps migrate
|
||||
|
||||
nginx_container=$(compose ps -q nginx)
|
||||
if [ -n "$nginx_container" ] && ! docker inspect --format '{{range .Mounts}}{{println .Destination}}{{end}}' "$nginx_container" | grep -qx /etc/nginx/conf.d/upstream.conf; then
|
||||
compose up -d --no-build --no-deps --force-recreate nginx
|
||||
nginx_container=$(compose ps -q nginx)
|
||||
fi
|
||||
if [ -n "$nginx_container" ]; then
|
||||
running_nginx_image=$(docker inspect --format '{{.Config.Image}}' "$nginx_container")
|
||||
if [ "$running_nginx_image" != "$NGINX_IMAGE" ]; then
|
||||
printf 'verified Nginx image differs from the running load balancer; deploy it in a dedicated maintenance operation\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
API_IMAGE=$new_api_image
|
||||
export API_IMAGE
|
||||
short_digest=$(printf '%s' "$new_api_image" | sed 's/.*sha256://; s/[^0-9a-f].*//' | cut -c1-12)
|
||||
if [ -z "$short_digest" ]; then
|
||||
short_digest=$(date +%s)
|
||||
fi
|
||||
generation=${DEPLOY_GENERATION:-"$(date +%s)-$$"}
|
||||
|
||||
candidate_pool=""
|
||||
index=1
|
||||
while [ "$index" -le "$replicas" ]; do
|
||||
name="${project}-api-${short_digest}-${generation}-${index}"
|
||||
container=$(compose run -d --no-deps --name "$name" api)
|
||||
candidate_pool="$candidate_pool $container"
|
||||
printf '%s\n' "$container" >> "$candidate_file"
|
||||
index=$((index + 1))
|
||||
done
|
||||
wait_for_containers "$candidate_pool"
|
||||
|
||||
write_upstream "$upstream_file.next" "$candidate_pool"
|
||||
cp "$upstream_file.next" "$upstream_file"
|
||||
upstream_changed=true
|
||||
|
||||
if [ -n "$(compose ps -q nginx)" ]; then
|
||||
compose exec -T nginx nginx -t
|
||||
switched=true
|
||||
compose exec -T nginx nginx -s reload
|
||||
else
|
||||
nginx_created=true
|
||||
compose up -d --no-build --no-deps nginx
|
||||
switched=true
|
||||
fi
|
||||
smoke_check
|
||||
|
||||
application_network="${project}_application"
|
||||
for container in $candidate_pool; do
|
||||
docker network disconnect "$application_network" "$container"
|
||||
docker network connect --alias api "$application_network" "$container"
|
||||
done
|
||||
smoke_check
|
||||
|
||||
compose up -d --no-build --no-deps dispatcher worker swagger postgres-exporter valkey-exporter redis-broker-exporter nginx-exporter prometheus grafana
|
||||
|
||||
printf '%s\n' "$candidate_pool" > "$active_containers"
|
||||
cp "$manifest" "$current_manifest"
|
||||
rm -f "$candidate_file" "$upstream_file.next"
|
||||
trap - EXIT INT TERM
|
||||
|
||||
if [ -n "$old_pool" ]; then
|
||||
for container in $old_pool; do
|
||||
docker stop --time 6 "$container" >/dev/null || true
|
||||
done
|
||||
printf '%s\n' "$old_pool" > "$previous_containers"
|
||||
fi
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
|
||||
for container in $(docker compose ps -q api); do
|
||||
instance=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop --time 6 "$container" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
printf '%s\n' "API instance not found: $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
state_file=$(mktemp)
|
||||
|
||||
restore_pipeline() {
|
||||
rm -f "$state_file"
|
||||
docker compose up -d dispatcher worker >/dev/null
|
||||
}
|
||||
|
||||
trap restore_pipeline EXIT INT TERM
|
||||
|
||||
docker compose stop worker dispatcher >/dev/null
|
||||
docker compose --profile experiments run --rm lab5-experiment /app/lab5experiment api-produce > "$state_file"
|
||||
docker compose restart api redis-broker >/dev/null
|
||||
docker compose up -d --wait --wait-timeout 90 api nginx redis-broker dispatcher worker >/dev/null
|
||||
docker compose --profile experiments run --rm --no-deps -T lab5-experiment /app/lab5experiment api-verify < "$state_file"
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
restore_pipeline() {
|
||||
docker compose up -d dispatcher worker >/dev/null
|
||||
}
|
||||
|
||||
trap restore_pipeline EXIT INT TERM
|
||||
docker compose stop worker dispatcher >/dev/null
|
||||
docker compose --profile experiments run --rm lab5-experiment
|
||||
Executable
+73
@@ -0,0 +1,73 @@
|
||||
#!/bin/sh
|
||||
|
||||
set -eu
|
||||
|
||||
profile=${1:-full}
|
||||
case "$profile" in
|
||||
smoke|full) ;;
|
||||
*)
|
||||
echo "usage: $0 [smoke|full]" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
env_file=${ENV_FILE:-lab6.env.example}
|
||||
base_url=${BASE_URL:-http://127.0.0.1:8080}
|
||||
prometheus_url=${PROMETHEUS_URL:-http://127.0.0.1:9090}
|
||||
tempo_url=${TEMPO_URL:-http://127.0.0.1:3200}
|
||||
loki_url=${LOKI_URL:-http://127.0.0.1:3100}
|
||||
run_id=$(date -u +%Y%m%dT%H%M%SZ)
|
||||
output_dir=${EVIDENCE_DIR:-evidence/runtime/lab6-$run_id}
|
||||
mkdir -p "$output_dir"
|
||||
|
||||
compose() {
|
||||
docker compose --env-file "$env_file" "$@"
|
||||
}
|
||||
|
||||
restore() {
|
||||
compose up -d postgres redis-broker s3 valkey api nginx dispatcher worker otel-collector prometheus loki tempo grafana >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap restore EXIT INT TERM
|
||||
|
||||
test -f "$env_file"
|
||||
compose config --quiet
|
||||
compose up -d --build --wait --wait-timeout 180
|
||||
python3 scripts/lab6-traffic.py \
|
||||
--base-url "$base_url" \
|
||||
--mode mixed \
|
||||
--duration "${BASELINE_LOAD_SECONDS:-15}" \
|
||||
--requests "${BASELINE_REQUESTS:-120}" \
|
||||
--concurrency 4 \
|
||||
--rate "${BASELINE_LOAD_RATE:-10}" \
|
||||
--wait-ready \
|
||||
--ready-timeout 120 \
|
||||
--output "$output_dir/baseline-traffic.json" >/dev/null
|
||||
python3 scripts/lab6-observe.py \
|
||||
--prometheus-url "$prometheus_url" \
|
||||
--phase baseline \
|
||||
--output "$output_dir/baseline-observability.json" >/dev/null
|
||||
python3 scripts/lab6-correlation.py \
|
||||
--tempo-url "$tempo_url" \
|
||||
--loki-url "$loki_url" \
|
||||
--output "$output_dir/baseline-correlation.json" \
|
||||
--require >/dev/null
|
||||
|
||||
if [ "$profile" = "full" ]; then
|
||||
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" TEMPO_URL="$tempo_url" LOKI_URL="$loki_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-database.sh
|
||||
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-worker.sh long
|
||||
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-worker.sh short
|
||||
ENV_FILE="$env_file" BASE_URL="$base_url" PROMETHEUS_URL="$prometheus_url" EVIDENCE_DIR="$output_dir/incidents" scripts/incident-telemetry.sh
|
||||
fi
|
||||
|
||||
arguments=
|
||||
if [ "$profile" = "full" ]; then
|
||||
arguments="--require-incidents"
|
||||
if [ "${REQUIRE_ALERT_TRANSITIONS:-1}" = "1" ]; then
|
||||
arguments="$arguments --require-alerts"
|
||||
fi
|
||||
fi
|
||||
# shellcheck disable=SC2086
|
||||
python3 scripts/validate-lab6-evidence.py "$output_dir" $arguments
|
||||
trap - EXIT INT TERM
|
||||
printf '%s\n' "$output_dir"
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def load(path):
|
||||
return json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def check(condition, message, errors):
|
||||
if not condition:
|
||||
errors.append(message)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Validate generated Lab 6 incident evidence")
|
||||
parser.add_argument("directory")
|
||||
parser.add_argument("--require-incidents", action="store_true")
|
||||
parser.add_argument("--require-alerts", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
root = Path(args.directory)
|
||||
errors = []
|
||||
baseline = root / "baseline-traffic.json"
|
||||
check(baseline.exists(), "baseline-traffic.json is missing", errors)
|
||||
if baseline.exists():
|
||||
report = load(baseline)
|
||||
check(report.get("requests", 0) > 0, "baseline sent no requests", errors)
|
||||
check(report.get("successful_requests", 0) > 0, "baseline had no successful requests", errors)
|
||||
|
||||
correlation = root / "baseline-correlation.json"
|
||||
check(correlation.exists(), "baseline-correlation.json is missing", errors)
|
||||
if correlation.exists():
|
||||
check(load(correlation).get("complete") is True, "metrics/log/trace correlation is incomplete", errors)
|
||||
|
||||
observability = root / "baseline-observability.json"
|
||||
check(observability.exists(), "baseline-observability.json is missing", errors)
|
||||
if observability.exists():
|
||||
firing = [item.get("name") for item in load(observability).get("alerts", {}).get("items", []) if item.get("state") == "firing"]
|
||||
check(not firing, "baseline has firing alerts: " + ", ".join(firing), errors)
|
||||
|
||||
summaries = list(root.rglob("summary.json"))
|
||||
if args.require_incidents:
|
||||
names = {load(path).get("incident") for path in summaries}
|
||||
for required in ("worker_unavailable", "postgres_unavailable", "telemetry_backends_unavailable"):
|
||||
check(required in names, "incident evidence is missing: " + required, errors)
|
||||
|
||||
for summary_path in summaries:
|
||||
summary = load(summary_path)
|
||||
incident = summary.get("incident")
|
||||
traffic_path = summary_path.parent / "traffic.json"
|
||||
check(traffic_path.exists(), str(traffic_path) + " is missing", errors)
|
||||
if not traffic_path.exists():
|
||||
continue
|
||||
traffic = load(traffic_path)
|
||||
check(traffic.get("requests", 0) > 0, incident + " sent no traffic", errors)
|
||||
if incident == "worker_unavailable":
|
||||
terminal = traffic.get("attachment_terminal_states") or {}
|
||||
check(traffic.get("attachments_accepted", 0) > 0, incident + " accepted no attachments", errors)
|
||||
check(terminal.get("ready", 0) == traffic.get("attachments_accepted", -1), incident + " did not drain every accepted attachment", errors)
|
||||
check(terminal.get("failed", 0) == 0, incident + " produced failed attachments", errors)
|
||||
check(terminal.get("timeout", 0) == 0, incident + " left attachment jobs non-terminal", errors)
|
||||
elif incident == "postgres_unavailable":
|
||||
statuses = traffic.get("status_counts", {})
|
||||
failures = sum(count for status, count in statuses.items() if not status.startswith("2"))
|
||||
check(failures > 0, incident + " produced no observable failed requests", errors)
|
||||
correlation_path = summary_path.parent / "database-correlation.json"
|
||||
check(correlation_path.exists(), str(correlation_path) + " is missing", errors)
|
||||
if correlation_path.exists():
|
||||
check(load(correlation_path).get("complete") is True, "database error trace/log correlation is incomplete", errors)
|
||||
elif incident == "telemetry_backends_unavailable":
|
||||
terminal = traffic.get("attachment_terminal_states") or {}
|
||||
check(traffic.get("successful_requests", 0) > 0, incident + " had no successful business requests", errors)
|
||||
check(traffic.get("attachments_accepted", 0) > 0, incident + " accepted no attachments", errors)
|
||||
check(terminal.get("ready", 0) == traffic.get("attachments_accepted", -1), incident + " did not finish every attachment", errors)
|
||||
check(terminal.get("failed", 0) == 0 and terminal.get("timeout", 0) == 0, incident + " left unsuccessful attachments", errors)
|
||||
check(summary.get("api_ready_http_status_during_outage") == 200, incident + " broke API readiness", errors)
|
||||
|
||||
if args.require_alerts and incident in ("worker_unavailable", "postgres_unavailable"):
|
||||
for name in ("alert-firing.json", "alert-resolved.json"):
|
||||
path = summary_path.parent / name
|
||||
check(path.exists(), str(path) + " is missing", errors)
|
||||
if path.exists():
|
||||
check(load(path).get("observed") is True, str(path) + " did not observe the transition", errors)
|
||||
if incident == "worker_unavailable" and summary.get("profile") == "long":
|
||||
for name in ("burn-fast-firing.json", "burn-slow-firing.json"):
|
||||
path = summary_path.parent / name
|
||||
check(path.exists(), str(path) + " is missing", errors)
|
||||
if path.exists():
|
||||
check(load(path).get("observed") is True, str(path) + " did not observe attachment burn", errors)
|
||||
|
||||
result = {"valid": not errors, "errors": errors, "incident_summaries": len(summaries)}
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
if errors:
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user