#!/usr/bin/env python3 """Observability acceptance checks for lab6. Proves, from the saved telemetry only: 1. metrics exist in Prometheus (HTTP, jobs, queue, DB pool, worker); 2. a controlled upload yields a structured API log in Loki whose trace_id is found in Tempo with BOTH messenger-api and messenger-worker spans (cross-process trace through the broker); 3. alert rules are loaded and can FIRE and RESOLVE for two incidents: worker stopped (queue age) and PostgreSQL down (5xx error ratio); 4. stopping a telemetry backend (Loki) does not break the API. Run from the repository root; needs docker CLI + running lab6 stand. """ from __future__ import annotations import argparse import base64 import json import os import struct import subprocess import sys import time import urllib.error import urllib.parse import urllib.request import uuid import zlib BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/") PROM = os.environ.get("PROM_URL", "http://localhost:9090").rstrip("/") LOKI = os.environ.get("LOKI_URL", "http://localhost:3100").rstrip("/") TEMPO = os.environ.get("TEMPO_URL", "http://localhost:3200").rstrip("/") def _chunk(tag, data): return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF) def make_png(width=320, height=200): raw = bytearray() pixels = os.urandom(width * height * 3) stride = width * 3 for row in range(height): raw.append(0) raw += pixels[row * stride : (row + 1) * stride] ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _chunk(b"IEND", b"") def request(method, url, token=None, body=None, raw=None, content_type=None, timeout=20): headers = {"Accept": "application/json"} data = raw if body is not None: data = json.dumps(body).encode() headers["Content-Type"] = "application/json" if content_type: headers["Content-Type"] = content_type if token: headers["Authorization"] = "Bearer " + token req = urllib.request.Request(url, data=data, headers=headers, method=method) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.status, resp.headers, resp.read() except urllib.error.HTTPError as error: return error.code, error.headers, error.read() def get_json(url): status, _headers, body = request("GET", url) if status != 200: return None return json.loads(body) def prom_query(expr): data = get_json(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr})) if not data or data.get("status") != "success": return [] return data["data"]["result"] def active_alerts(): data = get_json(PROM + "/api/v1/alerts") if not data: return {} result = {} for alert in data["data"]["alerts"]: result[alert["labels"].get("alertname")] = alert["state"] return result def login_upload(): username = "tel_" + uuid.uuid4().hex[:8] password = "T3st-" + uuid.uuid4().hex request("POST", BASE + "/api/v1/users", body={"username": username, "display_name": "Tel", "password": password}) credential = base64.b64encode(f"{username}:{password}".encode()).decode() req = urllib.request.Request( BASE + "/api/v1/auth/sessions", headers={"Authorization": "Basic " + credential, "Accept": "application/json"}, method="POST", ) with urllib.request.urlopen(req, timeout=20) as resp: token = json.loads(resp.read())["token"] user_id = json.loads(request("GET", BASE + "/api/v1/users/me", token=token)[2])["id"] chat = json.loads(request("POST", BASE + "/api/v1/chats", token=token, body={"title": "tel", "member_ids": [user_id]})[2]) status, headers, body = request( "POST", f"{BASE}/api/v1/chats/{chat['id']}/attachments?filename=t.png", token=token, raw=make_png(), content_type="image/png", ) assert status == 202, (status, body) return token, json.loads(body)["id"], headers.get("X-Request-Id") def wait_ready(timeout=90): deadline = time.time() + timeout while time.time() < deadline: if request("GET", BASE + "/health/ready")[0] == 200: return time.sleep(1) raise SystemExit("stand not ready") def compose(*args): subprocess.run(["docker", "compose", *args], check=True, capture_output=True, text=True) def tempo_search(service="messenger-api", limit=60, window=180): end = int(time.time()) start = end - window url = f"{TEMPO}/api/search?" + urllib.parse.urlencode( {"tags": f"service.name={service}", "start": start, "end": end, "limit": limit} ) data = get_json(url) or {} return [t["traceID"] for t in data.get("traces", [])] def loki_has_trace(trace_id, service): query = '{service_name="%s"} | trace_id = "%s"' % (service, trace_id) end = time.time() start = end - 900 url = LOKI + "/loki/api/v1/query_range?" + urllib.parse.urlencode( {"query": query, "limit": 1, "start": f"{int(start)}000000000", "end": f"{int(end)}000000000"} ) data = get_json(url) return bool(data and data["data"]["result"]) def tempo_services(trace_id): data = get_json(f"{TEMPO}/api/traces/{trace_id}") if not data: return set() services = set() for batch in data.get("batches", []): for attr in batch.get("resource", {}).get("attributes", []): if attr.get("key") == "service.name": services.add(attr["value"].get("stringValue")) return services def find_linked_trace(timeout=90): deadline = time.time() + timeout while time.time() < deadline: candidates = set(tempo_search("messenger-worker")) | set(tempo_search("messenger-api")) for trace_id in candidates: services = tempo_services(trace_id) if {"messenger-api", "messenger-worker"} <= services: return trace_id, services time.sleep(3) return None, set() def wait_alert(name, state, timeout): deadline = time.time() + timeout while time.time() < deadline: if active_alerts().get(name) == state: return True time.sleep(3) return False def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--skip-incidents", action="store_true") args = parser.parse_args() wait_ready() print("== 1. metrics present ==") for expr in [ "sum(http_server_requests_total)", "sum(messenger_jobs_processed_total)", "max(messenger_queue_depth)", "max(messenger_worker_capacity)", "max(messenger_db_pool_used)", ]: result = prom_query(expr) assert result, f"metric empty: {expr}" print(f" {expr} -> {result[0]['value'][1]}") print("== 2. cross-process trace (API -> worker) + correlated logs ==") token, attachment_id, request_id = login_upload() trace_id, services = find_linked_trace() assert trace_id, "no trace linking messenger-api and messenger-worker found in Tempo" print(f" trace {trace_id} services={sorted(services)}") assert loki_has_trace(trace_id, "messenger-api"), "no API log for that trace_id" assert loki_has_trace(trace_id, "messenger-worker"), "no worker log for that trace_id" print(" Loki has both API and worker logs with this trace_id") print("== 3. alert rules loaded ==") rules = get_json(PROM + "/api/v1/rules") or {"data": {"groups": []}} names = {r["name"] for g in rules["data"]["groups"] for r in g["rules"]} assert {"HighErrorRate", "QueueLagGrowing"} <= names, names print(f" rules: {sorted(names)}") if args.skip_incidents: print("PASS: telemetry signals (incidents skipped)") return print("== 4. incident 1: worker stopped -> queue age alert fires ==") compose("stop", "worker") try: for _ in range(6): login_upload() fired = wait_alert("QueueLagGrowing", "firing", 240) print(f" QueueLagGrowing firing={fired}") assert fired, "queue lag alert did not fire" finally: compose("start", "worker") resolved = wait_alert("QueueLagGrowing", None, 300) print(f" QueueLagGrowing resolved={resolved}") assert resolved, "queue lag alert did not resolve" print("== 5. incident 2: PostgreSQL down -> 5xx error ratio fires ==") compose("stop", "postgres") try: fired = False deadline = time.time() + 260 while time.time() < deadline: for _ in range(5): login_upload_safe() if active_alerts().get("HighErrorRate") == "firing": fired = True break time.sleep(10) print(f" HighErrorRate firing={fired}") assert fired, "error-rate alert did not fire" finally: compose("start", "postgres") resolved = wait_alert("HighErrorRate", None, 300) print(f" HighErrorRate resolved={resolved}") assert resolved, "error-rate alert did not resolve" wait_ready(120) print("== 6. telemetry backend down does not break the API ==") compose("stop", "loki") try: result = subprocess.run([sys.executable, "tests/smoke.py", "--base-url", BASE], capture_output=True, text=True) print(" smoke:", result.stdout.strip() or result.stderr.strip()) assert result.returncode == 0, "smoke failed while Loki was down" finally: compose("start", "loki") print("\nPASS: lab6 observability acceptance checks") def login_upload_safe(): try: login_upload() except Exception: # noqa: BLE001 - expected 503 while DB is down pass if __name__ == "__main__": main()