forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify two bounded failures from saved metrics, logs and traces."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
TRACE_ID = re.compile(r"^[0-9a-f]{32}$")
|
||||
|
||||
|
||||
def json_get(base_url, path, params=None, timeout=5):
|
||||
query = "?" + urllib.parse.urlencode(params) if params else ""
|
||||
request = urllib.request.Request(base_url.rstrip("/") + path + query)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def wait_for(description, action, timeout):
|
||||
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(2)
|
||||
raise AssertionError(f"timeout waiting for {description}: {last_error}")
|
||||
|
||||
|
||||
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 incident_from_loki(base_url, service_name, filter_expression, predicate):
|
||||
now = time.time_ns()
|
||||
payload = json_get(
|
||||
base_url,
|
||||
"/loki/api/v1/query_range",
|
||||
{
|
||||
"query": f'{{service_name="{service_name}"}} | {filter_expression}',
|
||||
"start": str(now - 2 * 60 * 60 * 1_000_000_000),
|
||||
"end": str(now),
|
||||
"direction": "backward",
|
||||
"limit": "1000",
|
||||
},
|
||||
)
|
||||
assert payload["status"] == "success", payload
|
||||
for result in payload["data"]["result"]:
|
||||
attributes = result.get("stream", {})
|
||||
trace_id = attributes.get("trace_id", "")
|
||||
if predicate(attributes) and TRACE_ID.fullmatch(trace_id):
|
||||
return {
|
||||
"event": attributes.get("event"),
|
||||
"route": attributes.get("route"),
|
||||
"status_code": attributes.get("status_code"),
|
||||
"outcome": attributes.get("outcome"),
|
||||
"attempt": attributes.get("attempt"),
|
||||
"trace_id": trace_id,
|
||||
}
|
||||
return None
|
||||
|
||||
|
||||
def trace_exists(base_url, trace_id):
|
||||
payload = json_get(base_url, f"/api/traces/{trace_id}")
|
||||
return bool(payload.get("batches"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
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("--timeout", type=int, default=90)
|
||||
args = parser.parse_args()
|
||||
|
||||
api_errors = wait_for(
|
||||
"API 5xx metric",
|
||||
lambda: prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
'sum(messenger_http_server_requests_total{status_class="5xx"})',
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
worker_failures = wait_for(
|
||||
"failed worker metric",
|
||||
lambda: prometheus_scalar(
|
||||
args.prometheus_url,
|
||||
'sum(messenger_worker_jobs_total{outcome="failed"})',
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
storage_incident = wait_for(
|
||||
"MinIO outage log",
|
||||
lambda: incident_from_loki(
|
||||
args.loki_url,
|
||||
"messenger-api",
|
||||
'status_code="503"',
|
||||
lambda attrs: (
|
||||
attrs.get("status_code") == "503"
|
||||
and attrs.get("route")
|
||||
== "POST /api/v1/chats/{chat_id}/attachments"
|
||||
),
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
worker_incident = wait_for(
|
||||
"failed worker log",
|
||||
lambda: incident_from_loki(
|
||||
args.loki_url,
|
||||
"messenger-worker",
|
||||
'event="attachment_job_failed"',
|
||||
lambda attrs: (
|
||||
attrs.get("event") == "attachment_job_failed"
|
||||
and attrs.get("outcome") == "failed"
|
||||
),
|
||||
),
|
||||
args.timeout,
|
||||
)
|
||||
wait_for(
|
||||
"MinIO outage trace",
|
||||
lambda: trace_exists(args.tempo_url, storage_incident["trace_id"]),
|
||||
args.timeout,
|
||||
)
|
||||
wait_for(
|
||||
"failed worker trace",
|
||||
lambda: trace_exists(args.tempo_url, worker_incident["trace_id"]),
|
||||
args.timeout,
|
||||
)
|
||||
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"status": "PASS",
|
||||
"api_5xx_total": int(api_errors),
|
||||
"worker_failed_total": int(worker_failures),
|
||||
"storage_incident": storage_incident,
|
||||
"worker_incident": worker_incident,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user