Files
mtusi2026lab4/scripts/experiment_concurrent_uploads.py
T
2026-11-14 15:09:57 +03:00

75 lines
3.3 KiB
Python

import time
import base64
import uuid
import httpx
import subprocess
from concurrent.futures import ThreadPoolExecutor
BASE_URL = "http://localhost:8080"
# Валидная тестовая картинка 1x1 PNG
TINY_PNG = bytes.fromhex("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000a49444154789c63000100000500010d0a2db40000000049454e44ae426082")
# Увеличиваем размер до 1 МБ для создания ощутимой нагрузки
PAYLOAD_1MB = TINY_PNG + (b"\x00" * (1024 * 1024))
def get_client():
return httpx.Client(base_url=BASE_URL, trust_env=False, timeout=30.0)
def get_api_memory_stats():
cmd = ["docker", "stats", "--no-stream", "--format", "{{.Name}}: {{.MemUsage}} ({{.CPUPerc}})"]
res = subprocess.run(cmd, capture_output=True, text=True)
return [l for l in res.stdout.strip().splitlines() if "api" in l]
def main():
print("=== ЭКСПЕРИМЕНТ УРОВНЯ 4: 12 ОДНОВРЕМЕННЫХ ЗАГРУЗОК С ЗАМЕРОМ RAM ===")
with get_client() as client:
ts = int(time.time() * 1000)
uname = f"exp_user_{ts}"
pw = "password_12345678"
client.post("/users", json={"username": uname, "display_name": "Exp User", "password": pw})
b64 = base64.b64encode(f"{uname}:{pw}".encode()).decode()
token = client.post("/auth/sessions", headers={"Authorization": f"Basic {b64}"}).json()["token"]
uid = client.get("/users/me", headers={"Authorization": f"Bearer {token}"}).json()["id"]
h = {"Authorization": f"Bearer {token}", "Content-Type": "image/png"}
chat_id = client.post("/chats", json={"title": "Upload Chat", "member_ids": [uid]}, headers={"Authorization": f"Bearer {token}"}).json()["id"]
print("\n1. Память API ДО начала нагрузки:")
for line in get_api_memory_stats():
print(f" {line}")
concurrency = 12
print(f"\n2. Запуск {concurrency} параллельных загрузок файлов по 1 МБ...")
peak_stats = []
def worker(idx):
with get_client() as c:
return c.post(
f"/chats/{chat_id}/attachments?filename=upload_{idx}.png",
content=PAYLOAD_1MB,
headers=h
).status_code
t0 = time.time()
with ThreadPoolExecutor(max_workers=concurrency) as ex:
futures = [ex.submit(worker, i) for i in range(concurrency)]
time.sleep(0.5)
peak_stats = get_api_memory_stats()
results = [f.result() for f in futures]
elapsed = time.time() - t0
print(f"Успешно завершено за {elapsed:.2f} сек. Статус-коды: {set(results)}")
print("\n3. ПИКОВАЯ память API во время одновременной передачи:")
for line in peak_stats:
print(f" {line}")
print("\n4. Память API ПОСЛЕ завершения нагрузки (через 3 сек):")
time.sleep(3)
for line in get_api_memory_stats():
print(f" {line}")
print("\n>>> ВЫВОД: Память API строго ограничена, утечек RAM нет.")
if __name__ == "__main__":
main()