Files
mtusi2026lab2/student-tests/metrics_collector.py
T

218 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""Сбор метрик деградации и автоматическая генерация графиков.
Запуск:
# 1. Запустить сервер с лимитами (в отдельном терминале):
export MAX_USERS=100 MAX_CHATS=100 MAX_MESSAGES=1000 MAX_MESSAGES_PER_CHAT=100 MAX_REQUEST_QUEUE=50 MAX_MESSAGES_PER_SECOND=5
python -m uvicorn src.app:app --host 0.0.0.0 --port 8081
# 2. Запустить сборщик:
python student-tests/metrics_collector.py
# 3. CSV и графики появятся в папке metrics/
"""
import csv
import json
import os
import threading
import time
import urllib.request
import uuid
# matplotlib для построения графиков
import matplotlib
matplotlib.use("Agg") # неинтерактивный бэкенд (без GUI)
import matplotlib.pyplot as plt
BASE_URL = "http://localhost:8081"
METRICS_DIR = "metrics"
CSV_FILE = os.path.join(METRICS_DIR, "metrics_data.csv")
DURATION_SECONDS = 15
BURST_INTERVAL = 0.05 # отправлять сообщение каждые 50 мс = 20/сек
def request(method, path, body=None, headers=None):
h = {"Accept": "application/json"}
if body is not None:
raw = json.dumps(body, ensure_ascii=False).encode("utf-8")
h["Content-Type"] = "application/json"
else:
raw = None
h.update(headers or {})
req = urllib.request.Request(BASE_URL + path, data=raw, headers=h, method=method)
try:
resp = urllib.request.urlopen(req)
return json.loads(resp.read().decode()) if resp.read else None
except urllib.error.HTTPError as e:
return {"error": {"code": e.code}}
def get_stats():
"""Получить текущую статистику с сервера."""
req = urllib.request.Request(BASE_URL + "/stats", method="GET")
try:
resp = urllib.request.urlopen(req)
return json.loads(resp.read().decode())
except Exception:
return None
def ensure_dir(path):
"""Создать папку, если её нет."""
os.makedirs(path, exist_ok=True)
def plot_metrics(metrics_log):
"""Построить графики по собранным метрикам и сохранить в metrics/."""
ensure_dir(METRICS_DIR)
times = [m["time"] for m in metrics_log]
# Нормализуем время: начало = 0
t0 = times[0] if times else 0
times_norm = [t - t0 for t in times]
total_attempts = [m["total_attempts"] for m in metrics_log]
rate_limited = [m["rate_limited"] for m in metrics_log]
available_tokens = [m["available_tokens"] for m in metrics_log]
messages = [m["messages"] for m in metrics_log]
# График 1: Нагрузка и ошибки
fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set_xlabel("Время, сек")
ax1.set_ylabel("Количество")
ax1.plot(times_norm, total_attempts, "b-", label="Всего попыток", linewidth=2)
ax1.plot(times_norm, rate_limited, "r-", label="Отклонено (429)", linewidth=2)
ax1.plot(times_norm, messages, "g-", label="Создано сообщений", linewidth=2)
ax1.legend(loc="upper left")
ax1.grid(True, alpha=0.3)
ax1.set_title("Нагрузка и ошибки при rate limiting")
plt.tight_layout()
path1 = os.path.join(METRICS_DIR, "load_and_errors.png")
fig.savefig(path1, dpi=150)
plt.close(fig)
print(f" Сохранён: {path1}")
# График 2: Токены bucket
fig, ax = plt.subplots(figsize=(10, 5))
ax.set_xlabel("Время, сек")
ax.set_ylabel("Доступные токены")
ax.fill_between(times_norm, available_tokens, alpha=0.4, color="orange")
ax.plot(times_norm, available_tokens, "orange", linewidth=2, label="Токены в bucket")
ax.axhline(y=5, color="gray", linestyle="--", alpha=0.5, label="MAX_MESSAGES_PER_SECOND=5")
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_title("Состояние token bucket")
plt.tight_layout()
path2 = os.path.join(METRICS_DIR, "tokens.png")
fig.savefig(path2, dpi=150)
plt.close(fig)
print(f" Сохранён: {path2}")
# График 3: Соотношение успех/отказ (кумулятивное)
fig, ax = plt.subplots(figsize=(10, 5))
success = [total_attempts[i] - rate_limited[i] for i in range(len(total_attempts))]
ax.set_xlabel("Время, сек")
ax.set_ylabel("Количество")
ax.stackplot(
times_norm,
success,
rate_limited,
labels=["Успешно", "Отклонено (429)"],
colors=["#2ecc71", "#e74c3c"],
alpha=0.8,
)
ax.legend(loc="upper left")
ax.grid(True, alpha=0.3)
ax.set_title("Успешные запросы vs отказы (кумулятивно)")
plt.tight_layout()
path3 = os.path.join(METRICS_DIR, "success_vs_rejected.png")
fig.savefig(path3, dpi=150)
plt.close(fig)
print(f" Сохранён: {path3}")
return path1, path2, path3
def main():
print("=== Сбор метрик деградации и генерация графиков ===")
print(f"Результат: папка {METRICS_DIR}/")
print(f"Длительность: {DURATION_SECONDS} секунд")
print()
# Создаём пользователей и чат
alice = request("POST", "/api/v1/users", body={"username": "metrics_alice_" + uuid.uuid4().hex[:6], "display_name": "Alice"})
bob = request("POST", "/api/v1/users", body={"username": "metrics_bob_" + uuid.uuid4().hex[:6], "display_name": "Bob"})
chat = request(
"POST",
"/api/v1/chats",
body={"title": "Metrics", "member_ids": [alice["id"], bob["id"]]},
headers={"X-User-Id": alice["id"]},
)
chat_id = chat["id"]
# Поток для сбора метрик
metrics_log = []
stop_event = threading.Event()
def collector():
while not stop_event.is_set():
stats = get_stats()
if stats:
metrics_log.append({
"time": round(time.time(), 2),
"total_attempts": stats.get("metrics", {}).get("total_message_attempts", 0),
"rate_limited": stats.get("metrics", {}).get("rate_limited_count", 0),
"available_tokens": stats.get("rate_limit", {}).get("available_tokens", 0),
"messages": stats.get("messages", 0),
"requests_in_flight": stats.get("requests_in_flight", 0),
})
time.sleep(0.1)
collector_thread = threading.Thread(target=collector)
collector_thread.start()
# Нагрузка: отправляем сообщения быстрее лимита
print("Начинаем нагрузку...")
start = time.time()
msg_count = 0
while time.time() - start < DURATION_SECONDS:
request(
"POST",
f"/api/v1/chats/{chat_id}/messages",
body={"text": f"msg{msg_count}"},
headers={"X-User-Id": alice["id"]},
)
msg_count += 1
time.sleep(BURST_INTERVAL)
print(f"Отправлено {msg_count} сообщений. Ждём завершения сбора...")
time.sleep(2) # даём время собрать метрики после нагрузки
stop_event.set()
collector_thread.join()
# Сохраняем CSV
ensure_dir(METRICS_DIR)
with open(CSV_FILE, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=[
"time", "total_attempts", "rate_limited", "available_tokens",
"messages", "requests_in_flight",
])
writer.writeheader()
writer.writerows(metrics_log)
print(f"\nСохранено {len(metrics_log)} записей в {CSV_FILE}")
# Строим графики
print("\nСтроим графики...")
paths = plot_metrics(metrics_log)
print("\n=== ГОТОВО ===")
print(f"Папка с графиками: {METRICS_DIR}/")
for p in paths:
print(f" - {p}")
print("\nЭти файлы можно вставить в REPORT.md как доказательства работы rate limiting.")
if __name__ == "__main__":
main()