308 lines
17 KiB
Python
308 lines
17 KiB
Python
"""lab6, уровень 4: контролируемые инциденты → alerts firing/resolved → диагностика по telemetry.
|
||
|
||
Запуск из корня репозитория (стенд поднят, пароль Grafana в .env):
|
||
python student-tests/incidents.py # все три сценария, ~12 минут
|
||
python student-tests/incidents.py --scenario worker # только один
|
||
Сценарии:
|
||
worker — остановить worker, загрузить файлы: растёт возраст старейшей job →
|
||
AttachmentQueueLagGrowing firing; запустить worker: backlog разобран → resolved.
|
||
db — заблокировать таблицу messages (LOCK ... ACCESS EXCLUSIVE) под нагрузкой:
|
||
запросы ждут statement_timeout 5 s → 503 → ApiHighErrorRate firing.
|
||
По trace видно, что время съел DB span (а не код handler). Снять блокировку → resolved.
|
||
telemetry — остановить Tempo и Loki, затем сам Collector: API продолжает отвечать без 5xx,
|
||
RAM Collector/API ограничена, потери считаются в otelcol_exporter_send_failed_*.
|
||
Docker-команды можно заменить файлом --hooks-file (JSON: имя → argv) для стенда без Docker.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
from common import SAMPLE_PNG, Api, Report, upload, wait_ready # noqa: E402
|
||
from telem import Telemetry, add_args, new_traceparent # noqa: E402
|
||
|
||
ROOT = Path(__file__).resolve().parent.parent
|
||
C = ["docker", "compose", "--env-file", ".env"]
|
||
PSQL = 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -v ON_ERROR_STOP=1 -qAt -c "$1"'
|
||
HOOKS = {
|
||
"stop_worker": C + ["stop", "worker"],
|
||
"start_worker": C + ["start", "worker"],
|
||
"psql": C + ["exec", "-T", "postgres", "sh", "-c", PSQL, "sh"],
|
||
"stop_backends": C + ["stop", "tempo", "loki"],
|
||
"start_backends": C + ["start", "tempo", "loki"],
|
||
"stop_collector": C + ["stop", "otel-collector"],
|
||
"start_collector": C + ["start", "otel-collector"],
|
||
"mem": ["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
|
||
}
|
||
LOCK_SQL = "BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(%d); COMMIT;"
|
||
UNLOCK_SQL = ("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity "
|
||
"WHERE query LIKE '%LOCK TABLE messages%' AND pid <> pg_backend_pid()")
|
||
|
||
|
||
def sh(name: str, *args: str, check: bool = True) -> str:
|
||
out = subprocess.run(HOOKS[name] + list(args), cwd=ROOT, capture_output=True, text=True)
|
||
if check and out.returncode != 0:
|
||
raise RuntimeError(f"{name}: {out.stderr.strip()[-300:]}")
|
||
return out.stdout
|
||
|
||
|
||
def mem_mib(pattern: str) -> dict:
|
||
"""RSS контейнеров/процессов по `docker stats` (имя → MiB)."""
|
||
res = {}
|
||
for line in sh("mem", check=False).splitlines():
|
||
parts = line.split()
|
||
if len(parts) >= 2 and re.search(pattern, parts[0]):
|
||
m = re.match(r"([\d.]+)\s*([KMG]i?B)", parts[1])
|
||
if m:
|
||
res[parts[0]] = float(m.group(1)) * {"KiB": 1 / 1024, "MiB": 1, "GiB": 1024,
|
||
"KB": 1 / 1000, "MB": 1, "GB": 1000}.get(m.group(2), 1)
|
||
return res
|
||
|
||
|
||
class Load:
|
||
"""Фоновая нагрузка на чтение/запись сообщений; считает коды и latency."""
|
||
|
||
def __init__(self, api: Api, user: dict, chat_id: str, threads: int = 6, pause: float = 0.2):
|
||
self.api, self.user, self.chat, self.pause = api, user, chat_id, pause
|
||
self.stop = threading.Event()
|
||
self.lock = threading.Lock()
|
||
self.codes: dict[int, int] = {}
|
||
self.lat: list[float] = []
|
||
self.ts = [threading.Thread(target=self.run, args=(i,), daemon=True) for i in range(threads)]
|
||
|
||
def run(self, i: int):
|
||
while not self.stop.is_set():
|
||
t = time.monotonic()
|
||
if i % 3 == 2:
|
||
st, _, _ = self.api.call("POST", f"/api/v1/chats/{self.chat}/messages",
|
||
{"text": "load"}, token=self.user["token"], timeout=15)
|
||
else:
|
||
st, _, _ = self.api.call("GET", f"/api/v1/chats/{self.chat}/messages?limit=20",
|
||
token=self.user["token"], timeout=15)
|
||
with self.lock:
|
||
self.codes[st] = self.codes.get(st, 0) + 1
|
||
self.lat.append(time.monotonic() - t)
|
||
time.sleep(self.pause)
|
||
|
||
def start(self):
|
||
for t in self.ts:
|
||
t.start()
|
||
return self
|
||
|
||
def snapshot(self, reset: bool = False):
|
||
with self.lock:
|
||
codes, lat = dict(self.codes), sorted(self.lat)
|
||
if reset:
|
||
self.codes, self.lat = {}, []
|
||
p = (lambda q: lat[min(len(lat) - 1, int(q * len(lat)))] if lat else 0)
|
||
return codes, sum(codes.values()), p(0.5), p(0.95)
|
||
|
||
def finish(self):
|
||
self.stop.set()
|
||
for t in self.ts:
|
||
t.join(20)
|
||
|
||
|
||
def setup(api: Api):
|
||
u = api.new_user("inc")
|
||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "incident", "member_ids": [u["id"]]}, token=u["token"])
|
||
assert st == 201, (st, chat)
|
||
return u, chat["id"]
|
||
|
||
|
||
def ticker(label: str):
|
||
last = {"s": None, "t": time.monotonic()}
|
||
|
||
def tick(state):
|
||
if state != last["s"]:
|
||
print(f" {time.monotonic() - last['t']:6.1f}s {label}: {state}")
|
||
last["s"] = state
|
||
return tick
|
||
|
||
|
||
# ============================================================================ worker
|
||
def scenario_worker(api: Api, tel: Telemetry, rep: Report):
|
||
print("== инцидент 1: worker остановлен → растёт возраст задач ==")
|
||
u, chat = setup(api)
|
||
rep.check(tel.wait_alert("AttachmentQueueLagGrowing", "inactive", 180) is not None,
|
||
"до инцидента AttachmentQueueLagGrowing inactive")
|
||
sh("stop_worker")
|
||
t0 = time.monotonic()
|
||
ids = []
|
||
for i in range(3):
|
||
st, att, _ = upload(api, u["token"], chat, SAMPLE_PNG, f"inc-{i}.png")
|
||
ids.append(att["id"] if st == 202 else None)
|
||
rep.check(all(ids), "worker остановлен, upload всё равно 202 queued ×3")
|
||
fired = tel.wait_alert("AttachmentQueueLagGrowing", "firing", 240, on_tick=ticker("AttachmentQueueLagGrowing"))
|
||
age = tel.scalar("max(messenger:queue_oldest_age_seconds:max)", 0)
|
||
depth = tel.scalar('sum(max by (state) (messenger_queue_depth{state=~"queued|processing"}))', 0)
|
||
rep.check(fired is not None, f"AttachmentQueueLagGrowing → firing через {time.monotonic() - t0:.0f}s "
|
||
f"после остановки (oldest age {age:.0f}s, depth {depth:.0f})")
|
||
busy = tel.query("sum(messenger_worker_busy)")
|
||
print(f" диагностика: worker_busy={busy[0]['value'][1] if busy else 'нет данных'}, "
|
||
f"depth queued+processing={depth:.0f} → задачи есть, обрабатывать некому")
|
||
sh("start_worker")
|
||
t1 = time.monotonic()
|
||
ready = [wait_ready(api, u["token"], a, 120).get("status") for a in ids]
|
||
rep.check(ready == ["ready"] * 3, f"после старта worker backlog разобран за {time.monotonic() - t1:.0f}s: {ready}")
|
||
res = tel.wait_alert("AttachmentQueueLagGrowing", "inactive", 180, on_tick=ticker("AttachmentQueueLagGrowing"))
|
||
rep.check(res is not None, f"AttachmentQueueLagGrowing → resolved через {time.monotonic() - t1:.0f}s после старта worker")
|
||
age2 = tel.scalar("max(messenger:queue_oldest_age_seconds:max)", -1)
|
||
rep.check(age2 is not None and age2 < 60, f"oldest age после восстановления: {age2:.0f}s")
|
||
|
||
|
||
# ============================================================================ db
|
||
def scenario_db(api: Api, tel: Telemetry, rep: Report):
|
||
print("== инцидент 2: БД медленная (LOCK messages) → 503 → error rate ==")
|
||
u, chat = setup(api)
|
||
load = Load(api, u, chat).start()
|
||
time.sleep(20)
|
||
codes, n, p50, p95 = load.snapshot(reset=True)
|
||
rep.check(n > 0 and not any(c >= 500 for c in codes), f"фон до инцидента: {n} запросов {codes}, p95 {p95*1000:.0f}ms")
|
||
rep.check(tel.wait_alert("ApiHighErrorRate", "inactive", 180) is not None,
|
||
"до инцидента ApiHighErrorRate inactive")
|
||
t_lock = time.time()
|
||
locker = subprocess.Popen(HOOKS["psql"] + [LOCK_SQL % 300], cwd=ROOT,
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||
t0 = time.monotonic()
|
||
fired = tel.wait_alert("ApiHighErrorRate", "firing", 240, on_tick=ticker("ApiHighErrorRate"))
|
||
ratio = tel.scalar("messenger:http_errors:ratio1m", 0)
|
||
codes, n, p50, p95 = load.snapshot(reset=True)
|
||
rep.check(fired is not None, f"ApiHighErrorRate → firing через {time.monotonic() - t0:.0f}s "
|
||
f"(доля 5xx за 1m = {ratio:.0%}; клиент: {codes}, p50 {p50:.1f}s)")
|
||
waiting = tel.scalar("max(messenger_db_pool_waiting)", 0)
|
||
used = tel.scalar('max(messenger_db_pool_connections{state="used"})', 0)
|
||
|
||
# --- диагностика по trace: где время ошибочного запроса
|
||
since = int(time.time() - t_lock) + 30
|
||
found = tel.search('{ resource.service.name = "messenger-api" && span.http.response.status_code = 503 }',
|
||
since_s=since, limit=5)
|
||
rep.check(bool(found), f"Tempo: найдено {len(found)} trace с 503 за время инцидента")
|
||
if found:
|
||
spans = tel.trace(found[0]["traceID"])
|
||
server = next(s for s in spans if s["kind"] == "SPAN_KIND_SERVER")
|
||
dbs = [s for s in spans if s["attrs"].get("db.system") == "postgresql"]
|
||
slow = max(dbs, key=lambda s: s["ms"]) if dbs else None
|
||
share = sum(s["ms"] for s in dbs) / server["ms"] if server["ms"] else 0
|
||
if slow:
|
||
print(f" trace {found[0]['traceID'][:16]}…: {server['name']} {server['ms']:.0f}ms; "
|
||
f"самый долгий DB span «{slow['name']}» {slow['ms']:.0f}ms status={slow['status']}; "
|
||
f"доля DB {share:.0%}; события {slow['events']}")
|
||
rep.check(bool(slow) and slow["ms"] >= 4000 and share >= 0.8,
|
||
"время ошибки — в DB span (≈ statement_timeout 5 s), handler сам по себе быстрый")
|
||
logs = tel.logs('{service_name="messenger-api"} | event="db.unavailable"', since_s=since, limit=50)
|
||
kinds = sorted({l.get("error_type") or l.get("error.type") or "?" for l in logs})
|
||
rep.check(bool(logs), f"Loki: {len(logs)} записей db.unavailable, error.type={kinds}")
|
||
print(f" DB pool: used max={used:.0f}, waiting max={waiting:.0f}")
|
||
|
||
killed = sh("psql", UNLOCK_SQL, check=False).strip()
|
||
print(f" блокировка снята: pg_terminate_backend → {killed or '?'} сессий")
|
||
locker.wait(30)
|
||
t1 = time.monotonic()
|
||
res = tel.wait_alert("ApiHighErrorRate", "inactive", 240, on_tick=ticker("ApiHighErrorRate"))
|
||
codes, n, p50, p95 = load.snapshot(reset=True)
|
||
rep.check(res is not None, f"ApiHighErrorRate → resolved через {time.monotonic() - t1:.0f}s после снятия блокировки")
|
||
time.sleep(10)
|
||
codes, n, p50, p95 = load.snapshot(reset=True)
|
||
load.finish()
|
||
rep.check(n > 0 and not any(c >= 500 for c in codes), f"после восстановления: {n} запросов {codes}, p95 {p95*1000:.0f}ms")
|
||
|
||
|
||
# ============================================================================ telemetry
|
||
def scenario_telemetry(api: Api, tel: Telemetry, rep: Report, outage: int):
|
||
print("== инцидент 3: хранилища telemetry и Collector недоступны → API работает ==")
|
||
u, chat = setup(api)
|
||
load = Load(api, u, chat, threads=3, pause=0.3).start()
|
||
time.sleep(15)
|
||
_, n0, _, p95_0 = load.snapshot(reset=True)
|
||
api_mem0 = mem_mib(r"api")
|
||
sent0 = tel.scalar('sum(otelcol_exporter_send_failed_spans_total) + sum(otelcol_exporter_send_failed_log_records_total)', 0)
|
||
print(f" до: {n0} запросов, p95 {p95_0*1000:.0f}ms; RAM API {api_mem0}")
|
||
|
||
tid_lost, tp = new_traceparent()
|
||
sh("stop_backends")
|
||
t0 = time.monotonic()
|
||
api.call("GET", "/api/v1/users/me", token=u["token"], headers={"traceparent": tp})
|
||
rss, qmax = [], []
|
||
while time.monotonic() - t0 < outage:
|
||
rss.append(tel.scalar('max(otelcol_process_memory_rss{job="otel-collector"})', 0) / 2**20)
|
||
qmax.append(tel.scalar('max(otelcol_exporter_queue_size{exporter=~"otlp/tempo|otlphttp/loki"})', 0))
|
||
time.sleep(10)
|
||
cap = tel.scalar('max(otelcol_exporter_queue_capacity{exporter="otlp/tempo"})', 0)
|
||
failed = tel.scalar('sum(otelcol_exporter_send_failed_spans_total) + sum(otelcol_exporter_send_failed_log_records_total)', 0) - sent0
|
||
enq = tel.scalar('sum({__name__=~"otelcol_exporter_enqueue_failed_(spans|log_records)(_total)?"})', 0)
|
||
codes, n, p50, p95 = load.snapshot(reset=True)
|
||
rep.check(n > 0 and not any(c >= 500 for c in codes),
|
||
f"Tempo+Loki остановлены {outage}s: API {n} запросов {codes}, p95 {p95*1000:.0f}ms (до: {p95_0*1000:.0f}ms)")
|
||
rep.check(max(rss or [0]) < 256, f"RSS Collector max {max(rss or [0]):.0f} MiB (лимит контейнера 256, memory_limiter 160)")
|
||
rep.check(max(qmax or [0]) <= max(cap, 200), f"очередь exporter max {max(qmax or [0]):.0f} ≤ capacity {cap:.0f}")
|
||
rep.check(failed > 0 or enq > 0, f"потери учтены: send_failed +{failed:.0f}, enqueue_failed {enq:.0f}")
|
||
alert = tel.alert_state("TelemetryExportFailing")
|
||
print(f" TelemetryExportFailing: {alert}")
|
||
|
||
sh("stop_collector")
|
||
t1 = time.monotonic()
|
||
time.sleep(40)
|
||
codes, n, p50, p95 = load.snapshot(reset=True)
|
||
api_mem1 = mem_mib(r"api")
|
||
rep.check(n > 0 and not any(c >= 500 for c in codes),
|
||
f"Collector остановлен 40s: API {n} запросов {codes}, p95 {p95*1000:.0f}ms")
|
||
grow = [api_mem1.get(k, 0) - v for k, v in api_mem0.items() if k in api_mem1]
|
||
rep.check(not grow or max(grow) < 64, f"RAM API без Collector: {api_mem1} (рост ≤ {max(grow or [0]):.0f} MiB, очереди SDK ограничены)")
|
||
|
||
sh("start_backends")
|
||
sh("start_collector")
|
||
t2 = time.monotonic()
|
||
load.finish()
|
||
tid, tp = new_traceparent()
|
||
ok = False
|
||
for _ in range(30):
|
||
api.call("GET", "/api/v1/users/me", token=u["token"], headers={"traceparent": tp})
|
||
time.sleep(3)
|
||
if tel.trace(tid) and tel.logs(f'{{service_name="messenger-api"}} | trace_id="{tid}"', since_s=300):
|
||
ok = True
|
||
break
|
||
rep.check(ok, f"после запуска: новый trace и лог снова видны через {time.monotonic() - t2:.0f}s")
|
||
lost = not tel.trace(tid_lost)
|
||
print(f" trace запроса во время простоя Tempo {'потерян (ожидаемо, retry 60s исчерпан)' if lost else 'доставлен из очереди'}")
|
||
print(f" [весь сценарий {time.monotonic() - t0 + 15:.0f}s, Collector простаивал {t2 - t1:.0f}s]")
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--base-url", default="https://localhost:8443")
|
||
ap.add_argument("--scenario", choices=["all", "worker", "db", "telemetry"], default="all")
|
||
ap.add_argument("--outage", type=int, default=90, help="сколько секунд Tempo+Loki недоступны")
|
||
ap.add_argument("--hooks-file", help="JSON {hook: argv} вместо docker compose")
|
||
add_args(ap)
|
||
args = ap.parse_args()
|
||
if args.hooks_file:
|
||
HOOKS.update(json.loads(Path(args.hooks_file).read_text(encoding="utf-8")))
|
||
api, tel, rep = Api(args.base_url), Telemetry(args), Report()
|
||
for name, fn in (("worker", scenario_worker), ("db", scenario_db), ("telemetry", scenario_telemetry)):
|
||
if args.scenario in ("all", name):
|
||
t = time.monotonic()
|
||
try:
|
||
fn(api, tel, rep, args.outage) if name == "telemetry" else fn(api, tel, rep)
|
||
finally:
|
||
if name == "worker":
|
||
sh("start_worker", check=False)
|
||
if name == "db":
|
||
sh("psql", UNLOCK_SQL, check=False)
|
||
if name == "telemetry":
|
||
sh("start_backends", check=False)
|
||
sh("start_collector", check=False)
|
||
print(f" [{name}: {time.monotonic() - t:.0f}s]")
|
||
rep.finish()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|