forked from mtusi2026/mtusi2026lab5
- F10: rolling-update.sh собирает migrate (единственный сервис с build), проверяет APP_VERSION в образе, в новой реплике и в ответах через LB; реально выполнено обновление 1 -> 2 (evidence/rolling-update.txt) - F14: s3_outage.py переписан под lab5 (503 в API, retry в worker, принятое задание доходит до ready); устаревший consistency_faults.py удалён - F15: .github/workflows/app.yml — сборка, готовность, smoke и регрессии на изолированном стенде, логи при ошибке, очистка - F16: upload_memory.py с явными критериями и ненулевым кодом выхода, размер в каждой записи, progressive JPEG в смеси - run_all.sh: все регрессии аудита, make validate, регрессия lab3, rolling update
205 lines
10 KiB
Python
205 lines
10 KiB
Python
#!/usr/bin/env python3
|
||
"""Пик памяти API при одновременных загрузках крупных файлов (уровень 4).
|
||
|
||
python3 student-tests/upload_memory.py --concurrency 12 --rounds 3 --output evidence/upload-memory-c12.json
|
||
|
||
Гипотеза: потоковый приём (буфер 64 KiB -> безымянный временный файл), multipart PUT
|
||
частями по 5 MiB и проверка JPEG в подпроцессе с лимитом (src/jpeg_probe.py) держат RAM
|
||
реплики ограниченной и не зависящей линейно от числа одновременных загрузок.
|
||
|
||
Lab5 (аудит F16): явные критерии успеха и ненулевой код выхода при нарушении — все ответы 202
|
||
(503 только с --allow-503), ни одного OOM-kill и перезапуска реплик, пик памяти cgroup каждой
|
||
реплики < 90% лимита. Объём считается по размеру файла в каждой записи. В смесь входят
|
||
несжимаемый PNG ~10 MiB, baseline JPEG и progressive JPEG 4:4:4 ~40 Мпикс (самый тяжёлый
|
||
по памяти вход, аудит F02) — JPEG генерируются в контейнере checks (Pillow).
|
||
|
||
Методика: перед прогоном API-реплики перезапускаются (VmHWM считается с нуля). В каждой
|
||
реплике фоново (docker exec ... while sleep 0.05) читаются VmRSS процесса (PID 1) и
|
||
anon/file из cgroup memory.stat. Нагрузка — concurrency потоков, каждый грузит свой
|
||
файл через LB; файлы: несжимаемый PNG ~9.99 MiB и (если на хосте есть Pillow) JPEG
|
||
6000x6000 = 36 Мпикс. В конце — VmHWM (пиковый RSS процесса) и memory.peak cgroup.
|
||
file-память cgroup — page cache временных файлов, она вытесняема и OOM не вызывает.
|
||
"""
|
||
import argparse
|
||
import hashlib
|
||
import io
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import zlib
|
||
from pathlib import Path
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
sys.path.insert(0, str(ROOT / "tests"))
|
||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||
from client import Client # noqa: E402
|
||
from attachments_negative import noise_png # noqa: E402
|
||
|
||
SAMPLER = ("while true; do r=$(grep VmRSS /proc/1/status | tr -s ' ' | cut -d' ' -f2); "
|
||
"a=$(grep '^anon ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); "
|
||
"f=$(grep '^file ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); echo \"$r $a $f\"; sleep 0.05; done")
|
||
|
||
|
||
def sh(*cmd):
|
||
return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, check=True).stdout
|
||
|
||
|
||
def containers():
|
||
return sh("docker", "compose", "ps", "-q", "api").split()
|
||
|
||
|
||
def proc_status(cid, field):
|
||
out = sh("docker", "exec", cid, "grep", field, "/proc/1/status")
|
||
return int(out.split()[1]) // 1024 # kB -> MiB
|
||
|
||
|
||
class Sampler:
|
||
def __init__(self, cid):
|
||
self.cid, self.samples = cid, []
|
||
self.p = subprocess.Popen(["docker", "exec", cid, "sh", "-c", SAMPLER], stdout=subprocess.PIPE, text=True)
|
||
threading.Thread(target=self._read, daemon=True).start()
|
||
|
||
def _read(self):
|
||
for line in self.p.stdout:
|
||
parts = line.split()
|
||
if len(parts) == 3:
|
||
self.samples.append((time.monotonic(), int(parts[0]) / 1024, int(parts[1]) / 2**20, int(parts[2]) / 2**20))
|
||
|
||
def stop(self):
|
||
self.p.terminate()
|
||
|
||
|
||
GEN = r"""
|
||
import io, sys
|
||
from PIL import Image
|
||
kind = sys.argv[1]
|
||
if kind == "baseline":
|
||
im = Image.effect_noise((6000, 6000), 40).convert("RGB")
|
||
for q in (60, 45, 30, 20):
|
||
b = io.BytesIO(); im.save(b, "JPEG", quality=q)
|
||
if b.tell() <= 10 * 1024 * 1024:
|
||
break
|
||
else:
|
||
g = Image.radial_gradient("L").resize((6324, 6324))
|
||
b = io.BytesIO(); Image.merge("RGB", (g, g.rotate(90), g)).save(b, "JPEG", quality=85, progressive=True, subsampling=0)
|
||
sys.stdout.buffer.write(b.getvalue())
|
||
"""
|
||
|
||
|
||
def make_jpeg(kind):
|
||
"""JPEG генерируется в контейнере checks (на хосте Pillow может не быть)."""
|
||
proc = subprocess.run(["docker", "compose", "--profile", "tools", "run", "--rm", "-T", "checks", "-c", GEN, kind],
|
||
cwd=ROOT, capture_output=True, check=True)
|
||
return proc.stdout
|
||
|
||
|
||
def main():
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||
ap.add_argument("--concurrency", type=int, default=12)
|
||
ap.add_argument("--rounds", type=int, default=3)
|
||
ap.add_argument("--no-restart", action="store_true")
|
||
ap.add_argument("--allow-503", action="store_true", help="считать 503 (перегрузка) допустимым ответом")
|
||
ap.add_argument("--output")
|
||
args = ap.parse_args()
|
||
files = [("image/png", noise_png(10 * 1024 * 1024))]
|
||
files.append(("image/jpeg", make_jpeg("baseline")))
|
||
files.append(("image/jpeg", make_jpeg("progressive444")))
|
||
if not args.no_restart:
|
||
sh("docker", "compose", "restart", "api")
|
||
sh("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--wait", "api")
|
||
time.sleep(4)
|
||
c = Client(args.base_url, timeout=120)
|
||
alice, _bob, _eve, chat = c.bootstrap()
|
||
# прогрев: один upload каждого типа (импорт Pillow, пулы соединений)
|
||
for ctype, data in files:
|
||
c.call("POST", "/api/v1/chats/%s/attachments?filename=w" % chat["id"], 202, actor=alice, raw=data,
|
||
headers={"Content-Type": ctype})
|
||
cids = containers()
|
||
restarts_before = sh("docker", "inspect", "-f", "{{.RestartCount}}", *cids).split()
|
||
idle = {cid[:12]: {"rss_mib": proc_status(cid, "VmRSS"), "hwm_mib_after_warmup": proc_status(cid, "VmHWM")}
|
||
for cid in cids}
|
||
s3_cid = sh("docker", "compose", "ps", "-q", "s3").split()[0]
|
||
s3_before = {"rss_mib": proc_status(s3_cid, "VmRSS"), "oom_killed": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip()}
|
||
samplers = [Sampler(cid) for cid in cids]
|
||
s3_sampler = Sampler(s3_cid)
|
||
time.sleep(1)
|
||
results, lock = [], threading.Lock()
|
||
|
||
def worker(i):
|
||
ctype, data = files[i % len(files)]
|
||
t = time.monotonic()
|
||
try:
|
||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=m%d" % (chat["id"], i), [202, 503], actor=alice,
|
||
raw=data, headers={"Content-Type": ctype}, schema=None)
|
||
st, inst = r["status"], r["headers"].get("X-Instance-Id")
|
||
except Exception as exc: # noqa: BLE001
|
||
st, inst = type(exc).__name__, None
|
||
with lock:
|
||
# Размер — в самой записи: потоки завершаются не по порядку (аудит F16).
|
||
results.append({"type": ctype, "bytes": len(data), "status": st, "instance": inst,
|
||
"s": round(time.monotonic() - t, 2)})
|
||
|
||
started = time.monotonic()
|
||
for _ in range(args.rounds):
|
||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
|
||
for th in threads:
|
||
th.start()
|
||
for th in threads:
|
||
th.join()
|
||
wall = time.monotonic() - started
|
||
time.sleep(1)
|
||
for s in samplers + [s3_sampler]:
|
||
s.stop()
|
||
per = {}
|
||
for cid, s in zip(cids, samplers):
|
||
k = cid[:12]
|
||
per[k] = dict(idle[k],
|
||
samples=len(s.samples),
|
||
peak_rss_mib_sampled=round(max(x[1] for x in s.samples), 1),
|
||
peak_anon_mib=round(max(x[2] for x in s.samples), 1),
|
||
peak_file_cache_mib=round(max(x[3] for x in s.samples), 1),
|
||
vmhwm_mib=proc_status(cid, "VmHWM"),
|
||
cgroup_memory_peak_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.peak")) / 2**20, 1),
|
||
memory_limit_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20),
|
||
uploads_served=sum(1 for r in results if r["instance"] == k))
|
||
durations = sorted(r["s"] for r in results if r["status"] == 202)
|
||
summary = {
|
||
"concurrency": args.concurrency, "rounds": args.rounds,
|
||
"files": [{"type": t, "bytes": len(d), "sha256": hashlib.sha256(d).hexdigest()[:16]} for t, d in files],
|
||
"uploads": len(results), "status_counts": {str(k): sum(1 for r in results if r["status"] == k)
|
||
for k in {r["status"] for r in results}},
|
||
"megabytes_uploaded_ok": round(sum(r["bytes"] for r in results if r["status"] == 202) / 2**20, 1),
|
||
"wall_s": round(wall, 1),
|
||
"latency_s_p50_max": [durations[len(durations) // 2], durations[-1]] if durations else None,
|
||
"replicas": per,
|
||
"s3": dict(s3_before,
|
||
peak_rss_mib_sampled=round(max(x[1] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||
peak_anon_mib=round(max(x[2] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||
restarts=int(sh("docker", "inspect", "-f", "{{.RestartCount}}", s3_cid)),
|
||
oom_killed_after=sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip(),
|
||
memory_limit_mib=round(int(sh("docker", "exec", s3_cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20)),
|
||
"oom_kills": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", *cids).split(),
|
||
}
|
||
allowed = {202, 503} if args.allow_503 else {202}
|
||
restarts_after = sh("docker", "inspect", "-f", "{{.RestartCount}}", *cids).split()
|
||
criteria = {
|
||
"all_responses_allowed": all(r["status"] in allowed for r in results),
|
||
"no_oom_kills": all(x == "false" for x in summary["oom_kills"]),
|
||
"no_replica_restarts": restarts_before == restarts_after,
|
||
"cgroup_peak_below_90pct": all(v["cgroup_memory_peak_mib"] < 0.9 * v["memory_limit_mib"] for v in per.values()),
|
||
}
|
||
summary["criteria"] = criteria
|
||
summary["pass"] = all(criteria.values())
|
||
print(json.dumps(summary, ensure_ascii=False, indent=1))
|
||
if args.output:
|
||
Path(args.output).write_text(json.dumps(summary, ensure_ascii=False, indent=1))
|
||
return 0 if summary["pass"] else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|