forked from mtusi2026/mtusi2026lab6
ЛР6
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
"""lab6, уровень 3: persistent volumes хранилищ телеметрии сохраняют историю после перезапуска.
|
||||
|
||||
make telemetry-persistence (= python student-tests/telemetry_persistence.py)
|
||||
|
||||
До перезапуска запоминаются: трасса последней загрузки (Tempo), лог запроса по X-Request-Id (Loki),
|
||||
значение HTTP-счётчика на момент 2 минуты назад (Prometheus). Затем
|
||||
docker compose restart prometheus loki tempo grafana (те же контейнеры и volumes promdata,
|
||||
lokidata, tempodata, grafanadata) — и те же данные находятся снова, dashboard по-прежнему импортирован.
|
||||
"""
|
||||
import time
|
||||
|
||||
import obs
|
||||
import ops
|
||||
from helpers import Client, check, idempotency, run
|
||||
|
||||
COUNTER = 'sum(http_server_request_duration_seconds_count{job="messenger-api"})'
|
||||
|
||||
|
||||
def wait_up(seconds=180):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
obs.prom("up")
|
||||
obs.loki('{service_name="messenger-api"}', minutes=1, limit=1)
|
||||
obs.tempo_search("{ kind = server }", limit=1, minutes=5)
|
||||
return
|
||||
except Exception: # хранилища ещё стартуют
|
||||
check(time.monotonic() < deadline, "telemetry stores did not come back")
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=20)
|
||||
alice, _bob, _eve, chat = api.bootstrap()
|
||||
att, _ = api.attachment(alice, chat)
|
||||
response = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, headers=idempotency(),
|
||||
body={"text": "до перезапуска хранилищ"})
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
log_before = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"')[-1]
|
||||
trace_id, spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{att["id"]}" && kind = server }}')
|
||||
at = time.time() - 120
|
||||
counter_before = obs.prom_value(COUNTER, at=at)
|
||||
check(counter_before is not None, "no HTTP counter 2 minutes ago: run make test first and wait 2 minutes")
|
||||
print(f"before: trace {trace_id} ({len(spans)} spans), log of X-Request-Id {request_id}, "
|
||||
f"HTTP requests counter at t-120s = {counter_before:.0f}")
|
||||
|
||||
ops.restart("prometheus", "loki", "tempo", "grafana")
|
||||
print("docker compose restart prometheus loki tempo grafana (same containers, volumes kept)")
|
||||
wait_up()
|
||||
|
||||
spans_after = obs.tempo_trace(trace_id)
|
||||
check(len(spans_after) == len(spans), f"trace changed after restart: {len(spans)} -> {len(spans_after)} spans")
|
||||
log_after = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"', seconds=90)[-1]
|
||||
check(log_after["line"] == log_before["line"], "log line changed after restart")
|
||||
counter_after = obs.prom_value(COUNTER, at=at)
|
||||
check(counter_after == counter_before, f"metric history changed: {counter_before} -> {counter_after}")
|
||||
print(f"after: trace {trace_id} — {len(spans_after)} spans; log found; counter at the same past moment "
|
||||
f"= {counter_after:.0f}")
|
||||
try:
|
||||
dashboard = obs.grafana("/api/dashboards/uid/messenger-lab6")
|
||||
print(f" Grafana: dashboard '{dashboard['dashboard']['title']}' still provisioned")
|
||||
except Exception as exc: # без Grafana (например, проверка только хранилищ) — не ошибка этой проверки
|
||||
print(f" Grafana not checked: {type(exc).__name__}")
|
||||
print("PASS: Prometheus, Loki and Tempo keep their history in volumes across a restart")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user