#!/usr/bin/env python3 """Эксперимент с памятью: >=10 одновременных загрузок настоящих PNG. Гипотеза: API не буферизует тело целиком в RAM, поэтому пик RSS не растёт пропорционально сумме размеров всех одновременных файлов. Скрипт измеряет память контейнеров API через `docker stats`, а не память клиента. Требуется Pillow для генерации большого валидного PNG (это инструмент эксперимента, а не рантайм API). Запуск: python3 student-tests/upload_experiment.py --concurrency 12 Docker CLI должен видеть тот же стенд (DOCKER_HOST/DOCKER_CONFIG). """ from __future__ import annotations import argparse import json import os import re import statistics import subprocess import sys import threading import time from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path from urllib.parse import quote ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure # noqa: E402 UNITS = {"B": 1, "KiB": 1024, "MiB": 1024**2, "GiB": 1024**3, "TiB": 1024**4} def parse_bytes(value: str) -> int: match = re.match(r"\s*([\d.]+)\s*([A-Za-z]+)", value) if match is None: raise ValueError("unrecognized memory value: %r" % value) number, unit = match.group(1), match.group(2) return int(float(number) * UNITS[unit]) def api_containers() -> list[str]: result = subprocess.run( ["docker", "ps", "--no-trunc", "--format", "{{.ID}} {{.Names}}"], check=True, capture_output=True, text=True, ) containers = [] for line in result.stdout.splitlines(): parts = line.split(maxsplit=1) if len(parts) == 2 and "lab4_api." in parts[1]: containers.append(parts[0]) return containers def api_memory(containers: list[str]) -> dict[str, int]: if not containers: return {} result = subprocess.run( ["docker", "stats", "--no-stream", "--no-trunc", "--format", "{{.ID}}\t{{.MemUsage}}"] + containers, check=True, capture_output=True, text=True, ) memory: dict[str, int] = {} for line in result.stdout.splitlines(): identifier, usage = line.split("\t", 1) memory[identifier] = parse_bytes(usage.split("/")[0]) return memory def make_png(path: Path, width: int = 1800, height: int = 1350) -> int: if path.exists() and path.stat().st_size <= 10_485_760: return path.stat().st_size from PIL import Image raw = os.urandom(width * height * 3) image = Image.frombytes("RGB", (width, height), raw) image.save(path, "PNG") size = path.stat().st_size if size > 10_485_760: raise SystemExit("generated PNG exceeds the contract limit: %d" % size) return size def percentile(values: list[float], fraction: float) -> float: if not values: return 0.0 ordered = sorted(values) index = min(len(ordered) - 1, max(0, int(round((len(ordered) - 1) * fraction)))) return ordered[index] def main() -> int: parser = argparse.ArgumentParser(description="Пик RAM API при одновременных загрузках") parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080")) parser.add_argument("--concurrency", type=int, default=12) parser.add_argument("--output", default="evidence/upload-memory.json") args = parser.parse_args() fixture = ROOT / "student-tests" / "fixtures" / "large.png" image = make_png(fixture) api = Client(args.base_url, None, timeout=30) alice, _bob, _eve, chat = api.bootstrap() containers = api_containers() if len(containers) < 2: raise SystemExit("expected >=2 lab4_api containers, saw %d" % len(containers)) stop = threading.Event() samples: list[dict] = [] def sampler() -> None: while not stop.is_set(): try: samples.append({"t": round(time.monotonic(), 3), "memory": api_memory(containers)}) except Exception as exc: # pragma: no cover - diagnostics only samples.append({"t": round(time.monotonic(), 3), "error": type(exc).__name__}) stop.wait(0.2) baseline = api_memory(containers) thread = threading.Thread(target=sampler, daemon=True) thread.start() started = time.monotonic() barrier = threading.Barrier(args.concurrency) results: list[dict] = [] def worker(_: int) -> None: local = Client(args.base_url, None, timeout=120) barrier.wait() began = time.monotonic() try: response = local.call( "POST", "/api/v1/chats/%s/attachments?filename=large.png" % chat["id"], 201, actor=alice, raw=fixture.read_bytes(), headers={"Content-Type": "image/png"}, schema="Attachment", ) results.append( { "status": response["status"], "seconds": round(time.monotonic() - began, 3), "instance": response["headers"].get("X-Instance-Id"), } ) except (Failure, OSError) as exc: results.append({"status": None, "seconds": round(time.monotonic() - began, 3), "error": str(exc)[:200]}) with ThreadPoolExecutor(max_workers=args.concurrency) as pool: list(pool.map(worker, range(args.concurrency))) elapsed = time.monotonic() - started time.sleep(0.5) stop.set() thread.join(timeout=5) time.sleep(0.5) after = api_memory(containers) peaks = {identifier: 0 for identifier in containers} for sample in samples: for identifier, value in (sample.get("memory") or {}).items(): peaks[identifier] = max(peaks.get(identifier, 0), value) successful = [item for item in results if item["status"] == 201] durations = [item["seconds"] for item in successful] report = { "measured_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), "base_url": args.base_url, "concurrency": args.concurrency, "image_bytes": image, "image_dimensions": [1800, 1350], "containers": containers, "baseline_rss_bytes": baseline, "peak_rss_bytes": peaks, "after_rss_bytes": after, "sum_peak_rss_bytes": sum(peaks.values()), "sum_baseline_rss_bytes": sum(baseline.values()), "peak_delta_bytes": sum(peaks.values()) - sum(baseline.values()), "successful": len(successful), "failed": len(results) - len(successful), "elapsed_seconds": round(elapsed, 3), "p50_seconds": round(statistics.median(durations), 3) if durations else None, "p95_seconds": round(percentile(durations, 0.95), 3) if durations else None, "instances": sorted({item.get("instance") for item in successful if item.get("instance")}), "samples": samples, "results": results, } output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8") print(json.dumps({key: value for key, value in report.items() if key not in ("samples", "results", "baseline_rss_bytes", "peak_rss_bytes", "after_rss_bytes")}, ensure_ascii=False, indent=2)) print("baseline_rss_bytes:", baseline) print("peak_rss_bytes:", peaks) print("evidence:", output) return 0 if len(successful) == args.concurrency else 1 if __name__ == "__main__": raise SystemExit(main())