forked from mtusi2026/mtusi2026lab5
165 lines
9.6 KiB
Python
165 lines
9.6 KiB
Python
"""lab4 (с lab5 — с ответом 202): эксперимент — ≥10 одновременных загрузок и пик памяти реплик API.
|
||
|
||
make upload-memory (= python student-tests/upload_memory.py [--count 12])
|
||
|
||
Гипотеза: память реплики почти не растёт с числом одновременных загрузок, потому что
|
||
(1) тело читается кусками и в памяти держится не больше 1 МиБ на загрузку (остальное во временном
|
||
файле), (2) с lab5 API картинку не декодирует, а только проверяет структуру потоком (по 1 МиБ),
|
||
декодирует worker в отдельном процессе, (3) слишком большой файл отклоняется по Content-Length
|
||
и вообще не читается.
|
||
Если бы тела держались в памяти целиком, только на них ушло бы count × размер файла.
|
||
|
||
Методика:
|
||
1. обе реплики API перезапускаются (чистый счётчик пика памяти процесса);
|
||
2. создаются пользователи и чат (вход — Argon2id, это тоже попадает в базовую линию);
|
||
3. замер «до»: VmRSS и VmHWM (пик RSS процесса с момента старта) у PID 1 каждой реплики,
|
||
memory.peak cgroup (включает файловый кэш временных файлов);
|
||
4. профиль A: count одновременных загрузок PNG со случайными пикселями (8,8 МиБ, 1800×1700);
|
||
профиль B: count одновременных запросов, заявляющих 11 МиБ (ожидается 413 без чтения тела);
|
||
5. замер «после» и каждые ~0,5 с во время серии (docker exec, VmRSS).
|
||
Результат: evidence/upload-memory.json и таблица в REPORT.md (между метками upload-memory).
|
||
Ограничения: клиент и стенд на одной машине; VmHWM — пик за всё время процесса, поэтому реплики
|
||
перезапускаются перед замером; опрос раз в ~0,5 с может пропустить короткий пик (для этого VmHWM).
|
||
"""
|
||
import argparse
|
||
import concurrent.futures
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import threading
|
||
import time
|
||
from datetime import datetime, timezone
|
||
|
||
from filegen import png, raw_upload, wait_status
|
||
from helpers import ROOT, Client, check, run
|
||
from stand import compose_quiet, docker, wait_balanced
|
||
|
||
MIB = 1024 * 1024
|
||
PROBE = "grep -E '^(VmRSS|VmHWM)' /proc/1/status; cat /sys/fs/cgroup/memory.peak 2>/dev/null || echo 0"
|
||
|
||
|
||
def memory(container):
|
||
"""{'rss': МиБ, 'hwm': МиБ, 'cgroup_peak': МиБ} для PID 1 контейнера."""
|
||
text = docker("exec", container, "sh", "-c", PROBE, check_exit=False)
|
||
rss = re.search(r"VmRSS:\s+(\d+)", text)
|
||
hwm = re.search(r"VmHWM:\s+(\d+)", text)
|
||
last = text.strip().splitlines()[-1] if text.strip() else "0"
|
||
return {"rss": round(int(rss.group(1)) / 1024, 1) if rss else None,
|
||
"hwm": round(int(hwm.group(1)) / 1024, 1) if hwm else None,
|
||
"cgroup_peak": round(int(last) / MIB, 1) if last.isdigit() and int(last) else None}
|
||
|
||
|
||
class Poller(threading.Thread):
|
||
"""Во время серии опрашивает VmRSS всех реплик и запоминает максимум."""
|
||
|
||
def __init__(self, containers):
|
||
super().__init__(daemon=True)
|
||
self.containers, self.stop, self.max_rss = containers, threading.Event(), {c: 0.0 for c in containers}
|
||
|
||
def run(self):
|
||
while not self.stop.is_set():
|
||
for container in self.containers:
|
||
rss = memory(container)["rss"] or 0
|
||
self.max_rss[container] = max(self.max_rss[container], rss)
|
||
time.sleep(0.2)
|
||
|
||
|
||
def burst(name, count, task):
|
||
with concurrent.futures.ThreadPoolExecutor(count) as pool:
|
||
started = time.monotonic()
|
||
results = list(pool.map(task, range(count)))
|
||
took = time.monotonic() - started
|
||
print(f"{name}: {count} concurrent uploads in {took:.2f} s -> statuses {sorted(set(r[0] for r in results))}")
|
||
return results, round(took, 2)
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--count", type=int, default=12)
|
||
args = parser.parse_args()
|
||
check(args.count >= 10, "the experiment needs >= 10 concurrent uploads")
|
||
|
||
compose_quiet("restart", "api")
|
||
containers = wait_balanced(2)
|
||
api = Client(timeout=60)
|
||
alice, bob, _eve, chat = api.bootstrap()
|
||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=load.png"
|
||
images = [png(1800, 1700, noise=True) for _ in range(args.count)]
|
||
size = len(images[0])
|
||
print(f"replicas: {[c[:12] for c in containers]}; {args.count} files x {size / MIB:.1f} MiB "
|
||
f"(1800x1700, random pixels)")
|
||
before = {c: memory(c) for c in containers}
|
||
|
||
poller = Poller(containers)
|
||
poller.start()
|
||
|
||
def accepted(i):
|
||
reply = Client(timeout=60).call("POST", path, 202, actor=alice, raw=images[i],
|
||
headers={"Content-Type": "image/png"}, schema="Attachment")
|
||
att = reply["json"]
|
||
check(att["sha256"] == hashlib.sha256(images[i]).hexdigest(), "checksum mismatch")
|
||
return reply["status"], reply["headers"]["X-Instance-Id"], att["id"]
|
||
|
||
results_a, took_a = burst("A (accepted)", args.count, accepted)
|
||
after_a = {c: memory(c) for c in containers}
|
||
|
||
def rejected(_i):
|
||
# Заявлено 11 МиБ: сервер должен ответить 413 по заголовку, не читая и не буферизуя тело.
|
||
reply = raw_upload(path, alice["token"], b"", content_length=11 * MIB)
|
||
return (reply[0] if reply else None), None, None
|
||
|
||
results_b, took_b = burst("B (11 MiB, rejected)", args.count, rejected)
|
||
check(all(r[0] == 413 for r in results_b), "oversize uploads must get 413")
|
||
poller.stop.set()
|
||
poller.join()
|
||
after_b = {c: memory(c) for c in containers}
|
||
|
||
# Все файлы профиля A после обработки worker скачиваются вторым участником без изменений.
|
||
for (_s, _inst, att_id), data in zip(results_a, images):
|
||
wait_status(api, bob, att_id, seconds=180)
|
||
got = api.call("GET", f"/api/v1/attachments/{att_id}/content", actor=bob)["bytes"]
|
||
check(got == data, "downloaded file differs")
|
||
|
||
rows = []
|
||
for c in containers:
|
||
served = sum(1 for r in results_a if c.startswith(r[1]))
|
||
rows.append({"replica": c[:12], "uploads_served": served,
|
||
"rss_before_mib": before[c]["rss"], "hwm_before_mib": before[c]["hwm"],
|
||
"hwm_after_a_mib": after_a[c]["hwm"], "hwm_after_b_mib": after_b[c]["hwm"],
|
||
"max_rss_polled_mib": poller.max_rss[c],
|
||
"cgroup_peak_after_mib": after_b[c]["cgroup_peak"],
|
||
"peak_growth_mib": round((after_a[c]["hwm"] or 0) - (before[c]["hwm"] or 0), 1),
|
||
"growth_from_b_mib": round((after_b[c]["hwm"] or 0) - (after_a[c]["hwm"] or 0), 1),
|
||
"bodies_if_in_memory_mib": round(served * size / MIB, 1)})
|
||
result = {"date": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "count": args.count,
|
||
"file_mib": round(size / MIB, 2), "profile_a_seconds": took_a, "profile_b_seconds": took_b,
|
||
"limits": {"api_memory": "512M", "spool_in_memory": "1 MiB per upload", "structure_checks_concurrency": 2,
|
||
"malloc_arena_max": 2},
|
||
"replicas": rows}
|
||
(ROOT / "evidence" / "upload-memory.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
|
||
|
||
table = ["| Реплика | Загрузок A | RSS до, МиБ | Пик RSS до → после A, МиБ | Рост пика, МиБ "
|
||
"| Тела целиком в памяти были бы, МиБ | Рост пика от B (11 МиБ ×{0}), МиБ | memory.peak cgroup, МиБ |"
|
||
.format(args.count), "| --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||
for r in rows:
|
||
table.append(f"| {r['replica']} | {r['uploads_served']} | {r['rss_before_mib']} | {r['hwm_before_mib']} → "
|
||
f"{r['hwm_after_a_mib']} | {r['peak_growth_mib']} | {r['bodies_if_in_memory_mib']} | "
|
||
f"{r['growth_from_b_mib']} | {r['cgroup_peak_after_mib']} |")
|
||
summary = (f"Профиль A: {args.count} одновременных PNG по {size / MIB:.1f} МиБ за {took_a} с, все 202, SHA-256 "
|
||
f"совпали при скачивании; профиль B: {args.count} одновременных по 11 МиБ за {took_b} с, все 413. "
|
||
f"Лимит памяти реплики 512 МиБ. Сырые данные: evidence/upload-memory.json.")
|
||
block = "\n".join([summary, "", *table])
|
||
print(block)
|
||
report = ROOT / "REPORT.md"
|
||
text = report.read_text(encoding="utf-8")
|
||
begin, end = "<!-- upload-memory:begin -->", "<!-- upload-memory:end -->"
|
||
if begin in text and end in text:
|
||
head, rest = text.split(begin, 1)
|
||
report.write_text(head + begin + "\n" + block + "\n" + end + rest.split(end, 1)[1], encoding="utf-8")
|
||
print("REPORT.md: table updated between upload-memory markers")
|
||
print("PASS: >= 10 concurrent uploads measured; see the table above")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
run(main)
|