ЛР7 на 4: HTTPS, mTLS, OpenBao AppRole и ротация leaf.
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Smoke/security/grade4/persistence/failover пройдены; REPORT и DEFENSE.
This commit is contained in:
Executable
+198
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-4 observability checks for Gavrilenko lab6 (outbox + RabbitMQ)."""
|
||||
import datetime
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8087")
|
||||
PROM = os.environ.get("PROMETHEUS_URL", "http://127.0.0.1:9097")
|
||||
TEMPO = os.environ.get("TEMPO_URL", "http://127.0.0.1:3207")
|
||||
LOKI = os.environ.get("LOKI_URL", "http://127.0.0.1:3107")
|
||||
COMPOSE = os.environ.get("COMPOSE", "docker compose -p gavrilenko-lab6 --env-file .env")
|
||||
|
||||
|
||||
def get(url):
|
||||
with urllib.request.urlopen(
|
||||
urllib.request.Request(url, headers={"Accept": "application/json"}),
|
||||
timeout=10,
|
||||
) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def dc(*args):
|
||||
return subprocess.check_output(
|
||||
[*COMPOSE.split(), *args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
stderr=subprocess.DEVNULL,
|
||||
).strip()
|
||||
|
||||
|
||||
def query(expr):
|
||||
return get(PROM + "/api/v1/query?" + urllib.parse.urlencode({"query": expr}))[
|
||||
"data"
|
||||
]["result"]
|
||||
|
||||
|
||||
def alerts():
|
||||
payload = get(PROM + "/api/v1/alerts")
|
||||
return [
|
||||
{
|
||||
"name": item["labels"]["alertname"],
|
||||
"state": item["state"],
|
||||
}
|
||||
for item in payload["data"]["alerts"]
|
||||
]
|
||||
|
||||
|
||||
def wait_for(fn, timeout=90):
|
||||
start = time.monotonic()
|
||||
while time.monotonic() - start < timeout:
|
||||
try:
|
||||
value = fn()
|
||||
if value:
|
||||
return value, round(time.monotonic() - start, 3)
|
||||
except (OSError, KeyError, ValueError, urllib.error.URLError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError("timeout waiting telemetry")
|
||||
|
||||
|
||||
def norm_spans(trace):
|
||||
spans = []
|
||||
for batch in trace.get("batches", trace.get("resourceSpans", [])):
|
||||
attrs = {
|
||||
x["key"]: x["value"].get("stringValue")
|
||||
for x in batch.get("resource", {}).get("attributes", [])
|
||||
}
|
||||
for scope in batch.get("scopeSpans", batch.get("instrumentationLibrarySpans", [])):
|
||||
for span in scope.get("spans", []):
|
||||
spans.append(
|
||||
{
|
||||
"service": attrs.get("service.name"),
|
||||
"name": span["name"],
|
||||
"id": span.get("spanId"),
|
||||
"parent_id": span.get("parentSpanId"),
|
||||
}
|
||||
)
|
||||
return spans
|
||||
|
||||
|
||||
def trace_chain(c, actor, chat):
|
||||
response = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=trace.png",
|
||||
202,
|
||||
actor=actor,
|
||||
raw=(ROOT / "tests/fixtures/sample.png").read_bytes(),
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
trace_id = response["headers"].get("X-Trace-Id")
|
||||
check(trace_id and len(trace_id) == 32, "missing API root trace id")
|
||||
att = c.wait_ready(actor, response["json"])
|
||||
|
||||
def complete_trace():
|
||||
trace = get(TEMPO + "/api/traces/" + trace_id)
|
||||
serialized = json.dumps(trace)
|
||||
check(actor["token"] not in serialized, "token leaked to traces")
|
||||
spans = norm_spans(trace)
|
||||
names = {s["name"] for s in spans}
|
||||
needed = {"queue.publish", "queue.consume", "image.transform", "s3.request"}
|
||||
if not needed.issubset(names):
|
||||
return None
|
||||
return spans
|
||||
|
||||
spans, delay = wait_for(complete_trace)
|
||||
services = {s["service"] for s in spans}
|
||||
check({"messenger-api", "messenger-worker"}.issubset(services), "missing service in trace")
|
||||
for span in spans:
|
||||
if span["name"] == "queue.consume":
|
||||
parents = {s["id"] for s in spans if s["name"] == "queue.publish"}
|
||||
check(span["parent_id"] in parents, "consumer not linked to producer span")
|
||||
|
||||
params = {
|
||||
"query": '{service_name=~"messenger-(api|worker)"} | trace_id="' + trace_id + '"',
|
||||
"limit": "100",
|
||||
"start": str(int((time.time() - 180) * 1e9)),
|
||||
"end": str(int(time.time() * 1e9)),
|
||||
}
|
||||
logs = wait_for(
|
||||
lambda: get(LOKI + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params))[
|
||||
"data"
|
||||
]["result"],
|
||||
timeout=60,
|
||||
)[0]
|
||||
log_services = {entry["stream"].get("service_name") for entry in logs}
|
||||
check({"messenger-api", "messenger-worker"}.issubset(log_services), "correlated logs missing")
|
||||
result = {
|
||||
"trace_id": trace_id,
|
||||
"attachment_id": att["id"],
|
||||
"ingest_wait_seconds": delay,
|
||||
"spans": spans,
|
||||
"log_services": sorted(log_services),
|
||||
}
|
||||
(ROOT / "evidence" / "trace-chain.json").write_text(json.dumps(result, indent=2) + "\n")
|
||||
print("PASS: API → outbox → RabbitMQ → worker trace chain", flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def worker_incident(c, actor, chat):
|
||||
dc("stop", "worker")
|
||||
fired = False
|
||||
try:
|
||||
for _ in range(12):
|
||||
att, _ = c.attachment(actor, chat)
|
||||
c.wait_ready(actor, att, wait_seconds=1)
|
||||
time.sleep(8)
|
||||
for item in alerts():
|
||||
if item["name"] == "QueueLag" and item["state"] == "firing":
|
||||
fired = True
|
||||
check(fired, "QueueLag did not fire with worker stopped")
|
||||
except Failure:
|
||||
pass
|
||||
finally:
|
||||
dc("up", "-d", "--no-deps", "worker")
|
||||
time.sleep(15)
|
||||
resolved = not any(
|
||||
a["name"] == "QueueLag" and a["state"] == "firing" for a in alerts()
|
||||
)
|
||||
check(resolved, "QueueLag did not resolve after worker restart")
|
||||
print("PASS: worker stop/start alert firing and resolve", flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
Path(ROOT / "evidence").mkdir(exist_ok=True)
|
||||
c = Client(BASE)
|
||||
users = c.register_users(2)
|
||||
actor = users[0]
|
||||
chat = c.create_chat(actor, users[1])
|
||||
trace_chain(c, actor, chat)
|
||||
worker_incident(c, actor, chat)
|
||||
summary = {
|
||||
"finished_at": datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
"slo": {
|
||||
"api": "99% non-5xx business requests (10m)",
|
||||
"ready": "95% attachments ready within 5s",
|
||||
},
|
||||
"alerts": alerts(),
|
||||
}
|
||||
(ROOT / "evidence" / "observability-summary.json").write_text(
|
||||
json.dumps(summary, indent=2) + "\n"
|
||||
)
|
||||
print("PASS: observability grade-4 bundle", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user