forked from mtusi2026/mtusi2026lab4
ЛР 4 - БПИ2302 - Щербацевич - на 4
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""10 параллельных загрузок и пик RSS API-реплик по docker stats."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
WORKERS = 10
|
||||
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
|
||||
def api_mem_mib() -> float:
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"],
|
||||
cwd=str(ROOT),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=20,
|
||||
)
|
||||
ids = [line.strip() for line in proc.stdout.splitlines() if line.strip()]
|
||||
if not ids:
|
||||
raise Failure("no api containers")
|
||||
stats = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", *ids],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=20,
|
||||
)
|
||||
if stats.returncode != 0:
|
||||
raise Failure("docker stats failed")
|
||||
peak = 0.0
|
||||
for line in stats.stdout.splitlines():
|
||||
used = line.split("/", 1)[0].strip()
|
||||
if used.endswith("GiB"):
|
||||
peak = max(peak, float(used[:-3].strip()) * 1024)
|
||||
elif used.endswith("MiB"):
|
||||
peak = max(peak, float(used[:-3].strip()))
|
||||
elif used.endswith("KiB"):
|
||||
peak = max(peak, float(used[:-3].strip()) / 1024)
|
||||
return peak
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(BASE, timeout=30)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
before = api_mem_mib()
|
||||
barrier = threading.Barrier(WORKERS)
|
||||
errors = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker(index: int) -> None:
|
||||
local = Client(BASE, timeout=30)
|
||||
try:
|
||||
barrier.wait(20)
|
||||
local.call(
|
||||
"POST",
|
||||
"/api/v1/chats/%s/attachments?filename=p%d.png" % (chat["id"], index),
|
||||
201,
|
||||
actor=alice,
|
||||
raw=SAMPLE,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
errors.append("%s: %s" % (type(exc).__name__, exc))
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(WORKERS)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
peak = before
|
||||
deadline = time.monotonic() + 30
|
||||
while any(thread.is_alive() for thread in threads) and time.monotonic() < deadline:
|
||||
peak = max(peak, api_mem_mib())
|
||||
time.sleep(0.4)
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
peak = max(peak, api_mem_mib())
|
||||
check(not errors, "concurrent uploads failed: " + "; ".join(errors[:3]))
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
(EVIDENCE / "upload_mem.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"workers": WORKERS,
|
||||
"rss_before_mib": round(before, 2),
|
||||
"rss_peak_mib": round(peak, 2),
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
print("PASS: %s concurrent uploads, peak RSS %.1f MiB" % (WORKERS, peak))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user