ЛР 4: вложения в S3 и двусторонняя сверка хранилищ

This commit is contained in:
2026-11-15 11:50:57 +03:00
parent ec540a1a72
commit b58e703546
160 changed files with 16598 additions and 25 deletions
+118
View File
@@ -0,0 +1,118 @@
import argparse
import collections
import concurrent.futures
import hashlib
import json
from pathlib import Path
import subprocess
import sys
import threading
import time
from urllib.parse import quote
root = Path.cwd()
sys.path.insert(0, str(root / "tests"))
from client import Client, check
parser = argparse.ArgumentParser(description="Measure memory on two disposable API replicas")
parser.add_argument("--base-url", required=True)
parser.add_argument("--project", required=True)
parser.add_argument("--fixtures", type=Path, required=True, help="Directory containing generated load.png and load.jpg")
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
out = args.output
out.mkdir(parents=True, exist_ok=True)
base, project, fixture_dir = args.base_url, args.project, args.fixtures
def docker(*args):
return subprocess.check_output(["docker", *args], text=True, timeout=20).strip()
def api_ids():
return docker("ps", "-q", "--filter", "label=com.docker.compose.project=" + project,
"--filter", "label=com.docker.compose.service=api").splitlines()
def memory(cid):
values = docker("exec", cid, "sh", "-c", "cd /sys/fs/cgroup && cat memory.current memory.peak memory.max memory.events").splitlines()
return dict(zip(("current", "peak", "limit"), map(int, values[:3]))) | {
"events": {k: int(v) for k, v in (line.split() for line in values[3:])},
"state": json.loads(docker("inspect", "--format", "{{json .State}}", cid)),
"restarts": int(docker("inspect", "--format", "{{.RestartCount}}", cid)),
}
def profile(name, files):
c = Client(base)
actor = c.user("load")
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, body={
"title": "Load " + name, "member_ids": [actor["id"]]}, schema="Chat")["json"]
ids = api_ids()
check(len(ids) == 2, "expected both API replicas")
before = {cid: memory(cid) for cid in ids}
workers = len(files)
gate = threading.Barrier(workers + 1)
samplers = []
stop = threading.Event()
sampled = {cid: [] for cid in ids}
def sample(cid):
proc = subprocess.Popen(["docker", "exec", cid, "sh", "-c",
"for i in $(seq 1 240); do read -r m </sys/fs/cgroup/memory.current || exit; printf '%s\\n' \"$m\"; sleep 0.05; done"],
stdout=subprocess.PIPE, text=True)
try:
for line in proc.stdout:
sampled[cid].append((round(time.monotonic() - start, 3), int(line)))
if stop.is_set():
break
finally:
proc.terminate()
proc.wait(timeout=5)
def upload_item(item):
i, (filename, mime, data) = item
client = Client(base, timeout=18)
gate.wait(timeout=12)
try:
res = client.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename),
[201, 429, 500, 503], actor=actor, raw=data, headers={"Content-Type": mime})
if res["status"] == 201:
check(json.loads(res["bytes"])["sha256"] == hashlib.sha256(data).hexdigest(), "checksum changed")
return {"index": i, "status": res["status"], "instance": res["headers"]["X-Instance-Id"], "seconds": res["elapsed"]}
except Exception as exc:
return {"index": i, "error": str(exc)}
start = time.monotonic()
for cid in ids:
worker = threading.Thread(target=sample, args=(cid,))
worker.start()
samplers.append(worker)
time.sleep(0.35)
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
pending = [executor.submit(upload_item, item) for item in enumerate(files)]
gate.wait(timeout=12)
results = [job.result() for job in pending]
time.sleep(0.25)
stop.set()
for worker in samplers:
worker.join(timeout=10)
after = {cid: memory(cid) for cid in ids}
states = {}
for cid in ids:
first, last = before[cid], after[cid]
states[cid] = {"before_peak": first["peak"], "after_peak": last["peak"], "limit": last["limit"],
"samples": sampled[cid], "events_delta": {k: v - first["events"][k] for k,v in last["events"].items()},
"restart_delta": last["restarts"] - first["restarts"],
"same_start": first["state"]["StartedAt"] == last["state"]["StartedAt"],
"oom_killed": last["state"]["OOMKilled"]}
report = {"clients": workers, "files": [{"name": a, "mime": b, "bytes": len(c), "sha256": hashlib.sha256(c).hexdigest()} for a,b,c in files],
"statuses": dict(collections.Counter(r.get("status", "error") for r in results)),
"results": results, "replicas": states, "sampling_seconds": 0.05}
(out / ("memory-" + name + ".json")).write_text(json.dumps(report, indent=2) + "\n")
print(name, report["statuses"], {k: v["after_peak"] for k,v in states.items()}, flush=True)
check(all(v["samples"] and v["same_start"] and v["restart_delta"] == 0 and not v["oom_killed"]
and not v["events_delta"].get("oom") and not v["events_delta"].get("oom_kill") for v in states.values()), "OOM or restart")
check(all(r.get("status") in (201, 429) for r in results), "unexpected upload results")
check(len({r["instance"] for r in results if r["status"] == 201}) == 2, "need successes on both replicas")
if name == "normal":
check(report["statuses"].get(201, 0) >= 10, "normal profile did not complete ten uploads")
normal = (root / "tests/fixtures/sample.png").read_bytes()
png = (fixture_dir / "load.png").read_bytes()
jpeg = (fixture_dir / "load.jpg").read_bytes()
profile("normal", [("sample.png", "image/png", normal)] * 12)
profile("heavy", [("load.png", "image/png", png), ("load.jpg", "image/jpeg", jpeg)] * 6)