Files
mtusi2026lab6/student-tests/observability.py
T
2026-12-03 20:20:07 +03:00

175 lines
7.7 KiB
Python

"""Verify the provisioned Grafana data sources on the dedicated local Lab 6 stack."""
import argparse
from base64 import b64encode
import json
import os
from pathlib import Path
import time
from urllib.parse import urlencode
from urllib.request import ProxyHandler, build_opener
from uuid import uuid4
from queue_recovery import Client, check, check_retry_limit, compose, wait_for
HTTP = build_opener(ProxyHandler({}))
class Grafana:
def __init__(self, base):
self.base = base.rstrip("/")
def get(self, path, **params):
query = "?" + urlencode(params) if params else ""
try:
with HTTP.open(self.base + path + query, timeout=5) as response:
return json.load(response)
except (OSError, ValueError):
return None
def source(self, name, path, **params):
return self.get(f"/api/datasources/proxy/uid/lab-{name}{path}", **params)
def logs(self, service, **fields):
query = f'{{service_name="{service}"}} | json'
for key, value in fields.items():
query += f" | {key} = {json.dumps(value)}"
result = self.source("loki", "/loki/api/v1/query_range", query=query,
start=str(time.time_ns() - 15 * 60 * 10**9), limit=50)
entries = []
for stream in (result or {}).get("data", {}).get("result", []):
for record in stream["values"]:
entries.append(json.loads(record[1]))
return entries
def metric(self, expression):
result = self.source("prometheus", "/api/v1/query", query=expression)
samples = (result or {}).get("data", {}).get("result", [])
return float(samples[0]["value"][1]) if samples else None
def spans(value):
if isinstance(value, dict):
if "spanId" in value and "name" in value:
yield value
else:
for child in value.values():
yield from spans(child)
if isinstance(value, list):
for child in value:
yield from spans(child)
def correlated(grafana, service, span_name, **fields):
entries = wait_for(lambda: grafana.logs(service, **fields), f"Missing log for {service}: {fields}")
entry = entries[0]
trace_id, span_id = entry["trace_id"], entry["span_id"]
check(len(trace_id) == 32 and len(span_id) == 16, "Malformed trace identifiers")
trace = wait_for(lambda: grafana.source("tempo", "/api/traces/" + trace_id),
f"Trace missing in Tempo: {trace_id}")
span = next((span for span in spans(trace) if span["name"] == span_name), None)
check(span is not None, f"Span missing in Tempo: {span_name}")
for field, identifier in (("spanId", span_id), ("traceId", trace_id)):
encoded = b64encode(bytes.fromhex(identifier)).decode("ascii")
check(span[field] in (identifier, encoded), f"Log and trace {field} differ")
expected_kind = 2 if service == "messenger-api" else 5
expected_name = "SPAN_KIND_SERVER" if expected_kind == 2 else "SPAN_KIND_CONSUMER"
check(span["kind"] in (expected_kind, expected_name), "Unexpected span kind")
attributes = {item["key"]: next(iter(item["value"].values())) for item in span.get("attributes", [])}
return {"log": entry, "trace": {"name": span_name, "kind": span["kind"], "attributes": attributes,
"events": [event["name"] for event in span.get("events", [])]}}
def postgres_incident():
code = """
import json
from urllib.error import HTTPError
from urllib.request import urlopen
try:
urlopen('http://127.0.0.1:8080/health/ready', timeout=12)
except HTTPError as error:
print(json.dumps({'status': error.code, 'request_id': error.headers.get('X-Request-Id')}))
"""
try:
compose("stop", "db")
observed = json.loads(compose("exec", "-T", "api1", "python", "-c", code))
check(observed["status"] == 503 and observed["request_id"], "Database outage did not yield API 503")
return observed
finally:
compose("start", "db")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
parser.add_argument("--grafana-url", default="http://127.0.0.1:13006")
parser.add_argument("--output", type=Path)
args = parser.parse_args()
grafana = Grafana(args.grafana_url)
dashboard = wait_for(lambda: grafana.get("/api/dashboards/uid/lab-messenger"),
"Grafana dashboard was not provisioned")
client = Client(args.base_url)
alice, bob, _, chat = client.bootstrap()
marker = "lab6_content_" + uuid4().hex
message = client.message(alice, chat, marker)
request_id = message["headers"]["X-Request-Id"]
request = correlated(grafana, "messenger-api", "POST /api/v1/chats/{chat_id}/messages",
request_id=request_id)
attachment, _ = client.attachment(alice, chat)
client.wait_ready(bob, attachment)
delivery = correlated(grafana, "messenger-worker", "attachment.process.v1 process",
attachment_id=attachment["id"], outcome="ready")
database = postgres_incident()
wait_for(lambda: client.call("GET", "/health/ready", schema="Health"), "API did not recover")
outage = correlated(grafana, "messenger-api", "GET /health/ready", request_id=database["request_id"])
check("postgresql.unavailable" in outage["trace"]["events"], "Trace does not diagnose the PostgreSQL outage")
try:
staging = check_retry_limit(client, alice, bob, chat)
failed = correlated(grafana, "messenger-worker", "attachment.process.v1 process",
attachment_id=staging["attachment_id"], outcome="failed")
check(failed["trace"]["attributes"]["job.reason"] == "staging_unavailable",
"Worker trace does not diagnose the staging failure")
finally:
compose("start", "worker")
try:
compose("stop", "tempo")
during_tempo_stop = client.message(alice, chat, "Проверка работы при остановленном Tempo")
check(during_tempo_stop["status"] == 201, "Tempo outage stopped business requests")
finally:
compose("start", "tempo")
metrics = {}
expressions = (
"sum(messenger_http_requests_total)",
'sum(messenger_http_requests_total{http_status_class="5xx"})',
"sum(messenger_http_duration_seconds_count)",
'sum(messenger_job_deliveries_total{job_outcome="ready"})',
'sum(messenger_job_deliveries_total{job_outcome="failed"})',
"sum(messenger_job_duration_seconds_count)",
)
for expression in expressions:
metrics[expression] = wait_for(lambda: grafana.metric(expression), f"Missing metric: {expression}")
check(marker not in json.dumps(grafana.logs("messenger-api", request_id=request_id)),
"Message content leaked into the API log")
check(marker not in json.dumps(request["trace"]), "Message content leaked into the API trace")
report = {
"dashboard": dashboard["dashboard"]["uid"], "metrics": metrics,
"api_correlation": request, "worker_correlation": delivery,
"postgresql_incident": outage, "staging_incident": failed, "staging_attempts": staging["attempts"],
"message_status_with_tempo_stopped": during_tempo_stop["status"], "message_marker_absent": True,
}
rendered = json.dumps(report, ensure_ascii=False, indent=2)
if args.output:
args.output.write_text(rendered + "\n", encoding="utf-8")
print("PASS: metrics, structured logs and correlated traces for API and worker, plus two incidents.")
if __name__ == "__main__":
for variable in ("NO_PROXY", "no_proxy"):
os.environ[variable] = ",".join(filter(None, (os.environ.get(variable), "127.0.0.1", "localhost")))
main()