370 lines
12 KiB
Python
370 lines
12 KiB
Python
#!/usr/bin/env python3
|
|
"""Grade-5 SLO experiment: short burst, sustained failure and ready latency."""
|
|
|
|
import concurrent.futures
|
|
import json
|
|
import subprocess
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
import uuid
|
|
|
|
from attachment_memory import cleanup
|
|
from client import Client, Failure
|
|
from observability_alerts import db_error_span
|
|
from observability_grade4 import trace_id_for_request
|
|
|
|
|
|
API_ALERTS = {"MessengerAPIBurnRateFast", "MessengerAPIBurnRateSlow"}
|
|
READY_ALERTS = {
|
|
"MessengerAttachmentReadyBurnRateFast",
|
|
"MessengerAttachmentReadyBurnRateSlow",
|
|
}
|
|
|
|
|
|
def compose(*args, check=True):
|
|
return subprocess.run(
|
|
["docker", "compose", *args],
|
|
check=check,
|
|
text=True,
|
|
capture_output=True,
|
|
)
|
|
|
|
|
|
def start_existing_container(service):
|
|
container_id = compose("ps", "-aq", service).stdout.strip()
|
|
if not container_id:
|
|
raise AssertionError(f"missing container for {service}")
|
|
subprocess.run(
|
|
["docker", "start", container_id],
|
|
check=True,
|
|
text=True,
|
|
capture_output=True,
|
|
)
|
|
|
|
|
|
def json_get(base_url, path, params=None, timeout=10):
|
|
query = "?" + urllib.parse.urlencode(params) if params else ""
|
|
with urllib.request.urlopen(base_url.rstrip("/") + path + query, timeout=timeout) as response:
|
|
return json.load(response)
|
|
|
|
|
|
def wait_for(description, action, timeout, interval=1):
|
|
deadline = time.monotonic() + timeout
|
|
last_error = None
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
value = action()
|
|
if value:
|
|
return value
|
|
except (AssertionError, KeyError, OSError, urllib.error.URLError, ValueError) as error:
|
|
last_error = error
|
|
time.sleep(interval)
|
|
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
|
|
|
|
|
def active_alerts(prometheus_url, names):
|
|
payload = json_get(prometheus_url, "/api/v1/alerts")
|
|
assert payload["status"] == "success", payload
|
|
return {
|
|
item["labels"]["alertname"]: item["state"]
|
|
for item in payload["data"]["alerts"]
|
|
if item.get("labels", {}).get("alertname") in names
|
|
}
|
|
|
|
|
|
def prometheus_scalar(base_url, expression):
|
|
payload = json_get(base_url, "/api/v1/query", {"query": expression})
|
|
assert payload["status"] == "success", payload
|
|
results = payload["data"]["result"]
|
|
return float(results[0]["value"][1]) if results else 0.0
|
|
|
|
|
|
def wait_firing(prometheus_url, names, started, timeout):
|
|
detected = {}
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
states = active_alerts(prometheus_url, names)
|
|
now = time.monotonic()
|
|
for name in names:
|
|
if states.get(name) == "firing" and name not in detected:
|
|
detected[name] = round(now - started, 3)
|
|
if set(detected) == set(names):
|
|
return detected
|
|
time.sleep(1)
|
|
raise AssertionError(f"alerts did not fire: {detected}, current={states}")
|
|
|
|
|
|
def observe_no_alert(prometheus_url, names, duration):
|
|
observed = []
|
|
max_short = 0.0
|
|
max_long = 0.0
|
|
deadline = time.monotonic() + duration
|
|
while time.monotonic() < deadline:
|
|
states = active_alerts(prometheus_url, names)
|
|
if states:
|
|
observed.append(states)
|
|
max_short = max(
|
|
max_short,
|
|
prometheus_scalar(prometheus_url, "messenger:sli_api_error_ratio_30s"),
|
|
)
|
|
max_long = max(
|
|
max_long,
|
|
prometheus_scalar(prometheus_url, "messenger:sli_api_error_ratio_5m"),
|
|
)
|
|
time.sleep(1)
|
|
assert not observed, f"false positive burn-rate alerts: {observed}"
|
|
return {"pending_or_firing": 0, "max_30s_ratio": max_short, "max_5m_ratio": max_long}
|
|
|
|
|
|
def parallel_successes(base_url, actor, count, concurrency=16):
|
|
def request(_):
|
|
local = Client(base_url, timeout=10)
|
|
return local.call("GET", "/api/v1/chats", actor=actor)["status"]
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
|
statuses = list(pool.map(request, range(count)))
|
|
assert set(statuses) == {200}, set(statuses)
|
|
|
|
|
|
def parallel_failures(base_url, actor, count):
|
|
request_ids = [str(uuid.uuid4()) for _ in range(count)]
|
|
|
|
def request(request_id):
|
|
local = Client(base_url, timeout=15)
|
|
local.call(
|
|
"GET",
|
|
"/api/v1/chats",
|
|
503,
|
|
actor=actor,
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
return request_id
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool:
|
|
return list(pool.map(request, request_ids))
|
|
|
|
|
|
def main():
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--base-url", default="http://localhost:8080")
|
|
parser.add_argument("--prometheus-url", default="http://localhost:9090")
|
|
parser.add_argument("--loki-url", default="http://localhost:3100")
|
|
parser.add_argument("--tempo-url", default="http://localhost:3200")
|
|
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
|
parser.add_argument("--timeout", type=int, default=150)
|
|
args = parser.parse_args()
|
|
|
|
dashboard = json_get(
|
|
args.grafana_url, "/api/dashboards/uid/mtusi-lab7-grade5"
|
|
)
|
|
assert dashboard["dashboard"]["title"] == "MTUSI Lab 6 - Grade 5 SLO"
|
|
|
|
client = Client(args.base_url, timeout=20)
|
|
alice, bob, eve, chat = client.bootstrap()
|
|
users = [alice["id"], bob["id"], eve["id"]]
|
|
postgres_paused = False
|
|
worker_stopped = False
|
|
api_result = {}
|
|
ready_result = {}
|
|
try:
|
|
parallel_successes(args.base_url, alice, 400)
|
|
time.sleep(6)
|
|
|
|
compose("pause", "postgres")
|
|
postgres_paused = True
|
|
brief_request_ids = parallel_failures(args.base_url, alice, 4)
|
|
compose("unpause", "postgres")
|
|
postgres_paused = False
|
|
parallel_successes(args.base_url, alice, 100)
|
|
false_positive = observe_no_alert(args.prometheus_url, API_ALERTS, 25)
|
|
|
|
compose("pause", "postgres")
|
|
postgres_paused = True
|
|
incident_started = time.monotonic()
|
|
stop_errors = threading.Event()
|
|
failure_ids = []
|
|
failure_lock = threading.Lock()
|
|
|
|
def error_stream(worker_id):
|
|
local = Client(args.base_url, timeout=15)
|
|
completed = 0
|
|
while not stop_errors.is_set():
|
|
request_id = str(uuid.uuid4())
|
|
try:
|
|
result = local.call(
|
|
"GET",
|
|
"/api/v1/chats",
|
|
[200, 503],
|
|
actor=alice,
|
|
headers={"X-Request-Id": request_id},
|
|
)
|
|
if result["status"] == 503:
|
|
with failure_lock:
|
|
failure_ids.append(request_id)
|
|
completed += 1
|
|
except Failure:
|
|
if not stop_errors.is_set():
|
|
raise
|
|
return completed
|
|
|
|
pool = concurrent.futures.ThreadPoolExecutor(max_workers=8)
|
|
futures = [pool.submit(error_stream, index) for index in range(8)]
|
|
try:
|
|
detection = wait_firing(
|
|
args.prometheus_url, API_ALERTS, incident_started, args.timeout
|
|
)
|
|
finally:
|
|
if postgres_paused:
|
|
compose("unpause", "postgres", check=False)
|
|
postgres_paused = False
|
|
stop_errors.set()
|
|
failure_count = sum(future.result(timeout=30) for future in futures)
|
|
pool.shutdown(wait=True)
|
|
assert failure_ids, "sustained incident produced no 503"
|
|
|
|
recovery_started = time.monotonic()
|
|
parallel_successes(args.base_url, alice, 900)
|
|
wait_for(
|
|
"API burn-rate alerts resolved",
|
|
lambda: not active_alerts(args.prometheus_url, API_ALERTS),
|
|
args.timeout,
|
|
)
|
|
trace_id = wait_for(
|
|
"sustained DB incident log",
|
|
lambda: trace_id_for_request(args.loki_url, failure_ids[0]),
|
|
args.timeout,
|
|
)
|
|
error_span = wait_for(
|
|
"sustained DB incident trace",
|
|
lambda: db_error_span(args.tempo_url, trace_id),
|
|
args.timeout,
|
|
)
|
|
api_result = {
|
|
"brief_spike_failures": len(brief_request_ids),
|
|
"false_positive": false_positive,
|
|
"sustained_failures": failure_count,
|
|
"detection_seconds": detection,
|
|
"recovery_seconds": round(time.monotonic() - recovery_started, 3),
|
|
"trace_id": trace_id,
|
|
"root_cause_span": error_span,
|
|
}
|
|
print(
|
|
json.dumps({"phase": "api_slo", **api_result}, ensure_ascii=False),
|
|
flush=True,
|
|
)
|
|
|
|
wait_for(
|
|
"clean attachment alert state before ready experiment",
|
|
lambda: not active_alerts(args.prometheus_url, READY_ALERTS),
|
|
args.timeout,
|
|
)
|
|
|
|
content = open("tests/fixtures/sample.png", "rb").read()
|
|
|
|
def upload(index, prefix):
|
|
local = Client(args.base_url, timeout=20)
|
|
return local.call(
|
|
"POST",
|
|
f'/api/v1/chats/{chat["id"]}/attachments?filename={prefix}-{index}.png',
|
|
202,
|
|
actor=alice,
|
|
raw=content,
|
|
headers={"Content-Type": "image/png"},
|
|
schema="Attachment",
|
|
)["json"]
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as uploads:
|
|
baseline_attachments = list(
|
|
uploads.map(lambda index: upload(index, "slo-fast"), range(20))
|
|
)
|
|
for attachment in baseline_attachments:
|
|
client.wait_ready(alice, attachment, args.timeout)
|
|
|
|
compose("stop", "worker")
|
|
worker_stopped = True
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as uploads:
|
|
slow_attachments = list(
|
|
uploads.map(lambda index: upload(index, "slo-slow"), range(5))
|
|
)
|
|
time.sleep(12)
|
|
start_existing_container("worker")
|
|
worker_stopped = False
|
|
for attachment in slow_attachments:
|
|
client.wait_ready(alice, attachment, args.timeout)
|
|
ready_incident_started = time.monotonic()
|
|
ready_detection = wait_firing(
|
|
args.prometheus_url, READY_ALERTS, ready_incident_started, args.timeout
|
|
)
|
|
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as uploads:
|
|
recovery_attachments = list(
|
|
uploads.map(lambda index: upload(index, "slo-recovery"), range(100))
|
|
)
|
|
for attachment in recovery_attachments:
|
|
client.wait_ready(alice, attachment, args.timeout)
|
|
ready_recovery_started = time.monotonic()
|
|
wait_for(
|
|
"attachment burn-rate alerts resolved",
|
|
lambda: not active_alerts(args.prometheus_url, READY_ALERTS),
|
|
args.timeout,
|
|
)
|
|
ready_result = {
|
|
"baseline_fast": len(baseline_attachments),
|
|
"slow_over_10s": len(slow_attachments),
|
|
"recovery_fast": len(recovery_attachments),
|
|
"detection_seconds": ready_detection,
|
|
"recovery_seconds": round(
|
|
time.monotonic() - ready_recovery_started, 3
|
|
),
|
|
"final_5m_slow_ratio": prometheus_scalar(
|
|
args.prometheus_url,
|
|
"messenger:sli_attachment_slow_ratio_5m",
|
|
),
|
|
}
|
|
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"status": "PASS",
|
|
"api_slo": api_result,
|
|
"attachment_ready_slo": ready_result,
|
|
"dashboard_uid": "mtusi-lab7-grade5",
|
|
},
|
|
ensure_ascii=False,
|
|
indent=2,
|
|
)
|
|
)
|
|
finally:
|
|
if postgres_paused:
|
|
compose("unpause", "postgres", check=False)
|
|
if worker_stopped:
|
|
try:
|
|
start_existing_container("worker")
|
|
except (AssertionError, subprocess.CalledProcessError):
|
|
compose("up", "-d", "worker", check=False)
|
|
wait_for(
|
|
"PostgreSQL before cleanup",
|
|
lambda: compose(
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"pg_isready",
|
|
"-U",
|
|
"messenger",
|
|
check=False,
|
|
).returncode
|
|
== 0,
|
|
30,
|
|
)
|
|
cleanup(chat["id"], users)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|