This commit is contained in:
2026-11-08 00:33:25 +03:00
parent 20afc2c790
commit 3d5c6a6689
148 changed files with 21441 additions and 79 deletions
+126
View File
@@ -0,0 +1,126 @@
"""lab6, уровень 4, сценарий 3: хранилища телеметрии недоступны — API работает, память ограничена.
make telemetry-outage (= python student-tests/telemetry_outage.py) ~7 минут
1. фон: сообщения (3 потока) и загрузка картинки раз в 5 с;
2. docker compose stop tempo loki — на 3 минуты. Каждые 15 с: коды ответов API, RSS Collector,
очереди его exporter (пачки), неудачные отправки, состояние alert TelemetryExportFailing.
Ожидаем: все бизнес-запросы успешны, загрузки становятся ready, очередь растёт, но не выше ёмкости,
куча Collector ниже memory_limiter (400 МиБ), RSS ниже лимита контейнера (512 МиБ);
3. docker compose start tempo loki: очереди разгружаются, alert resolved. Данные, ждавшие в очереди
меньше 5 минут (retry max_elapsed_time), доезжают: трасса и лог загрузки, сделанной во время
отказа, находятся. Отброшенное (если очередь переполнилась) посчитано otelcol_exporter_send_failed_*;
4. docker compose stop otel-collector на 60 с: API работает (SDK отправляет в фоне и отбрасывает
не влезшее в очередь 2048 записей), RSS реплик API не растёт; после запуска телеметрия идёт снова.
"""
import time
import obs
import ops
from filegen import wait_status
from helpers import Client, check, run
from traffic import Traffic
RSS = 'max(otelcol_process_memory_rss_bytes)'
HEAP = 'max(otelcol_process_runtime_heap_alloc_bytes)'
QUEUE = 'sum by (exporter) (otelcol_exporter_queue_size)'
CAPACITY = 'max(otelcol_exporter_queue_capacity)'
FAILED = ('sum(otelcol_exporter_send_failed_spans_total) + sum(otelcol_exporter_send_failed_log_records_total)'
' + sum(otelcol_exporter_send_failed_metric_points_total)')
API_RSS = 'max(process_memory_usage_bytes{job="messenger-api"})'
MIB = 2 ** 20
def snapshot(started, traffic):
queues = {r["metric"].get("exporter", "?").split("/")[-1]: int(r["value"]) for r in obs.prom(QUEUE)}
rss, heap = obs.prom_value(RSS, 0) / MIB, obs.prom_value(HEAP, 0) / MIB
state = obs.alerts().get("TelemetryExportFailing", "inactive")
print(f" t={time.monotonic() - started:5.0f}s collector heap={heap:5.1f} rss={rss:6.1f} MiB queues={queues} "
f"send_failed_total={obs.prom_value(FAILED, 0):.0f} TelemetryExportFailing={state:<8} http={traffic.snapshot()}")
return max(rss, 0), heap, queues, state
def main():
api = Client(timeout=20)
alice, bob, _eve, chat = api.bootstrap()
traffic = Traffic(api, alice, chat, threads=3, pause=0.3, uploads_every=5).start()
started = time.monotonic()
capacity = obs.prom_value(CAPACITY, 0)
failed_before = obs.prom_value(FAILED, 0)
max_rss, max_heap, max_queue = 0.0, 0.0, 0
try:
time.sleep(15)
print(f"1. baseline (exporter queue capacity {capacity:.0f} batches, memory_limiter 400 MiB heap, "
"container limit 512 MiB):")
snapshot(started, traffic)
ops.stop("tempo", "loki")
stopped_at = time.monotonic() - started
print(f"2. t={stopped_at:.0f}s docker compose stop tempo loki (traces and logs stores)")
firing = None
while time.monotonic() - started - stopped_at < 180:
time.sleep(15)
rss, heap, queues, state = snapshot(started, traffic)
max_rss, max_heap = max(max_rss, rss), max(max_heap, heap)
max_queue = max([max_queue] + list(queues.values()))
if state == "firing" and firing is None:
firing = time.monotonic() - started
during = list(traffic.uploads)
check(during, "no uploads during the outage")
victim = during[-3][0]
ready = wait_status(api, alice, victim, ("ready",), seconds=60)
print(f" upload {victim} made during the outage -> {ready['status']} (business path unaffected)")
codes = traffic.snapshot()
bad = {k: v for k, v in codes.items() if not k.endswith(("201", "202"))}
check(not bad, f"business requests failed during the telemetry outage: {bad}")
check(max_heap < 400, f"collector heap {max_heap:.0f} MiB exceeded memory_limiter")
check(max_rss < 512, f"collector RSS {max_rss:.0f} MiB above the container limit")
check(max_queue <= capacity, "exporter queue above its capacity")
alert = f"firing at t={firing:.0f}s" if firing else "not firing yet"
print(f" during the outage: every business request succeeded {codes}; collector RSS max {max_rss:.0f} MiB "
f"(heap max {max_heap:.0f} MiB < 400 MiB limit); exporter queue max {max_queue} of {capacity:.0f} batches; "
f"TelemetryExportFailing {alert}")
finally:
ops.start("tempo", "loki")
started_at = time.monotonic() - started
print(f"3. t={started_at:.0f}s docker compose start tempo loki")
deadline = time.monotonic() + 300
while True:
time.sleep(15)
_rss, _heap, queues, state = snapshot(started, traffic)
if not any(queues.values()) and state == "inactive":
break
check(time.monotonic() < deadline, "queues did not drain / alert did not resolve")
print(f" queues drained and TelemetryExportFailing resolved at t={time.monotonic() - started:.0f}s")
lost = obs.prom_value(FAILED, 0) - failed_before
attachment_id, request_id = during[len(during) // 2]
logs = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"', seconds=120)
trace_id, _spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{attachment_id}" && kind = server }}',
seconds=120)
print(f" upload {attachment_id} from the middle of the outage: log (X-Request-Id {request_id}) and trace "
f"{trace_id} arrived after recovery (they waited in the collector queue); "
f"telemetry items dropped by exporters during the run: {lost:.0f}")
print("4. docker compose stop otel-collector for 60 s (the SDK cannot export at all)")
api_rss_before = obs.prom_value(API_RSS, 0) / MIB
before = traffic.snapshot()
ops.stop("otel-collector")
try:
time.sleep(60)
finally:
ops.start("otel-collector")
after = traffic.snapshot()
delta = {k: after.get(k, 0) - before.get(k, 0) for k in after}
bad = {k: v for k, v in delta.items() if v and not k.endswith(("201", "202"))}
check(not bad, f"business requests failed while the collector was down: {bad}")
time.sleep(30)
traffic.stop()
api_rss_after = obs.prom_value(API_RSS, 0) / MIB
print(f" API answered {delta} while the collector was down (no errors); API replica RSS "
f"{api_rss_before:.0f} -> {api_rss_after:.0f} MiB (SDK queues are bounded: 2048 records per signal)")
check(api_rss_after < api_rss_before + 60, "API memory grew while the collector was down")
print("PASS: telemetry stores and the collector down -> business API unaffected, bounded collector memory and "
"queues, delayed telemetry delivered after recovery, drops are counted")
if __name__ == "__main__":
run(main)