forked from mtusi2026/mtusi2026lab6
lab6
This commit is contained in:
+20
-14
@@ -3,25 +3,31 @@ set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
[ -f .env ] || { cp .env.example .env; echo ".env создан из .env.example"; }
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
python3 - <<'PY'
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
from urllib.parse import quote
|
||||
|
||||
env = Path('.env')
|
||||
lines = env.read_text().splitlines()
|
||||
values = dict(line.split('=', 1) for line in lines if '=' in line and not line.startswith('#'))
|
||||
password_file = Path('secrets/postgres_password.txt')
|
||||
values['POSTGRES_PASSWORD'] = values.get('POSTGRES_PASSWORD') or (password_file.read_text().strip() if password_file.exists() else secrets.token_hex(24))
|
||||
values['DATABASE_URL'] = values.get('DATABASE_URL') or f"postgres://{values.get('POSTGRES_USER', 'messenger')}:{values['POSTGRES_PASSWORD']}@postgres:5432/{values.get('POSTGRES_DB', 'messenger')}?sslmode=disable"
|
||||
for key in ('POSTGRES_PASSWORD', 'DATABASE_URL'):
|
||||
lines = [line for line in lines if not line.startswith(key + '=')]
|
||||
lines.append(key + '=' + values[key])
|
||||
for filename, key in [('postgres_password.txt', 'POSTGRES_PASSWORD'), ('database_url.txt', 'DATABASE_URL')]:
|
||||
p = Path('secrets') / filename
|
||||
if not p.exists():
|
||||
p.write_text(values[key])
|
||||
env.write_text('\n'.join(lines) + '\n')
|
||||
values = dict(line.split('=', 1) for line in env.read_text().splitlines() if '=' in line and not line.lstrip().startswith('#'))
|
||||
|
||||
def local_secret(filename, default):
|
||||
path = Path('secrets') / filename
|
||||
if not path.exists():
|
||||
path.write_text(default + '\n')
|
||||
return path.read_text().strip()
|
||||
|
||||
password = local_secret('postgres_password.txt', values.get('POSTGRES_PASSWORD') or secrets.token_hex(24))
|
||||
user = quote(values.get('POSTGRES_USER', 'messenger'), safe='')
|
||||
database = quote(values.get('POSTGRES_DB', 'messenger'), safe='')
|
||||
dsn = f"postgres://{user}:{quote(password, safe='')}@postgres:5432/{database}?sslmode=disable"
|
||||
local_secret('database_url.txt', values.get('DATABASE_URL') or dsn)
|
||||
local_secret('grafana_admin_password.txt', secrets.token_urlsafe(24))
|
||||
env.chmod(0o600)
|
||||
PY
|
||||
./scripts/gen-s3-secrets.sh
|
||||
chmod 644 secrets/*
|
||||
chmod 644 secrets/postgres_password.txt secrets/database_url.txt secrets/grafana_admin_password.txt \
|
||||
secrets/s3_config.json secrets/s3_api_access_key.txt secrets/s3_api_secret_key.txt \
|
||||
secrets/s3_admin_access_key.txt secrets/s3_admin_secret_key.txt
|
||||
echo "секреты готовы"
|
||||
|
||||
+21
-14
@@ -8,22 +8,26 @@ import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
LAB = json.loads((ROOT / "lab.json").read_text())["number"]
|
||||
|
||||
|
||||
def run(*args):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
info = json.loads(run('docker', 'info', '--format', '{{json .}}'))
|
||||
version, cpus, memory = run('docker', 'info', '--format', '{{.ServerVersion}} {{.NCPU}} {{.MemTotal}}').split()
|
||||
ids = run('docker', 'compose', 'ps', '-q').splitlines()
|
||||
inspected = json.loads(run('docker', 'inspect', *ids))
|
||||
project = inspected[0]['Config']['Labels']['com.docker.compose.project']
|
||||
containers = []
|
||||
for item in json.loads(run('docker', 'inspect', *ids)):
|
||||
for item in inspected:
|
||||
containers.append(dict(name=item['Name'], image=item['Config']['Image'],
|
||||
started_at=item['State']['StartedAt'], cpus=item['HostConfig']['NanoCpus']/1e9,
|
||||
memory_bytes=item['HostConfig']['Memory'], volumes=[m['Name'] for m in item['Mounts'] if m['Type']=='volume']))
|
||||
report = dict(date=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
host_machine=platform.machine(), host_os=platform.platform(),
|
||||
docker=dict(version=info['ServerVersion'], cpus=info['NCPU'], memory_bytes=info['MemTotal']),
|
||||
docker=dict(version=version, cpus=int(cpus), memory_bytes=int(memory)),
|
||||
go=run('go','version'), compose=run('docker','compose','version'),
|
||||
image_runtime=run('docker','compose','exec','-T','worker','python3','-c',"import sys,PIL; print(sys.version.split()[0], 'Pillow', PIL.__version__)"),
|
||||
containers=containers)
|
||||
@@ -34,21 +38,24 @@ def dataset():
|
||||
return json.loads(raw)
|
||||
report['dataset_before']=dataset()
|
||||
if '--load' in sys.argv:
|
||||
log=(ROOT/'evidence/lab5-load.txt').open('w')
|
||||
load=subprocess.Popen([sys.executable,'tests/load.py','--duration','30','--concurrency','4','--output','evidence/lab5-load.json'],cwd=ROOT,stdout=log,stderr=subprocess.STDOUT)
|
||||
samples=[]
|
||||
while load.poll() is None:
|
||||
samples.append(dict(at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
containers=[json.loads(line) for line in run('docker','stats','--no-stream','--format','{{json .}}',*ids).splitlines()]))
|
||||
time.sleep(1)
|
||||
log.close()
|
||||
log_path = EVIDENCE / f"lab{LAB}-load.txt"
|
||||
load_path = EVIDENCE / f"lab{LAB}-load.json"
|
||||
samples = []
|
||||
with log_path.open('w') as log:
|
||||
load = subprocess.Popen([sys.executable, 'tests/load.py', '--duration', '30', '--concurrency', '4',
|
||||
'--output', str(load_path)], cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
|
||||
while load.poll() is None:
|
||||
stats = run('docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids)
|
||||
samples.append(dict(at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
||||
containers=[json.loads(line) for line in stats.splitlines()]))
|
||||
time.sleep(1)
|
||||
if load.returncode:
|
||||
raise SystemExit('load failed; see evidence/lab5-load.txt')
|
||||
raise SystemExit(f'load failed; see {log_path}')
|
||||
report['load_samples']=samples
|
||||
report['dataset_after']=dataset()
|
||||
events=run('docker','events','--since','1h','--until','0s','--filter','type=container',
|
||||
'--filter','label=com.docker.compose.project=mtusi2026lab5','--format','{{json .}}')
|
||||
'--filter',f'label=com.docker.compose.project={project}','--format','{{json .}}')
|
||||
report['lifecycle_events']=[dict(time=e['time'],action=e['Action'],name=e['Actor']['Attributes'].get('name'))
|
||||
for e in (json.loads(line) for line in events.splitlines()) if e['Action'] in ('start','stop','die','kill','restart')]
|
||||
(ROOT/'evidence/lab5-runtime.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
(EVIDENCE / f"lab{LAB}-runtime.json").write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS sanitized runtime evidence saved')
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run the level 4 exercises on the local Compose project and save telemetry evidence."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import re
|
||||
import select
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def wait_for(probe, description, timeout=60, interval=2):
|
||||
deadline = time.monotonic() + timeout
|
||||
last_error = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = probe()
|
||||
if value:
|
||||
return value
|
||||
except HTTPError as error:
|
||||
if error.code not in (502, 503, 504):
|
||||
raise
|
||||
last_error = f"HTTP {error.code}"
|
||||
except (URLError, TimeoutError) as error:
|
||||
last_error = type(error).__name__
|
||||
time.sleep(interval)
|
||||
suffix = f" (last transport error: {last_error})" if last_error else ""
|
||||
check(False, "timed out waiting for " + description + suffix)
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.check_output(["docker", "compose", *args], cwd=ROOT, text=True, timeout=60).strip()
|
||||
|
||||
|
||||
def start_only(service):
|
||||
ids = compose("ps", "--all", "--quiet", service).splitlines()
|
||||
check(bool(ids), "missing Compose container for " + service)
|
||||
subprocess.run(["docker", "start", *ids], cwd=ROOT, check=True, capture_output=True, timeout=30)
|
||||
|
||||
|
||||
def collector_started_at():
|
||||
container = compose("ps", "-q", "otel-collector")
|
||||
return subprocess.check_output(["docker", "inspect", "--format", "{{.State.StartedAt}}", container],
|
||||
cwd=ROOT, text=True, timeout=10).strip()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def stopped(service):
|
||||
compose("stop", "-t", "5", service)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
start_only(service)
|
||||
|
||||
|
||||
def trace_headers():
|
||||
trace_id, parent = uuid4().hex, uuid4().hex[:16]
|
||||
return trace_id, parent, {"traceparent": f"00-{trace_id}-{parent}-01", "tracestate": "lab=probe"}
|
||||
|
||||
|
||||
def attrs(items):
|
||||
result = {}
|
||||
for item in items:
|
||||
kind, value = next(iter(item["value"].items()))
|
||||
result[item["key"]] = int(value) if kind == "intValue" else value
|
||||
return result
|
||||
|
||||
|
||||
def span_id(value):
|
||||
if not value or re.fullmatch(r"[0-9a-f]{16}", value):
|
||||
return value
|
||||
return base64.b64decode(value).hex()
|
||||
|
||||
|
||||
class Grafana:
|
||||
def __init__(self, base):
|
||||
self.base = base.rstrip("/")
|
||||
|
||||
def get(self, path, **params):
|
||||
url = self.base + path + ("?" + urlencode(params) if params else "")
|
||||
with urlopen(Request(url, headers={"Accept": "application/json"}), timeout=8) as response:
|
||||
return json.load(response)
|
||||
|
||||
def source(self, uid, path, **params):
|
||||
return self.get(f"/api/datasources/proxy/uid/{uid}{path}", **params)
|
||||
|
||||
def scalar(self, query, optional=False):
|
||||
result = self.source("prometheus", "/api/v1/query", query=query)["data"]["result"]
|
||||
if not result and optional:
|
||||
return None
|
||||
check(len(result) == 1, "expected one Prometheus series for " + query)
|
||||
value = float(result[0]["value"][1])
|
||||
return value if math.isfinite(value) else None
|
||||
|
||||
def alert(self, name):
|
||||
groups = self.source("prometheus", "/api/v1/rules", type="alert")["data"]["groups"]
|
||||
rule = next(rule for group in groups for rule in group["rules"] if rule["name"] == name)
|
||||
check(rule["health"] == "ok", "Prometheus error evaluating " + name)
|
||||
return rule["state"]
|
||||
|
||||
def logs(self, trace_id):
|
||||
data = self.source("loki", "/loki/api/v1/query_range",
|
||||
query='{service_name=~"messenger-.*"} | trace_id="' + trace_id + '"',
|
||||
since="15m", limit=100)
|
||||
result = []
|
||||
for stream in data["data"]["result"]:
|
||||
for ts, event, *extra in stream["values"]:
|
||||
labels = dict(stream["stream"])
|
||||
for fields in extra:
|
||||
labels.update(fields.get("structuredMetadata", fields))
|
||||
result.append({"timestamp_unix_ns": ts, "event": event, **labels})
|
||||
return result
|
||||
|
||||
def spans(self, trace_id):
|
||||
try:
|
||||
trace = self.source("tempo", "/api/traces/" + trace_id)
|
||||
except HTTPError as error:
|
||||
if error.code == 404:
|
||||
return []
|
||||
raise
|
||||
result = []
|
||||
for batch in trace.get("batches", trace.get("resourceSpans", [])):
|
||||
resource = attrs(batch["resource"]["attributes"])
|
||||
for scope in batch.get("scopeSpans", batch.get("instrumentationLibrarySpans", [])):
|
||||
for s in scope["spans"]:
|
||||
result.append({
|
||||
"name": s["name"], "kind": s.get("kind"), "resource": resource,
|
||||
"span_id": span_id(s["spanId"]), "parent_span_id": span_id(s.get("parentSpanId", "")),
|
||||
"tracestate": s.get("traceState", ""), "status": s.get("status", {}),
|
||||
"duration_ms": (int(s["endTimeUnixNano"]) - int(s["startTimeUnixNano"])) / 1e6,
|
||||
"attributes": attrs(s.get("attributes", [])),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def check_private(actor, chat, evidence, *markers):
|
||||
text = json.dumps(evidence, ensure_ascii=False)
|
||||
for value in (actor["token"], actor["registration"]["password"], actor["id"], chat["id"], *markers):
|
||||
check(value not in text, "synthetic private marker appeared in telemetry")
|
||||
|
||||
|
||||
def verify_queue(c, g, actor, chat):
|
||||
alert = "MessengerQueueLag"
|
||||
upload_route = f"/api/v1/chats/{chat['id']}/attachments"
|
||||
trace_id, client_parent, carrier = trace_headers()
|
||||
filename = "private-" + uuid4().hex + ".png"
|
||||
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
series = []
|
||||
|
||||
def sample():
|
||||
data = {
|
||||
"at": now(), "state": g.alert(alert), "depth": g.scalar("max(messenger_queue_depth)"),
|
||||
"oldest_seconds": g.scalar("max(messenger_queue_oldest_age_seconds)"),
|
||||
}
|
||||
series.append(data)
|
||||
return data
|
||||
|
||||
print("Останавливаем worker и проверяем возраст очереди", flush=True)
|
||||
check(sample()["state"] == "inactive", "queue alert must start inactive")
|
||||
with stopped("worker"):
|
||||
stopped_at = now()
|
||||
accepted = c.call("POST", upload_route + "?filename=" + filename, 202, actor=actor, raw=fixture,
|
||||
headers={**carrier, "Content-Type": "image/png"}, schema="Attachment")
|
||||
attachment = accepted["json"]
|
||||
extra, _ = c.attachment(actor, chat)
|
||||
wait_for(lambda: (state := sample())["state"] == "firing" and state["depth"] >= 2,
|
||||
"queue alarm firing", timeout=55)
|
||||
print("Алерт очереди firing. Проверяем retry при кратком отказе S3-прокси", flush=True)
|
||||
with stopped("s3-proxy"):
|
||||
start_only("worker")
|
||||
wait_for(lambda: any(x["event"] == "attachment.attempt_failed" for x in g.logs(trace_id)),
|
||||
"worker attempt failed in Loki", timeout=22, interval=0.5)
|
||||
recovered_at = now()
|
||||
wait_for(lambda: ready(c), "API readiness after S3 restart", timeout=35)
|
||||
ready_one, ready_two = c.wait_ready(actor, attachment), c.wait_ready(actor, extra)
|
||||
original = c.call("GET", f"/api/v1/attachments/{ready_one['id']}/content", actor=actor)
|
||||
check(original["bytes"] == fixture, "original changed after retry")
|
||||
wait_for(lambda: (state := sample())["state"] == "inactive" and state["depth"] == 0,
|
||||
"queue alarm resolved")
|
||||
spans = wait_for(lambda: (found := g.spans(trace_id)) and
|
||||
any(x["name"] == "db.job.complete" for x in found) and found, "complete upload trace")
|
||||
logs = wait_for(lambda: (found := g.logs(trace_id)) and any(x["event"] == "attachment.ready" for x in found)
|
||||
and found, "worker completion log")
|
||||
server = next(s for s in spans if s["kind"] in (2, "SPAN_KIND_SERVER"))
|
||||
accept = next(s for s in spans if s["name"] == "db.attachment.accept")
|
||||
check(server["parent_span_id"] == client_parent and accept["parent_span_id"] == server["span_id"],
|
||||
"API trace lost client or acceptance parent")
|
||||
producers = {s["attributes"]["job.attempt"]: s for s in spans if s["kind"] in (4, "SPAN_KIND_PRODUCER")}
|
||||
consumers = {s["attributes"]["job.attempt"]: s for s in spans if s["kind"] in (5, "SPAN_KIND_CONSUMER")}
|
||||
check(len(consumers) >= 2 and len(producers) >= 2, "retry missing in trace")
|
||||
for attempt, consumer in consumers.items():
|
||||
producer = producers[attempt]
|
||||
check(producer["parent_span_id"] == accept["span_id"] and consumer["parent_span_id"] == producer["span_id"],
|
||||
"Redis did not preserve producer/consumer linkage")
|
||||
check(consumer["tracestate"] == carrier["tracestate"], "worker lost W3C tracestate")
|
||||
check(consumers[min(consumers)]["attributes"]["job.outcome"] == "error", "first attempt should fail")
|
||||
last = consumers[max(consumers)]
|
||||
check(last["attributes"]["job.outcome"] == "success"
|
||||
and any(s["name"] == "db.job.complete" and s["parent_span_id"] == last["span_id"] for s in spans)
|
||||
and any(s["name"] == "s3.put_object" and s["parent_span_id"] == last["span_id"] for s in spans),
|
||||
"successful retry must write S3 and commit DB in the same trace")
|
||||
request_id = accepted["headers"]["X-Request-Id"]
|
||||
check(any(x.get("request_id") == request_id and x.get("span_id") == server["span_id"] for x in logs)
|
||||
and any(x["event"] == "attachment.ready" and x.get("span_id") == last["span_id"] for x in logs),
|
||||
"logs lack request ID or matching span ID")
|
||||
check_private(actor, chat, [spans, logs], filename, attachment["id"], base64.b64encode(fixture).decode())
|
||||
return {"worker_stopped_at": stopped_at, "services_restored_at": recovered_at, "timeline": series,
|
||||
"trace_id": trace_id, "request_id": request_id, "spans": spans, "logs": logs,
|
||||
"durable_ready": [ready_one["status"], ready_two["status"]], "original_matches_fixture": True}
|
||||
|
||||
|
||||
def ready(client):
|
||||
try:
|
||||
with urlopen(client.base + "/health/ready", timeout=3) as response:
|
||||
return response.status == 200
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def verify_db(c, g, actor, chat, message_path):
|
||||
alert = "MessengerHighErrorRate"
|
||||
timeline = []
|
||||
marker = "private-message-" + uuid4().hex
|
||||
fired = Event()
|
||||
stop = Event()
|
||||
results = []
|
||||
|
||||
def write_messages():
|
||||
while not stop.is_set():
|
||||
trace_id, _, carrier = trace_headers()
|
||||
reply = c.call("POST", message_path, [201, 500], actor=actor, body={"text": marker}, schema="Message",
|
||||
headers={**carrier, "Idempotency-Key": uuid4().hex})
|
||||
results.append({"status": reply["status"], "request_id": reply["headers"]["X-Request-Id"],
|
||||
"trace_id": trace_id, "ms": round(1000 * reply["elapsed"], 2)})
|
||||
stop.wait(0.4)
|
||||
|
||||
def sample():
|
||||
data = {
|
||||
"at": now(), "state": g.alert(alert),
|
||||
"error_ratio_1m": g.scalar("messenger:api_errors:ratio1m", optional=True),
|
||||
"lock_waiters": g.scalar("max(messenger_db_messages_lock_waiters)"),
|
||||
}
|
||||
timeline.append(data)
|
||||
if data["state"] == "firing":
|
||||
fired.set()
|
||||
return data
|
||||
|
||||
print("Блокируем запись в messages и проверяем алерт 5xx", flush=True)
|
||||
check(sample()["state"] == "inactive", "HTTP alert must start inactive")
|
||||
lock_sql = "BEGIN; SET LOCAL lock_timeout='2s'; LOCK TABLE messages IN SHARE MODE;\n"
|
||||
lock_sql += "SELECT 'lab6_lock_acquired'; SELECT pg_sleep(40); ROLLBACK;\n"
|
||||
command = ["docker", "compose", "exec", "-T", "postgres", "sh", "-c",
|
||||
'exec psql -XqAt -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"']
|
||||
with subprocess.Popen(command, cwd=ROOT, text=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as lock:
|
||||
lock.stdin.write(lock_sql)
|
||||
lock.stdin.close()
|
||||
check(select.select([lock.stdout], [], [], 15)[0] and lock.stdout.readline().strip() == "lab6_lock_acquired",
|
||||
"could not acquire the bounded database lock")
|
||||
locked_at = now()
|
||||
with ThreadPoolExecutor(max_workers=3) as pool:
|
||||
writers = [pool.submit(write_messages) for _ in range(3)]
|
||||
try:
|
||||
while lock.poll() is None:
|
||||
sample()
|
||||
time.sleep(2)
|
||||
check(lock.returncode == 0 and fired.is_set(), "HTTP alert did not fire during database degradation")
|
||||
released_at = now()
|
||||
check(c.message(actor, chat, marker)["status"] == 201, "message write did not recover")
|
||||
wait_for(lambda: (state := sample())["state"] == "inactive" and state["lock_waiters"] == 0,
|
||||
"HTTP alarm resolved", timeout=85)
|
||||
finally:
|
||||
stop.set()
|
||||
for writer in writers:
|
||||
writer.result()
|
||||
failure = next(reply for reply in results if reply["status"] == 500)
|
||||
spans = wait_for(lambda: g.spans(failure["trace_id"]), "failed write trace")
|
||||
logs = wait_for(lambda: g.logs(failure["trace_id"]), "failed write log")
|
||||
check(any(s["name"] == "db.query" and s["duration_ms"] > 3500
|
||||
and s["attributes"].get("db.operation.name") == "INSERT"
|
||||
and s["attributes"].get("error.type") == "deadline_exceeded" for s in spans),
|
||||
"trace did not attribute the timeout to PostgreSQL INSERT")
|
||||
check(max(row["lock_waiters"] for row in timeline) > 0 and
|
||||
any(x.get("request_id") == failure["request_id"] for x in logs), "database or request correlation incomplete")
|
||||
check_private(actor, chat, [spans, logs], marker)
|
||||
return {"locked_at": locked_at, "released_at": released_at, "timeline": timeline, "failed_write": failure,
|
||||
"spans": spans, "logs": logs, "writes_201": sum(x["status"] == 201 for x in results),
|
||||
"writes_500": sum(x["status"] == 500 for x in results)}
|
||||
|
||||
|
||||
def verify_loki(c, g, actor, chat, message_path):
|
||||
def exporter(metric, optional=False):
|
||||
return g.scalar(f'sum({{__name__=~"otelcol_exporter_{metric}(_total)?",exporter="otlphttp/loki"}})',
|
||||
optional=optional)
|
||||
|
||||
def sample():
|
||||
return {
|
||||
"at": now(), "capacity": exporter("queue_capacity"), "queue": exporter("queue_size"),
|
||||
"send_failed": exporter("send_failed_log_records", optional=True) or 0,
|
||||
"enqueue_failed": exporter("enqueue_failed_log_records", optional=True) or 0,
|
||||
"sent": exporter("sent_log_records"),
|
||||
"accepted": g.scalar('sum({__name__=~"otelcol_receiver_accepted_log_records(_total)?"})'),
|
||||
"rss_bytes": g.scalar('max({__name__=~"otelcol_process_memory_rss(_bytes)?",job="otel-collector"})'),
|
||||
}
|
||||
|
||||
print("Останавливаем Loki и проверяем запись сообщений и буфер Collector", flush=True)
|
||||
wait_for(lambda: exporter("queue_size") == 0, "initial empty log queue")
|
||||
collector_start = collector_started_at()
|
||||
timeline = [sample()]
|
||||
total = 0
|
||||
marker = "loki-outage-" + uuid4().hex
|
||||
dropped_trace_id, _, drop_carrier = trace_headers()
|
||||
with stopped("loki"):
|
||||
stopped_at = now()
|
||||
written = c.call("POST", message_path, 201, actor=actor, body={"text": marker}, schema="Message",
|
||||
headers={**drop_carrier, "Idempotency-Key": uuid4().hex})["json"]
|
||||
deadline = time.monotonic() + 30
|
||||
next_sample = time.monotonic()
|
||||
while time.monotonic() < deadline:
|
||||
c.message(actor, chat, "synthetic Loki outage load")
|
||||
total += 1
|
||||
if time.monotonic() >= next_sample:
|
||||
timeline.append(sample())
|
||||
next_sample = time.monotonic() + 3
|
||||
time.sleep(0.12)
|
||||
timeline.append(sample())
|
||||
restarted_at = now()
|
||||
page = c.call("GET", message_path + "?limit=100", actor=actor, schema="MessagePage")["json"]
|
||||
check(any(msg["id"] == written["id"] for msg in page["items"]), "message written during Loki outage disappeared")
|
||||
|
||||
wait_for(lambda: g.logs(dropped_trace_id) is not None, "Loki query endpoint", timeout=70)
|
||||
wait_for(lambda: exporter("queue_size") == 0, "log queue drain", timeout=50)
|
||||
trace_id, _, carrier = trace_headers()
|
||||
probe = c.call("POST", message_path, 201, actor=actor, body={"text": marker},
|
||||
schema="Message", headers={**carrier, "Idempotency-Key": uuid4().hex})
|
||||
wait_for(lambda: g.logs(trace_id), "post-outage logs", timeout=35)
|
||||
wait_for(lambda: exporter("sent_log_records") > timeline[-1]["sent"], "post-outage Prometheus scrape")
|
||||
timeline.append(sample())
|
||||
before, after = timeline[0], timeline[-1]
|
||||
estimated_missing = round((after["accepted"] - before["accepted"]) - (after["sent"] - before["sent"]))
|
||||
check(all(0 <= x["queue"] <= x["capacity"] == 8 for x in timeline), "collector queue exceeded its configured bound")
|
||||
check(max(s["rss_bytes"] for s in timeline) < 256 * 1024**2, "collector RSS exceeded its budget")
|
||||
check(collector_started_at() == collector_start, "collector restarted during the outage")
|
||||
check(estimated_missing > 0 and not g.logs(dropped_trace_id) and g.spans(dropped_trace_id),
|
||||
"collector log loss during the outage was not measurable")
|
||||
timeline_summary = {"writes_201_during_outage": total + 1, "persisted_during_outage": True,
|
||||
"probe_201_after_recovery": probe["status"], "resumed_trace_id": trace_id,
|
||||
"dropped_log_trace_id": dropped_trace_id, "estimated_lost_log_records": estimated_missing,
|
||||
"collector_started_at": collector_start}
|
||||
return {"stopped_at": stopped_at, "restarted_at": restarted_at, "timeline": timeline, **timeline_summary}
|
||||
|
||||
|
||||
def verify_history(g, trace_id):
|
||||
print("Проверяем, что Loki, Prometheus и Tempo сохранили историю", flush=True)
|
||||
check(bool(g.logs(trace_id)), "logs written before the Loki restart were lost")
|
||||
compose("restart", "prometheus", "tempo")
|
||||
|
||||
def history():
|
||||
try:
|
||||
alerts = g.source("prometheus", "/api/v1/query",
|
||||
query='max_over_time(ALERTS{alertstate="firing"}[15m])')["data"]["result"]
|
||||
names = sorted(row["metric"]["alertname"] for row in alerts)
|
||||
traces = g.spans(trace_id)
|
||||
if {"MessengerHighErrorRate", "MessengerQueueLag"}.issubset(names) and traces:
|
||||
return {"retained_trace_id": trace_id, "retained_spans": len(traces), "retained_alerts": names,
|
||||
"retained_logs": len(g.logs(trace_id))}
|
||||
return None
|
||||
except HTTPError as error:
|
||||
if error.code in (502, 503):
|
||||
return None
|
||||
raise
|
||||
|
||||
return wait_for(history, "telemetry history after storage restart", timeout=70)
|
||||
|
||||
|
||||
def verify_metrics(g):
|
||||
required = {
|
||||
"messenger_http_requests_total", "messenger_http_request_duration_seconds_bucket",
|
||||
"messenger_job_attempts_total", "messenger_job_processing_duration_seconds_bucket",
|
||||
"messenger_attachment_time_to_ready_seconds_bucket", "messenger_queue_depth",
|
||||
"messenger_queue_oldest_age_seconds", "messenger_db_pool_used", "messenger_db_pool_waiting",
|
||||
"messenger_db_pool_capacity", "messenger_worker_busy", "messenger_worker_capacity",
|
||||
"messenger_process_cpu_time_seconds_total", "messenger_process_memory_rss_bytes",
|
||||
}
|
||||
series = g.source("prometheus", "/api/v1/series", **{"match[]": '{__name__=~"messenger_.+"}'})["data"]
|
||||
check(required.issubset({entry["__name__"] for entry in series}), "missing dashboard metric series")
|
||||
forbidden = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "filename", "url", "text"}
|
||||
check(all(not forbidden.intersection(entry) for entry in series), "private or high-cardinality metric label")
|
||||
requests = [entry for entry in series if entry["__name__"] == "messenger_http_requests_total"]
|
||||
instances = {entry["service_instance_id"] for entry in requests
|
||||
if entry.get("service_name") == "messenger-api" and entry.get("deployment_environment_name") == "lab"}
|
||||
check(len(instances) >= 2, "HTTP metric series should cover at least two API replicas")
|
||||
values = {}
|
||||
metrics = {
|
||||
"http": "messenger_http_request_duration_seconds_bucket",
|
||||
"worker": "messenger_job_processing_duration_seconds_bucket",
|
||||
"time_to_ready": "messenger_attachment_time_to_ready_seconds_bucket",
|
||||
}
|
||||
for name, metric in metrics.items():
|
||||
values[name] = {}
|
||||
for q in (0.5, 0.95, 0.99):
|
||||
value = g.scalar(f"histogram_quantile({q}, sum by (le) (rate({metric}[10m])))")
|
||||
check(value is not None, "missing percentile for " + metric)
|
||||
values[name][f"p{int(100 * q)}"] = value
|
||||
return {"prometheus_series": len(series), "api_instances": sorted(instances), "percentile_seconds": values,
|
||||
"sli_ratio30m": g.scalar("messenger:api_availability:ratio30m")}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
||||
parser.add_argument("--output", default=str(ROOT / "evidence/lab6-observability.json"))
|
||||
args = parser.parse_args()
|
||||
c, g = Client(args.base_url), Grafana(args.grafana_url)
|
||||
dashboard = g.get("/api/dashboards/uid/messenger-lab6")["dashboard"]
|
||||
wait_for(lambda: g.scalar("max(messenger_queue_depth)", optional=True) is not None,
|
||||
"queue metrics in Prometheus")
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
queue = verify_queue(c, g, actor, chat)
|
||||
db = verify_db(c, g, actor, chat, path)
|
||||
outage_chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
|
||||
body={"title": "Loki outage", "member_ids": [actor["id"]]})["json"]
|
||||
loki = verify_loki(c, g, actor, outage_chat, f"/api/v1/chats/{outage_chat['id']}/messages")
|
||||
metrics = verify_metrics(g)
|
||||
history = verify_history(g, queue["trace_id"])
|
||||
summary = {"dashboard": dashboard["title"], "panels": len(dashboard["panels"]), "at": now(),
|
||||
"queue_and_retry": queue, "postgres_lock": db, "loki_outage": loki, "metrics": metrics,
|
||||
"storage_history": history}
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS alerts, retry, log correlation and bounded Collector queue: {output}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user