forked from mtusi2026/mtusi2026lab6
429 lines
14 KiB
Python
429 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Проверка сигналов и отказов на локальном учебном Compose-стенде."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from urllib.error import HTTPError, URLError
|
|
from urllib.parse import urlencode
|
|
from urllib.request import urlopen
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, Failure, check, run
|
|
|
|
BACKLOG_ALERT = "MessengerQueueLag"
|
|
ERROR_ALERT = "MessengerHighErrorRate"
|
|
UPLOAD_ROUTE = "/api/v1/chats/{chat_id}/attachments"
|
|
|
|
|
|
def compose(*args, stdin=None):
|
|
subprocess.run(
|
|
["docker", "compose", "-p", "messenger-lab6", *args],
|
|
cwd=ROOT,
|
|
input=stdin,
|
|
text=True,
|
|
check=True,
|
|
timeout=90,
|
|
stdout=sys.stderr,
|
|
)
|
|
|
|
|
|
def sql(statement):
|
|
compose(
|
|
"exec",
|
|
"-T",
|
|
"postgres",
|
|
"sh",
|
|
"-c",
|
|
'psql -X -q -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
|
stdin=statement,
|
|
)
|
|
|
|
|
|
@contextmanager
|
|
def stopped(*services):
|
|
compose("stop", *services)
|
|
try:
|
|
yield
|
|
finally:
|
|
compose("start", *services)
|
|
|
|
|
|
def eventually(label, predicate, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
result = predicate()
|
|
if result:
|
|
return result
|
|
except (URLError, TimeoutError, Failure):
|
|
pass
|
|
time.sleep(1)
|
|
raise Failure(label)
|
|
|
|
|
|
class Observations:
|
|
def __init__(self, grafana):
|
|
self.grafana = grafana.rstrip("/")
|
|
|
|
def get(self, path, **params):
|
|
url = self.grafana + path + ("?" + urlencode(params) if params else "")
|
|
with urlopen(url, timeout=5) as response:
|
|
return json.load(response)
|
|
|
|
def ready(self, datasource):
|
|
url = self.grafana + f"/api/datasources/proxy/uid/{datasource}/ready"
|
|
with urlopen(url, timeout=5) as response:
|
|
return response.status == 200
|
|
|
|
def query(self, expression):
|
|
data = self.get(
|
|
"/api/datasources/proxy/uid/prometheus/api/v1/query", query=expression
|
|
)
|
|
return data["data"]["result"]
|
|
|
|
def value(self, expression):
|
|
rows = self.query(expression)
|
|
return float(rows[0]["value"][1]) if rows else 0.0
|
|
|
|
def firing(self, name):
|
|
alerts = self.get("/api/datasources/proxy/uid/prometheus/api/v1/alerts")[
|
|
"data"
|
|
]["alerts"]
|
|
return any(
|
|
alert["labels"]["alertname"] == name and alert["state"] == "firing"
|
|
for alert in alerts
|
|
)
|
|
|
|
def trace(self, trace_id):
|
|
try:
|
|
data = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id)
|
|
except HTTPError as error:
|
|
if error.code == 404:
|
|
return []
|
|
raise
|
|
return [
|
|
(span, attributes(batch["resource"]).get("service.name"))
|
|
for batch in data.get("batches", data.get("resourceSpans", []))
|
|
for scope in batch["scopeSpans"]
|
|
for span in scope["spans"]
|
|
]
|
|
|
|
def logs(self, service, trace_id):
|
|
data = self.get(
|
|
"/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
|
|
query=f'{{service_name="{service}"}} | trace_id="{trace_id}"',
|
|
limit=50,
|
|
)
|
|
return data["data"]["result"]
|
|
|
|
|
|
def attributes(entity):
|
|
return {
|
|
item["key"]: next(iter(item["value"].values()))
|
|
for item in entity.get("attributes", [])
|
|
}
|
|
|
|
|
|
def upload(client, actor, chat):
|
|
body = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
|
name = "private-filename-" + uuid.uuid4().hex + ".png"
|
|
response = client.call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/attachments?filename={name}",
|
|
202,
|
|
actor=actor,
|
|
raw=body,
|
|
headers={"Content-Type": "image/png"},
|
|
schema="Attachment",
|
|
)
|
|
check(response["json"]["status"] == "queued", "upload did not return queued")
|
|
trace_id = response["headers"].get("X-Trace-Id", "")
|
|
check(bool(re.fullmatch(r"[0-9a-f]{32}", trace_id)), "missing trace ID")
|
|
return response["json"], trace_id, response["headers"]["X-Request-Id"], name
|
|
|
|
|
|
def chain(obs, trace_id, attempts):
|
|
def lookup():
|
|
spans = obs.trace(trace_id)
|
|
producer = {
|
|
int(attributes(span)["job.attempt"]): span
|
|
for span, service in spans
|
|
if service == "messenger-dispatcher" and span["name"] == "rabbitmq.publish"
|
|
}
|
|
consumer = {
|
|
int(attributes(span)["job.attempt"]): span
|
|
for span, service in spans
|
|
if service == "messenger-worker" and span["name"] == "rabbitmq.consume"
|
|
}
|
|
names = {span["name"] for span, _ in spans}
|
|
if not (
|
|
{f"POST {UPLOAD_ROUTE}", "s3.put", "postgres.complete"} <= names
|
|
and attempts <= producer.keys()
|
|
and attempts <= consumer.keys()
|
|
):
|
|
return None
|
|
for attempt in attempts:
|
|
check(
|
|
consumer[attempt]["parentSpanId"] == producer[attempt]["spanId"],
|
|
"consumer parent mismatch",
|
|
)
|
|
return spans
|
|
|
|
return eventually("trace lacks upload, RabbitMQ, S3 or committed result", lookup)
|
|
|
|
|
|
def verify_signals(client, obs, alice, chat):
|
|
attachment, trace_id, request_id, filename = upload(client, alice, chat)
|
|
ready = client.wait_ready(alice, attachment)
|
|
check(len(ready["variants"]) == 3, "missing image variants")
|
|
spans = chain(obs, trace_id, {1})
|
|
api_logs = eventually(
|
|
"API log missing", lambda: obs.logs("messenger-api", trace_id)
|
|
)
|
|
worker_logs = eventually(
|
|
"worker log missing", lambda: obs.logs("messenger-worker", trace_id)
|
|
)
|
|
exported = json.dumps([spans, api_logs, worker_logs])
|
|
check(request_id in exported, "request ID absent")
|
|
check(
|
|
alice["token"] not in exported
|
|
and alice["registration"]["password"] not in exported
|
|
and filename not in exported,
|
|
"private data exported",
|
|
)
|
|
metrics = [
|
|
"messenger_http_requests_total",
|
|
"messenger_http_duration_seconds_bucket",
|
|
"messenger_jobs_total",
|
|
"messenger_job_duration_seconds_bucket",
|
|
"messenger_attachment_ready_duration_seconds_bucket",
|
|
"messenger_queue_depth",
|
|
"messenger_queue_oldest_age_seconds",
|
|
"messenger_outbox_pending",
|
|
"messenger_db_pool",
|
|
"messenger_worker_busy",
|
|
"messenger_worker_capacity",
|
|
"messenger_process_cpu_seconds_total",
|
|
"messenger_process_memory_bytes",
|
|
"messenger_container_cpu_seconds_total",
|
|
"messenger_container_memory_bytes",
|
|
"messenger:http_availability:15m",
|
|
]
|
|
eventually(
|
|
"missing Prometheus series",
|
|
lambda: all(obs.query(metric) for metric in metrics),
|
|
)
|
|
disallowed = {
|
|
"request_id",
|
|
"user_id",
|
|
"chat_id",
|
|
"message_id",
|
|
"attachment_id",
|
|
"filename",
|
|
"url",
|
|
}
|
|
check(
|
|
not any(
|
|
disallowed & row["metric"].keys()
|
|
for metric in metrics
|
|
for row in obs.query(metric)
|
|
),
|
|
"unexpected metric labels",
|
|
)
|
|
dashboard = obs.get("/api/dashboards/uid/messenger-lab6")["dashboard"]
|
|
check(
|
|
dashboard["uid"] == "messenger-lab6" and len(dashboard["panels"]) >= 16,
|
|
"dashboard not provisioned",
|
|
)
|
|
print(
|
|
f"SIGNALS trace={trace_id} request_id={request_id} spans={len(spans)} "
|
|
f"metrics={len(metrics)} panels={len(dashboard['panels'])}",
|
|
flush=True,
|
|
)
|
|
return trace_id
|
|
|
|
|
|
def verify_queue(client, obs, alice, chat):
|
|
with stopped("worker"):
|
|
attachment, trace_id, _, _ = upload(client, alice, chat)
|
|
client.message(alice, chat, "Контроль очереди", attachments=[attachment["id"]])
|
|
client.call(
|
|
"GET", f"/api/v1/attachments/{attachment['id']}/content", 409, actor=alice
|
|
)
|
|
eventually("queue alert did not fire", lambda: obs.firing(BACKLOG_ALERT))
|
|
depth = obs.value("max(messenger_queue_depth)")
|
|
age = obs.value("max(messenger_queue_oldest_age_seconds)")
|
|
check(depth >= 1 and age > 10, "queue metrics did not show backlog")
|
|
trigger = "lab6_retry_" + uuid.uuid4().hex
|
|
sql(f"""CREATE FUNCTION {trigger}() RETURNS trigger LANGUAGE plpgsql AS $$
|
|
BEGIN IF NEW.id = '{attachment["id"]}' AND NEW.status = 'ready'
|
|
THEN RAISE EXCEPTION 'lab6 retry verification'; END IF; RETURN NEW; END; $$;
|
|
CREATE TRIGGER {trigger} BEFORE UPDATE ON attachments FOR EACH ROW
|
|
EXECUTE FUNCTION {trigger}();""")
|
|
try:
|
|
eventually(
|
|
"retry was not exported",
|
|
lambda: any(
|
|
attributes(span).get("job.outcome") == "retry"
|
|
for span, _ in obs.trace(trace_id)
|
|
),
|
|
)
|
|
finally:
|
|
sql(
|
|
f"DROP TRIGGER IF EXISTS {trigger} ON attachments; DROP FUNCTION IF EXISTS {trigger}();"
|
|
)
|
|
ready = client.wait_ready(alice, attachment)
|
|
chain(obs, trace_id, {1, 2})
|
|
downloaded = client.call(
|
|
"GET", f"/api/v1/attachments/{ready['id']}/content", actor=alice
|
|
)["bytes"]
|
|
check(hashlib.sha256(downloaded).hexdigest() == ready["sha256"], "original changed")
|
|
eventually(
|
|
"queue did not drain or alert still firing",
|
|
lambda: obs.value("max(messenger_queue_depth)") == 0
|
|
and not obs.firing(BACKLOG_ALERT),
|
|
)
|
|
print(
|
|
f"QUEUE firing → resolved; depth={depth:g} oldest={age:.1f}s trace={trace_id} retry linked",
|
|
flush=True,
|
|
)
|
|
|
|
|
|
def verify_database(client, obs, alice, chat):
|
|
with stopped("postgres"):
|
|
first_failed = None
|
|
started = time.monotonic()
|
|
failures = 0
|
|
while time.monotonic() - started < 35:
|
|
response = client.call(
|
|
"POST",
|
|
f"/api/v1/chats/{chat['id']}/messages",
|
|
503,
|
|
actor=alice,
|
|
body={"text": "Контроль отказа"},
|
|
headers={"Idempotency-Key": uuid.uuid4().hex},
|
|
)
|
|
first_failed = first_failed or response["headers"]["X-Trace-Id"]
|
|
failures += 1
|
|
if obs.firing(ERROR_ALERT):
|
|
break
|
|
time.sleep(0.25)
|
|
check(obs.firing(ERROR_ALERT), "5xx alert did not fire")
|
|
error_ratio = obs.value("messenger:http_error_ratio:30s")
|
|
spans = eventually(
|
|
"PostgreSQL failure span missing",
|
|
lambda: [
|
|
span
|
|
for span, _ in obs.trace(first_failed)
|
|
if span["name"].startswith("postgres.")
|
|
and attributes(span).get("error.type")
|
|
],
|
|
)
|
|
logs = eventually(
|
|
"PostgreSQL error log missing",
|
|
lambda: obs.logs("messenger-api", first_failed),
|
|
)
|
|
check(
|
|
"postgres.unavailable" in json.dumps(logs),
|
|
"trace and DB error log not linked",
|
|
)
|
|
eventually(
|
|
"PostgreSQL did not recover",
|
|
lambda: client.call("GET", "/health/ready", schema="Health"),
|
|
)
|
|
client.message(alice, chat, "PostgreSQL восстановлен")
|
|
eventually("5xx alert still firing", lambda: not obs.firing(ERROR_ALERT))
|
|
print(
|
|
f"DB firing → resolved; 503={failures} ratio={error_ratio:.1%} "
|
|
f"trace={first_failed} failed_span={spans[0]['name']}",
|
|
flush=True,
|
|
)
|
|
|
|
|
|
def verify_storage(client, obs, alice, chat, previous_trace):
|
|
metrics = 'sum({__name__=~"otelcol_exporter_(send|enqueue)_failed_(log_records|spans)_total"})'
|
|
before = eventually(
|
|
"Prometheus counters unavailable", lambda: (obs.value(metrics),)
|
|
)[0]
|
|
with stopped("loki", "tempo"):
|
|
deadline = time.monotonic() + 18
|
|
successes = 0
|
|
with ThreadPoolExecutor(max_workers=3) as pool:
|
|
while time.monotonic() < deadline:
|
|
successes += sum(
|
|
pool.map(
|
|
lambda _: client.message(alice, chat, "Контроль экспорта")[
|
|
"status"
|
|
]
|
|
== 201,
|
|
range(6),
|
|
)
|
|
)
|
|
time.sleep(0.2)
|
|
# Counters increase after a batch exhausts its retry budget.
|
|
lost = eventually(
|
|
"collector drop counters did not increase",
|
|
lambda: max(0, obs.value(metrics) - before),
|
|
)
|
|
rss = eventually(
|
|
"Collector RSS missing",
|
|
lambda: obs.value(
|
|
"max(max_over_time(otelcol_process_memory_rss_bytes[1m]))"
|
|
),
|
|
)
|
|
check(
|
|
0 < rss < 256 * 1024 * 1024, "collector RSS not observed below cgroup limit"
|
|
)
|
|
check(
|
|
successes >= 30,
|
|
"not enough successful business requests during telemetry outage",
|
|
)
|
|
eventually("Loki/Tempo not ready", lambda: obs.ready("loki") and obs.ready("tempo"))
|
|
eventually(
|
|
"collector queues did not drain",
|
|
lambda: bool(obs.query("otelcol_exporter_queue_size"))
|
|
and obs.value("sum(otelcol_exporter_queue_size)") == 0,
|
|
)
|
|
check(obs.logs("messenger-api", previous_trace), "Loki history lost on restart")
|
|
check(obs.trace(previous_trace), "Tempo history lost on restart")
|
|
_, trace_id, _, _ = upload(client, alice, chat)
|
|
eventually(
|
|
"Loki did not resume ingest", lambda: obs.logs("messenger-api", trace_id)
|
|
)
|
|
eventually("Tempo did not resume ingest", lambda: obs.trace(trace_id))
|
|
print(
|
|
f"STORAGE successful writes={successes} dropped logs/spans={lost:g} "
|
|
f"peak collector RSS={rss / 1024**2:.1f} MiB; history preserved and new signals ingested",
|
|
flush=True,
|
|
)
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--base-url", required=True)
|
|
parser.add_argument("--grafana-url", required=True)
|
|
parser.add_argument("--incidents", action="store_true")
|
|
args = parser.parse_args()
|
|
client = Client(args.base_url)
|
|
obs = Observations(args.grafana_url)
|
|
alice, _, _, chat = client.bootstrap()
|
|
trace_id = verify_signals(client, obs, alice, chat)
|
|
if args.incidents:
|
|
verify_queue(client, obs, alice, chat)
|
|
verify_database(client, obs, alice, chat)
|
|
verify_storage(client, obs, alice, chat, trace_id)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run(main)
|