выполнение ЛР4 на 4
- S3: SeaweedFS 4.51 (MinIO-образы недоступны), приватный bucket, отдельные ограниченные ключи API, служебные порты закрыты; идемпотентный s3-init с проверкой приватности и прогревом записи - вложения: потоковая загрузка PNG/JPEG, лимиты 10 MiB / 40 Мпикс, тип по содержимому, проверка filename, скачивание только участникам - согласованность PG/S3: pending -> PUT -> ready, компенсация, sweeper с grace и dry-run; attachment_ids в сообщениях, FK по чату - back-pressure на S3 PUT после найденного OOM SeaweedFS - тесты student-tests, evidence, REPORT.md, DEMO.md
This commit is contained in:
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Negative/positive suite for attachments (lab4, level 4). User errors must never become 500."""
|
||||
import hashlib
|
||||
import os
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from stack import SAMPLE_JPG, SAMPLE_PNG, png, png_header_only, psql
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
LIMIT = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Attachment validation, ACL and linking through the LB")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
other = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "Другой чат", "member_ids": [alice["id"], eve["id"]]}, schema="Chat")["json"]
|
||||
results = []
|
||||
|
||||
def case(name, fn):
|
||||
fn()
|
||||
results.append(name)
|
||||
print("PASS", name)
|
||||
|
||||
def upload(data, ctype="image/png", filename="f.png", actor=alice, target=chat, expected=201):
|
||||
path = "/api/v1/chats/" + target["id"] + "/attachments"
|
||||
if filename is not None:
|
||||
path += "?filename=" + quote(filename, safe="")
|
||||
headers = {"Content-Type": ctype} if ctype else {}
|
||||
r = c.call("POST", path, expected, actor=actor, raw=data, headers=headers, schema="Attachment" if expected == 201 else None)
|
||||
return r["json"]
|
||||
|
||||
def post(body, actor=alice, target=chat, expected=201):
|
||||
return c.call("POST", "/api/v1/chats/" + target["id"] + "/messages", expected, actor=actor, body=body,
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex}, schema="Message" if expected == 201 else None)["json"]
|
||||
|
||||
def download(att_id, actor=bob, suffix="/content"):
|
||||
return c.call("GET", "/api/v1/attachments/" + att_id + suffix, actor=actor)
|
||||
|
||||
# --- positive -----------------------------------------------------------------------------
|
||||
att_png = upload(SAMPLE_PNG, filename="фото 😀.png")
|
||||
att_jpg = upload(SAMPLE_JPG, "image/jpeg", "sample.jpg")
|
||||
|
||||
def roundtrip():
|
||||
check(att_png["filename"] == "фото 😀.png" and att_png["status"] == "ready" and att_png["variants"] == [], "png metadata")
|
||||
check(att_jpg["content_type"] == "image/jpeg" and att_jpg["sha256"] == hashlib.sha256(SAMPLE_JPG).hexdigest(), "jpeg metadata")
|
||||
for att, data, ctype in ((att_png, SAMPLE_PNG, "image/png"), (att_jpg, SAMPLE_JPG, "image/jpeg")):
|
||||
d = download(att["id"])
|
||||
check(d["bytes"] == data and d["headers"].get_content_type() == ctype, "download differs")
|
||||
check(d["headers"].get("X-Content-Type-Options") == "nosniff", "nosniff missing")
|
||||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
check(meta == att, "metadata via GET differs from upload response")
|
||||
case("png+jpeg upload, member download is byte-identical, metadata stable", roundtrip)
|
||||
|
||||
def message_links():
|
||||
m = post({"text": "", "attachment_ids": [att_jpg["id"], att_png["id"]]})
|
||||
check(m["attachment_ids"] == [att_jpg["id"], att_png["id"]] and m["text"] == "", "order/text of attachment message")
|
||||
plain = post({"text": "без вложений"})
|
||||
check(plain["attachment_ids"] == [], "default attachment_ids must be []")
|
||||
hist = c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
|
||||
by_id = {x["id"]: x for x in hist}
|
||||
check(by_id[m["id"]]["attachment_ids"] == m["attachment_ids"] and by_id[plain["id"]]["attachment_ids"] == [], "history lost links")
|
||||
post({"text": "второй раз то же вложение", "attachment_ids": [att_png["id"]]}, actor=bob)
|
||||
case("message with only attachments, order kept, history shows links, re-use by other member", message_links)
|
||||
|
||||
def idempotency():
|
||||
key = uuid.uuid4().hex
|
||||
h = {"Idempotency-Key": key}
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
a = c.call("POST", path, 201, actor=alice, body={"text": "x"}, headers=h, schema="Message")["json"]
|
||||
b = c.call("POST", path, 201, actor=alice, body={"attachment_ids": [], "text": "x"}, headers=h, schema="Message")["json"]
|
||||
check(a == b, "missing attachment_ids and [] must be the same request")
|
||||
c.call("POST", path, 409, actor=alice, body={"text": "x", "attachment_ids": [att_png["id"]]}, headers=h)
|
||||
case("idempotency: missing attachment_ids == [], other attachments -> 409", idempotency)
|
||||
|
||||
def boundary_pixels():
|
||||
att = upload(png(8000, 5000, 0), filename="40mpx.png") # exactly 40 000 000 px, gray
|
||||
check(att["size_bytes"] > 0, "boundary image rejected")
|
||||
case("exactly 40 000 000 px accepted", boundary_pixels)
|
||||
|
||||
# --- size / pixels ------------------------------------------------------------------------
|
||||
big = b"\x89PNG\r\n\x1a\n" + os.urandom(LIMIT + 1 - 8)
|
||||
case("10 MiB + 1 byte with Content-Length -> 413", lambda: upload(big, expected=413))
|
||||
|
||||
def chunked():
|
||||
def gen():
|
||||
for i in range(0, len(big), 256 * 1024):
|
||||
yield big[i:i + 256 * 1024]
|
||||
upload(gen(), expected=413)
|
||||
case("10 MiB + 1 byte chunked (no Content-Length) -> 413 while streaming", chunked)
|
||||
case("decompression bomb 8000x5001 px (~1 KB/40 MB raw) -> 413", lambda: upload(png(8000, 5001, 0), expected=413))
|
||||
case("RGB 20000x20000 header -> 413 before decode", lambda: upload(png_header_only(20000, 20000), expected=413))
|
||||
|
||||
# --- corrupted / MIME ---------------------------------------------------------------------
|
||||
case("truncated PNG -> 415", lambda: upload(SAMPLE_PNG[:len(SAMPLE_PNG) // 2], expected=415))
|
||||
flipped = bytearray(SAMPLE_PNG)
|
||||
flipped[len(flipped) // 2] ^= 0xFF
|
||||
case("PNG with damaged IDAT byte (CRC) -> 415", lambda: upload(bytes(flipped), expected=415))
|
||||
case("truncated JPEG -> 415", lambda: upload(SAMPLE_JPG[:len(SAMPLE_JPG) // 2], "image/jpeg", expected=415))
|
||||
case("PNG bytes declared image/jpeg -> 415", lambda: upload(SAMPLE_PNG, "image/jpeg", expected=415))
|
||||
case("JPEG bytes declared image/png -> 415", lambda: upload(SAMPLE_JPG, "image/png", expected=415))
|
||||
case("text declared image/png -> 415", lambda: upload(b"<?php echo 1; ?>" * 10, expected=415))
|
||||
case("GIF declared image/png -> 415", lambda: upload(b"GIF89a" + bytes(100), expected=415))
|
||||
case("SVG/HTML declared image/png -> 415", lambda: upload(b"<svg xmlns='http://www.w3.org/2000/svg'><script>1</script></svg>", expected=415))
|
||||
case("PNG magic + garbage -> 415", lambda: upload(b"\x89PNG\r\n\x1a\n" + os.urandom(2000), expected=415))
|
||||
case("empty body -> 415", lambda: upload(b"", expected=415))
|
||||
case("Content-Type application/octet-stream -> 415", lambda: upload(SAMPLE_PNG, "application/octet-stream", expected=415))
|
||||
case("Content-Type multipart/form-data -> 415", lambda: upload(SAMPLE_PNG, "multipart/form-data; boundary=x", expected=415))
|
||||
|
||||
# --- filename -----------------------------------------------------------------------------
|
||||
for label, name in (("missing", None), ("path ../", "../etc/passwd.png"), ("slash", "a/b.png"), ("backslash", "a\\b.png"),
|
||||
("NUL", "a\x00.png"), ("newline", "a\nb.png"), ("bidi RLO", "gpj.exe"), ("dot-dot", ".."),
|
||||
("blank", " "), ("256 chars", "a" * 252 + ".png")):
|
||||
case("filename %s -> 400" % label, lambda name=name: upload(SAMPLE_PNG, filename=name, expected=400))
|
||||
|
||||
# --- access -------------------------------------------------------------------------------
|
||||
case("outsider uploads into chat -> 404", lambda: upload(SAMPLE_PNG, actor=eve, expected=404))
|
||||
case("outsider metadata -> 404", lambda: c.call("GET", "/api/v1/attachments/" + att_png["id"], 404, actor=eve))
|
||||
case("outsider content -> 404", lambda: c.call("GET", "/api/v1/attachments/" + att_png["id"] + "/content", 404, actor=eve))
|
||||
case("unknown attachment -> 404", lambda: c.call("GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=alice))
|
||||
case("invalid attachment UUID -> 400", lambda: c.call("GET", "/api/v1/attachments/not-a-uuid", 400, actor=alice))
|
||||
case("no session -> 401", lambda: c.call("GET", "/api/v1/attachments/" + att_png["id"] + "/content", 401))
|
||||
case("variant thumbnail not produced in lab4 -> 404", lambda: c.call("GET", "/api/v1/attachments/" + att_png["id"] + "/content?variant=thumbnail", 404, actor=bob))
|
||||
case("unknown variant -> 400", lambda: c.call("GET", "/api/v1/attachments/" + att_png["id"] + "/content?variant=raw", 400, actor=bob))
|
||||
case("variant=original explicit -> 200", lambda: c.call("GET", "/api/v1/attachments/" + att_png["id"] + "/content?variant=original", 200, actor=bob))
|
||||
|
||||
# --- linking ------------------------------------------------------------------------------
|
||||
foreign = upload(SAMPLE_PNG, actor=alice, target=other)
|
||||
case("attachment of another chat (same author) -> 404", lambda: post({"text": "x", "attachment_ids": [foreign["id"]]}, expected=404))
|
||||
case("outsider links chat attachment into own chat -> 404", lambda: post({"text": "x", "attachment_ids": [att_png["id"]]}, actor=eve, target=other, expected=404))
|
||||
case("unknown attachment id in message -> 404", lambda: post({"text": "x", "attachment_ids": [str(uuid.uuid4())]}, expected=404))
|
||||
case("11 attachment ids -> 400", lambda: post({"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, expected=400))
|
||||
case("duplicate attachment ids -> 400", lambda: post({"text": "x", "attachment_ids": [att_png["id"], att_png["id"]]}, expected=400))
|
||||
case("blank text without attachments -> 400", lambda: post({"text": " "}, expected=400))
|
||||
case("attachment_ids wrong type -> 400", lambda: post({"text": "x", "attachment_ids": "abc"}, expected=400))
|
||||
|
||||
def db_guard():
|
||||
msg = post({"text": "db guard"})
|
||||
sql = ("BEGIN; INSERT INTO message_attachments (message_id, attachment_id, chat_id, position) VALUES ('%s','%s','%s',0); ROLLBACK;"
|
||||
% (msg["id"], foreign["id"], chat["id"]))
|
||||
try:
|
||||
psql(sql)
|
||||
except RuntimeError as exc:
|
||||
check("foreign key" in str(exc), "unexpected DB error")
|
||||
return
|
||||
check(False, "DB accepted a cross-chat attachment link")
|
||||
case("DB composite FK rejects cross-chat link even bypassing API", db_guard)
|
||||
|
||||
print("PASS: %d attachment cases" % len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import math
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
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, arguments, check, run
|
||||
|
||||
|
||||
def pct(values, p):
|
||||
return round(1000 * values[max(0, math.ceil(p * len(values)) - 1)], 1) if values else None
|
||||
|
||||
|
||||
def docker_stats():
|
||||
ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids],
|
||||
capture_output=True, text=True)
|
||||
return sorted(out.stdout.splitlines())
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument("--duration", type=float, default=25)
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--action", default=None, help="command run once at --action-at seconds")
|
||||
p.add_argument("--action-at", type=float, default=5)
|
||||
p.add_argument("--output", default=None)
|
||||
args = arguments("Load with an operator action in the middle", configure)
|
||||
boot = Client(args.base_url, timeout=10)
|
||||
alice, bob, _eve, chat = boot.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
|
||||
events = []
|
||||
confirmed = []
|
||||
lock = threading.Lock()
|
||||
t0 = time.monotonic()
|
||||
stop_at = t0 + args.duration
|
||||
action_info = {}
|
||||
|
||||
def worker(wid):
|
||||
c = Client(args.base_url, timeout=2)
|
||||
key, text, n = None, None, 0
|
||||
while time.monotonic() < stop_at:
|
||||
if key is None:
|
||||
key = uuid.uuid4().hex
|
||||
text = "chaos-%d-%d-%s" % (wid, n, key[:8])
|
||||
for kind in ("write", "read"):
|
||||
start = time.monotonic()
|
||||
try:
|
||||
if kind == "write":
|
||||
r = c.call("POST", path, 201, actor=alice, body={"text": text}, headers={"Idempotency-Key": key}, schema="Message")
|
||||
else:
|
||||
r = c.call("GET", path + "?limit=20", actor=bob, schema="MessagePage")
|
||||
ok, inst = True, r["headers"].get("X-Instance-Id")
|
||||
except Failure:
|
||||
ok, inst = False, None
|
||||
end = time.monotonic()
|
||||
with lock:
|
||||
events.append((start - t0, kind, ok, end - start, inst))
|
||||
if ok and kind == "write":
|
||||
confirmed.append(r["json"])
|
||||
if kind == "write" and ok:
|
||||
key, n = None, n + 1
|
||||
if not ok:
|
||||
time.sleep(0.05)
|
||||
|
||||
def action():
|
||||
time.sleep(args.action_at)
|
||||
action_info["started"] = time.monotonic() - t0
|
||||
proc = subprocess.run(shlex.split(args.action), cwd=ROOT, capture_output=True, text=True)
|
||||
action_info["finished"] = time.monotonic() - t0
|
||||
action_info["returncode"] = proc.returncode
|
||||
action_info["output_tail"] = proc.stdout.strip().splitlines()[-6:]
|
||||
|
||||
stats_mid = []
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
|
||||
if args.action:
|
||||
threads.append(threading.Thread(target=action))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(min(args.duration / 2, args.action_at + 3))
|
||||
stats_mid = docker_stats()
|
||||
for t in threads:
|
||||
t.join()
|
||||
elapsed = time.monotonic() - t0
|
||||
|
||||
ok_lat = sorted(e[3] for e in events if e[2])
|
||||
errors = [e for e in events if not e[2]]
|
||||
a0 = action_info.get("started")
|
||||
timeline = defaultdict(lambda: [0, 0])
|
||||
for e in events:
|
||||
timeline[int(e[0])][0 if e[2] else 1] += 1
|
||||
report = {
|
||||
"profile": "closed loop, %d workers, each: POST message (retry same key) + GET history; client timeout 2 s" % args.concurrency,
|
||||
"action": args.action, "action_started_s": a0 and round(a0, 2), "action_finished_s": action_info.get("finished") and round(action_info["finished"], 2),
|
||||
"action_returncode": action_info.get("returncode"), "action_output": action_info.get("output_tail"),
|
||||
"elapsed_s": round(elapsed, 2), "requests": len(events), "successful": len(ok_lat), "errors": len(errors),
|
||||
"error_ratio": round(len(errors) / len(events), 5) if events else None,
|
||||
"successful_rps": round(len(ok_lat) / elapsed, 1),
|
||||
"latency_ms_success": {"p50": pct(ok_lat, .50), "p95": pct(ok_lat, .95), "p99": pct(ok_lat, .99), "max": pct(ok_lat, 1)},
|
||||
"slow_over_500ms_after_action": sum(1 for e in events if e[2] and e[3] > .5 and a0 is not None and e[0] >= a0),
|
||||
"error_window_s": [round(errors[0][0] - (a0 or 0), 2), round(max(e[0] + e[3] for e in errors) - (a0 or 0), 2)] if errors else None,
|
||||
"recovery_s_after_action": None,
|
||||
"instances_before": dict(Counter(e[4] for e in events if e[2] and (a0 is None or e[0] < a0))),
|
||||
"instances_last_5s": dict(Counter(e[4] for e in events if e[2] and e[0] > elapsed - 5)),
|
||||
"timeline_ok_err_per_s": {k: v for k, v in sorted(timeline.items())},
|
||||
"docker_stats_mid": stats_mid,
|
||||
}
|
||||
if a0 is not None:
|
||||
bad_ends = [e[0] + e[3] for e in events if e[0] + e[3] >= a0 and (not e[2] or e[3] > 1)]
|
||||
report["recovery_s_after_action"] = round(max(bad_ends) - a0, 2) if bad_ends else 0.0
|
||||
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
q = path + "?limit=100" + ("&cursor=" + quote(cursor, safe="") if cursor else "")
|
||||
page = boot.call("GET", q, actor=bob, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
ids = Counter(m["id"] for m in items)
|
||||
texts = Counter(m["text"] for m in items)
|
||||
stored = {m["id"]: m for m in items}
|
||||
report["integrity"] = {
|
||||
"stored_messages": len(items), "confirmed_writes": len(confirmed),
|
||||
"duplicate_ids": sum(1 for n in ids.values() if n > 1), "duplicate_texts": sum(1 for n in texts.values() if n > 1),
|
||||
"confirmed_missing": sum(1 for m in confirmed if stored.get(m["id"]) != m),
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=1)
|
||||
print(text)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + "\n")
|
||||
check(report["integrity"]["duplicate_texts"] == 0 and report["integrity"]["confirmed_missing"] == 0, "data integrity violated")
|
||||
check(action_info.get("returncode", 0) == 0, "action failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Failures between S3 and PostgreSQL: S3 outage, aborted upload, and the sweeper with injected faults.
|
||||
|
||||
Modifies the compose stack: stops/starts the s3 service and writes synthetic rows/objects. Takes ~1.5 min
|
||||
(the sweeper refuses grace < 60 s, so injected "old" objects must really age).
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from stack import SAMPLE_PNG, api_python, count_objects, dc, psql
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
GRACE = 60
|
||||
|
||||
|
||||
def pending_count():
|
||||
return int(psql("SELECT count(*) FROM attachments WHERE status = 'pending'"))
|
||||
|
||||
|
||||
def put_object(key):
|
||||
api_python("import io; from app.objects import ObjectStore; s=ObjectStore(); "
|
||||
"s._s3.put_object(Bucket=s.bucket, Key=%r, Body=io.BytesIO(b'injected'))" % key)
|
||||
|
||||
|
||||
def object_exists(key):
|
||||
return api_python("from app.objects import ObjectStore; s=ObjectStore(); "
|
||||
"print(any(k == %r for k, _ in s.list_originals()))" % key) == "True"
|
||||
|
||||
|
||||
def insert_pending(chat_id, owner_id, key, age_seconds):
|
||||
psql("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, "
|
||||
"object_key, status, created_at, updated_at) VALUES ('%s','%s','%s','injected.png','image/png',8,'%s',1,1,'%s',"
|
||||
"'pending', now() - make_interval(secs => %d), now() - make_interval(secs => %d))"
|
||||
% (uuid.uuid4(), chat_id, owner_id, "0" * 64, key, age_seconds, age_seconds))
|
||||
|
||||
|
||||
def row_exists(key):
|
||||
return psql("SELECT count(*) FROM attachments WHERE object_key = '%s'" % key) == "1"
|
||||
|
||||
|
||||
def sweep(*flags):
|
||||
out = dc("run", "--rm", "--no-deps", "-T", "sweeper", "python", "-m", "app.sweeper", "--once", "--grace", str(GRACE), *flags).stdout
|
||||
report = json.loads(out.strip().splitlines()[-1])
|
||||
check("skipped" not in report, "sweeper lock is held")
|
||||
return report
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("S3/PostgreSQL consistency under failures")
|
||||
c = Client(args.base_url, timeout=15)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=x.png"
|
||||
ready = c.call("POST", path, 201, actor=alice, raw=SAMPLE_PNG, headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||
ready_key = psql("SELECT object_key FROM attachments WHERE id = '%s'" % ready["id"])
|
||||
|
||||
# 1. S3 outage -------------------------------------------------------------------------------
|
||||
pend0 = pending_count()
|
||||
dc("stop", "s3")
|
||||
try:
|
||||
t = time.monotonic()
|
||||
c.call("POST", path, 503, actor=alice, raw=SAMPLE_PNG, headers={"Content-Type": "image/png"})
|
||||
upload_s = time.monotonic() - t
|
||||
c.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", 503, actor=bob)
|
||||
meta = c.call("GET", "/api/v1/attachments/" + ready["id"], actor=bob, schema="Attachment")["json"]
|
||||
c.message(alice, chat, "S3 лежит, а сообщения работают")
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
check(pending_count() == pend0, "failed upload left a pending row")
|
||||
print("PASS S3 down: upload 503 in %.2fs, content 503, metadata 200 (%s), messages 201, ready 200, no pending row left"
|
||||
% (upload_s, meta["status"]))
|
||||
finally:
|
||||
dc("start", "s3")
|
||||
dc("up", "-d", "--no-build", "--wait", "s3")
|
||||
t = time.monotonic()
|
||||
while True:
|
||||
try:
|
||||
r = c.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", [200, 503], actor=bob)
|
||||
except Failure:
|
||||
r = {"status": None}
|
||||
if r["status"] == 200:
|
||||
check(r["bytes"] == SAMPLE_PNG, "bytes changed after S3 restart")
|
||||
break
|
||||
check(time.monotonic() - t < 30, "S3 did not recover")
|
||||
time.sleep(1)
|
||||
print("PASS S3 back (healthy per compose): first download byte-identical after %.1fs" % (time.monotonic() - t))
|
||||
|
||||
# 2. Client aborts in the middle of the body ----------------------------------------------------
|
||||
objects0, pend0 = count_objects(), pending_count()
|
||||
u = urlparse(c.base)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=5)
|
||||
s.sendall(("POST /api/v1/chats/%s/attachments?filename=abort.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\n"
|
||||
"Content-Type: image/png\r\nContent-Length: %d\r\n\r\n" % (chat["id"], u.hostname, alice["token"], 5 * 1024 * 1024)).encode())
|
||||
s.sendall(SAMPLE_PNG + bytes(1024 * 1024))
|
||||
s.close()
|
||||
time.sleep(2)
|
||||
check(count_objects() == objects0 and pending_count() == pend0, "aborted upload left an object or a row")
|
||||
print("PASS aborted upload (1.1 of 5 MiB sent): no S3 object, no metadata row")
|
||||
|
||||
# 3. Sweeper: inject inconsistencies on both sides -----------------------------------------------
|
||||
# The background sweeper (grace 900 s) would clean the injected 1-hour-old rows during the wait; pause it
|
||||
# and run single passes with grace 60 s instead.
|
||||
dc("stop", "sweeper")
|
||||
try:
|
||||
sweeper_scenario(c, alice, bob, chat, ready, ready_key)
|
||||
finally:
|
||||
dc("start", "sweeper")
|
||||
|
||||
|
||||
def sweeper_scenario(c, alice, bob, chat, ready, ready_key):
|
||||
old_orphan = "originals/" + uuid.uuid4().hex # object without row (failed compensation)
|
||||
old_pending_obj = "originals/" + uuid.uuid4().hex # crash after PUT, before COMMIT ready
|
||||
old_pending_noobj = "originals/" + uuid.uuid4().hex # crash before PUT
|
||||
put_object(old_orphan)
|
||||
put_object(old_pending_obj)
|
||||
insert_pending(chat["id"], alice["id"], old_pending_obj, 3600)
|
||||
insert_pending(chat["id"], alice["id"], old_pending_noobj, 3600)
|
||||
print("injected: orphan object, stale pending row + object, stale pending row without object; waiting %ds" % (GRACE + 3))
|
||||
time.sleep(GRACE + 3)
|
||||
fresh_orphan = "originals/" + uuid.uuid4().hex # look like uploads still in progress
|
||||
fresh_pending = "originals/" + uuid.uuid4().hex
|
||||
put_object(fresh_orphan)
|
||||
put_object(fresh_pending)
|
||||
insert_pending(chat["id"], alice["id"], fresh_pending, 0)
|
||||
|
||||
dry = sweep("--dry-run")
|
||||
print("dry-run:", json.dumps({k: dry[k] for k in ("pending_found", "orphans_found", "objects_scanned", "duration_ms")}))
|
||||
check(dry["pending_found"] >= 2 and dry["orphans_found"] >= 1, "dry-run did not detect injected faults")
|
||||
check(old_orphan in dry["orphan_keys_sample"] or dry["orphans_found"] > 5, "orphan key not reported")
|
||||
check(object_exists(old_orphan) and row_exists(old_pending_obj), "dry-run changed something")
|
||||
|
||||
real = sweep()
|
||||
print("real:", json.dumps({k: real[k] for k in ("pending_deleted", "orphans_deleted", "objects_scanned", "duration_ms")}))
|
||||
check(not object_exists(old_orphan), "orphan object survived")
|
||||
check(not object_exists(old_pending_obj) and not row_exists(old_pending_obj), "stale pending row/object survived")
|
||||
check(not row_exists(old_pending_noobj), "stale pending row without object survived")
|
||||
check(object_exists(fresh_orphan) and object_exists(fresh_pending) and row_exists(fresh_pending), "fresh upload was deleted")
|
||||
check(object_exists(ready_key), "ready object was deleted")
|
||||
d = c.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=bob)
|
||||
check(d["bytes"] == SAMPLE_PNG, "ready attachment damaged")
|
||||
|
||||
again = sweep()
|
||||
print("repeat:", json.dumps({k: again[k] for k in ("pending_found", "orphans_found")}))
|
||||
check(again["pending_found"] == 0 and again["orphans_found"] == 0, "second pass is not a no-op")
|
||||
print("PASS sweeper: dry-run reports only; real pass removes stale pending rows/objects and orphans; "
|
||||
"fresh and ready kept; repeat is a no-op")
|
||||
# fresh_* are left on purpose: the background sweeper removes them after ORPHAN_GRACE_SECONDS.
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.9 KiB |
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env python3
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def post(c, actor, chat, text, key, expected=201):
|
||||
return c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", expected, actor=actor,
|
||||
body={"text": text}, headers={"Idempotency-Key": key},
|
||||
schema="Message" if expected == 201 else None)
|
||||
|
||||
|
||||
def history(c, actor, chat):
|
||||
return c.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=actor, schema="MessagePage")["json"]["items"]
|
||||
|
||||
|
||||
def db_count(chat_id):
|
||||
sql = "SELECT count(*) FROM messages WHERE chat_id = '%s'" % uuid.UUID(chat_id)
|
||||
out = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql],
|
||||
cwd=ROOT, capture_output=True, text=True)
|
||||
return int(out.stdout.strip()) if out.returncode == 0 else None
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument("--parallel", type=int, default=32)
|
||||
p.add_argument("--rounds", type=int, default=5)
|
||||
args = arguments("Concurrent idempotency through the LB", configure)
|
||||
c = Client(args.base_url, timeout=10)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
for rnd in range(args.rounds):
|
||||
key = "par-%d-%s" % (rnd, uuid.uuid4().hex)
|
||||
text = "одновременно " + key
|
||||
barrier = threading.Barrier(args.parallel)
|
||||
results, errors = [], []
|
||||
|
||||
def worker():
|
||||
local = Client(args.base_url, timeout=10)
|
||||
barrier.wait()
|
||||
try:
|
||||
r = post(local, alice, chat, text, key)
|
||||
results.append((r["json"], r["headers"]["X-Instance-Id"]))
|
||||
except Failure as exc:
|
||||
errors.append(str(exc))
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(args.parallel)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
check(not errors, "concurrent replay failed: %s" % errors[:3])
|
||||
ids = {m["id"] for m, _ in results}
|
||||
instances = Counter(i for _, i in results)
|
||||
check(len(ids) == 1, "concurrent requests created %d messages" % len(ids))
|
||||
check(all(m == results[0][0] for m, _ in results), "replays returned different bodies")
|
||||
check(len(instances) >= 2, "all requests hit one replica; LB not balancing")
|
||||
stored = [m for m in history(c, bob, chat) if m["text"] == text]
|
||||
check(len(stored) == 1, "history has %d copies" % len(stored))
|
||||
print("ok - round %d: %d parallel requests, 1 message, replicas %s" % (rnd + 1, args.parallel, dict(instances)))
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
first = post(c, alice, chat, "оригинал", key)["json"]
|
||||
for _ in range(4):
|
||||
post(c, alice, chat, "другой текст", key, expected=409)
|
||||
check(post(c, alice, chat, "оригинал", key)["json"] == first, "replay changed")
|
||||
print("ok - different body with same key -> 409, original replays unchanged")
|
||||
|
||||
other = post(c, bob, chat, "оригинал", key)["json"]
|
||||
check(other["id"] != first["id"] and other["sender_id"] == bob["id"], "key leaked across users")
|
||||
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "второй", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
||||
third = post(c, alice, chat2, "оригинал", key)["json"]
|
||||
check(third["id"] != first["id"] and third["chat_id"] == chat2["id"], "key leaked across chats")
|
||||
print("ok - same key independent per user and per chat")
|
||||
|
||||
for bad in ("", "with space", "кириллица", "x" * 129, "a/b"):
|
||||
try:
|
||||
post(c, alice, chat, "bad key", bad, expected=400)
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
c.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400, actor=alice, body={"text": "без ключа"})
|
||||
post(c, alice, chat, "ok", "A-Za-z0-9._:-" + "k" * 115)
|
||||
print("ok - missing/invalid Idempotency-Key -> 400, max-length key accepted")
|
||||
|
||||
post(c, eve, chat, "оригинал", key, expected=404)
|
||||
sid = Client(args.base_url)
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=bob)
|
||||
post(sid, bob, chat, "оригинал", key, expected=401)
|
||||
print("ok - replay needs a valid session and chat access (404 outsider, 401 revoked)")
|
||||
|
||||
count = db_count(chat["id"])
|
||||
texts = Counter(m["text"] for m in history(c, alice, chat))
|
||||
check(all(n == 1 for t, n in texts.items() if t.startswith("одновременно")), "duplicates in history")
|
||||
print("ok - DB rows in chat: %s, history items: %d, no duplicate texts" % (count, sum(texts.values())))
|
||||
print("PASS: shared idempotency")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Private bucket checked OUTSIDE the API, least-privilege API credentials, no exposed admin interfaces."""
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from stack import SAMPLE_PNG, api_python, dc, psql
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
PROBE = r'''
|
||||
import json, socket, urllib.request, urllib.error
|
||||
from app import config
|
||||
from app.objects import ObjectStore
|
||||
from botocore.exceptions import ClientError
|
||||
key = %r
|
||||
s = ObjectStore()
|
||||
out = {}
|
||||
def anon(path):
|
||||
try:
|
||||
return urllib.request.urlopen(config.S3_ENDPOINT + path, timeout=3).status
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code
|
||||
out["anonymous_get_object"] = anon("/" + s.bucket + "/" + key)
|
||||
out["anonymous_list_bucket"] = anon("/" + s.bucket + "?list-type=2")
|
||||
out["anonymous_list_all"] = anon("/")
|
||||
def try_(name, fn):
|
||||
try:
|
||||
fn(); out[name] = "ALLOWED"
|
||||
except ClientError as e:
|
||||
out[name] = e.response["Error"]["Code"]
|
||||
pub = '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::%%s/*"}]}' %% s.bucket
|
||||
try_("api_create_bucket", lambda: s._s3.create_bucket(Bucket="evil-bucket"))
|
||||
try_("api_put_bucket_policy_public", lambda: s._s3.put_bucket_policy(Bucket=s.bucket, Policy=pub))
|
||||
try_("api_put_object_acl_public", lambda: s._s3.put_object_acl(Bucket=s.bucket, Key=key, ACL="public-read"))
|
||||
try_("api_delete_bucket", lambda: s._s3.delete_bucket(Bucket=s.bucket))
|
||||
try_("api_get_own_bucket_object", lambda: s._s3.head_object(Bucket=s.bucket, Key=key))
|
||||
def port(p):
|
||||
try:
|
||||
socket.create_connection(("s3", p), timeout=2).close(); return "OPEN"
|
||||
except OSError as e:
|
||||
return type(e).__name__
|
||||
out["s3:9333 master UI"] = port(9333)
|
||||
out["s3:8888 filer UI"] = port(8888)
|
||||
out["s3:8080 volume"] = port(8080)
|
||||
out["s3:9000 S3 API"] = port(9000)
|
||||
print(json.dumps(out))
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("S3 privacy and least privilege")
|
||||
c = Client(args.base_url, timeout=10)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
att = c.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=p.png", 201, actor=alice, raw=SAMPLE_PNG,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||
key = psql("SELECT object_key FROM attachments WHERE id = '%s'" % att["id"])
|
||||
check(key.startswith("originals/") and att["id"].replace("-", "") not in key and "p.png" not in key,
|
||||
"object key must be server-generated, unrelated to id/filename")
|
||||
print("object key: originals/<random 128-bit hex>, unrelated to attachment id and filename")
|
||||
|
||||
r = json.loads(api_python(PROBE % key))
|
||||
for k, v in r.items():
|
||||
print(" %-32s %s" % (k, v))
|
||||
check(r["anonymous_get_object"] == 403 and r["anonymous_list_bucket"] == 403, "bucket is not private")
|
||||
check(r["anonymous_list_all"] in (401, 403), "anonymous ListBuckets allowed")
|
||||
for k in ("api_create_bucket", "api_put_bucket_policy_public", "api_put_object_acl_public", "api_delete_bucket"):
|
||||
check(r[k] != "ALLOWED", k + " must be denied for API credentials")
|
||||
check(r["api_get_own_bucket_object"] == "ALLOWED", "API cannot read its bucket")
|
||||
for k in ("s3:9333 master UI", "s3:8888 filer UI", "s3:8080 volume"):
|
||||
check(r[k] != "OPEN", k + " reachable from the network")
|
||||
|
||||
ports = subprocess.run(["docker", "inspect", "-f", "{{json .NetworkSettings.Ports}}", dc("ps", "-q", "s3").stdout.strip()],
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
check("HostPort" not in ports, "s3 publishes ports on the host")
|
||||
print(" s3 published host ports: none (%s)" % ports)
|
||||
lb = dc("exec", "-T", "lb", "wget", "-q", "-T", "2", "-O", "/dev/null", "http://s3:9000/", check=False)
|
||||
check(lb.returncode != 0, "LB (edge network) can reach S3")
|
||||
print(" lb -> s3:9000 (edge network): unreachable (%s)" % (lb.stderr.strip().splitlines() or ["refused"])[-1])
|
||||
print("PASS: private bucket, least-privilege API credentials, no exposed admin interfaces")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Helpers for student tests: synthetic images (stdlib only) and read-only inspection of the compose stack."""
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
SAMPLE_PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
SAMPLE_JPG = (FIXTURES / "sample.jpg").read_bytes()
|
||||
|
||||
|
||||
def _chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width, height, color_type=2, row=None):
|
||||
"""PNG writer: color_type 0 = gray (1 byte/px), 2 = RGB (3 bytes/px). row(y) returns raw row bytes."""
|
||||
bpp = {0: 1, 2: 3}[color_type]
|
||||
blank = bytes(width * bpp)
|
||||
comp = zlib.compressobj(6)
|
||||
parts = []
|
||||
for y in range(height):
|
||||
parts.append(comp.compress(b"\x00" + (row(y) if row else blank)))
|
||||
parts.append(comp.flush())
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, color_type, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", b"".join(parts)) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def png_header_only(width, height):
|
||||
"""Valid signature + IHDR claiming width x height, tiny IDAT: the pixel limit must fire before decoding."""
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(1000))) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def noise_png(width, height):
|
||||
return png(width, height, 2, row=lambda y: os.urandom(width * 3))
|
||||
|
||||
|
||||
def dc(*args, check=True, timeout=120):
|
||||
out = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if check and out.returncode != 0:
|
||||
raise RuntimeError("docker compose %s failed: %s" % (args[0], out.stderr.strip()[-300:]))
|
||||
return out
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return dc("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAX", "-c", sql).stdout.strip()
|
||||
|
||||
|
||||
def api_python(code, service="api"):
|
||||
"""Run Python inside an API container: it has the API's own (restricted) S3 credentials as secrets."""
|
||||
return dc("exec", "-T", service, "python", "-c", code).stdout.strip()
|
||||
|
||||
|
||||
def count_objects():
|
||||
return int(api_python("from app.objects import ObjectStore; print(sum(1 for _ in ObjectStore().list_originals()))"))
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload -> stop exactly the API replica that served the upload -> download through the other one.
|
||||
|
||||
Repeats so that each replica is once the "uploader" that dies; restores the replica in between.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from stack import ROOT, SAMPLE_PNG, dc
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def container_of(instance_id):
|
||||
for cid in dc("ps", "-q", "api").stdout.split():
|
||||
alias = subprocess.run(["docker", "exec", cid, "cat", "/tmp/instance-id"], capture_output=True, text=True).stdout.strip()
|
||||
if alias == instance_id:
|
||||
return subprocess.run(["docker", "inspect", "-f", "{{.Name}}", cid], capture_output=True, text=True).stdout.strip("/\n")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Attachment survives the loss of the replica that stored it")
|
||||
c = Client(args.base_url, timeout=10)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
stopped = set()
|
||||
for rnd in range(1, 3):
|
||||
# Upload until the serving replica is one we have not stopped yet.
|
||||
for _ in range(10):
|
||||
r = c.call("POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=r%d.png" % rnd, 201, actor=alice,
|
||||
raw=SAMPLE_PNG, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
uploader = r["headers"]["X-Instance-Id"]
|
||||
name = container_of(uploader)
|
||||
if name not in stopped:
|
||||
break
|
||||
att = r["json"]
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=uploader)
|
||||
out = subprocess.run([str(ROOT / "scripts/stop-one.sh")], env=env, capture_output=True, text=True)
|
||||
check(out.returncode == 0, "stop-one.sh failed")
|
||||
print("round %d: uploaded via %s (%s); %s" % (rnd, uploader, name, out.stdout.strip()))
|
||||
served, ok = set(), 0
|
||||
deadline = time.monotonic() + 10
|
||||
while ok < 10:
|
||||
try:
|
||||
d = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "download did not recover within 10 s")
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
check(hashlib.sha256(d["bytes"]).hexdigest() == att["sha256"], "bytes differ after failover")
|
||||
served.add(d["headers"]["X-Instance-Id"])
|
||||
ok += 1
|
||||
check(uploader not in served, "stopped replica still served")
|
||||
print("round %d: 10/10 downloads byte-identical via %s" % (rnd, sorted(served)))
|
||||
stopped.add(name)
|
||||
dc("up", "-d", "--no-build", "--no-recreate", "--wait", "api")
|
||||
print("PASS: attachment downloaded through another replica after its uploader stopped (%d rounds)" % len(stopped))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Experiment: N simultaneous uploads through the LB; peak memory of every API container (cgroup v2).
|
||||
|
||||
Hypothesis: with streaming into a spooled temp file (UPLOAD_SPOOL_BYTES in RAM per upload) and DECODE_CONCURRENCY=1,
|
||||
peak anonymous memory of a replica grows by O(spool x N + one decoded image), not O(file size x N).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from stack import ROOT, dc, noise_png, png
|
||||
from client import Client, Failure
|
||||
|
||||
MB = 1024 * 1024
|
||||
|
||||
|
||||
def sample(cid):
|
||||
out = subprocess.run(["docker", "exec", cid, "sh", "-c",
|
||||
"cat /sys/fs/cgroup/memory.current; grep -E '^(anon|file) ' /sys/fs/cgroup/memory.stat"],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
return {"current": int(out[0]), "anon": int(out[2]), "file": int(out[4])}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--concurrency", type=int, default=10)
|
||||
p.add_argument("--kind", choices=["noise", "pixels"], default="noise",
|
||||
help="noise: ~9.6 MiB incompressible PNG; pixels: 7000x5714 RGB (39.99 Mpx, tiny file, 120 MB decoded)")
|
||||
p.add_argument("--label", default="")
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
|
||||
data = noise_png(1790, 1790) if a.kind == "noise" else png(7000, 5714, 2)
|
||||
c = Client(a.base_url, timeout=120)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
cids = dc("ps", "-q", "api").stdout.split() + dc("ps", "-q", "s3").stdout.split()
|
||||
names = {cid: subprocess.run(["docker", "inspect", "-f", "{{.Name}}", cid], capture_output=True, text=True).stdout.strip("/\n")
|
||||
for cid in cids}
|
||||
base = {cid: sample(cid) for cid in cids}
|
||||
peaks = {cid: dict(base[cid]) for cid in cids}
|
||||
stop = threading.Event()
|
||||
|
||||
def poll(cid):
|
||||
while not stop.is_set():
|
||||
s = sample(cid)
|
||||
for k in s:
|
||||
peaks[cid][k] = max(peaks[cid][k], s[k])
|
||||
|
||||
pollers = [threading.Thread(target=poll, args=(cid,), daemon=True) for cid in cids]
|
||||
for t in pollers:
|
||||
t.start()
|
||||
time.sleep(1)
|
||||
results = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def one(i):
|
||||
t = time.monotonic()
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=m%d.png" % (chat["id"], i), [201, 413, 503], actor=alice,
|
||||
raw=data, headers={"Content-Type": "image/png"})
|
||||
status, inst = r["status"], r["headers"].get("X-Instance-Id")
|
||||
except Failure as exc:
|
||||
status, inst = str(exc)[:60], None
|
||||
with lock:
|
||||
results.append({"status": status, "seconds": round(time.monotonic() - t, 3), "instance": inst})
|
||||
|
||||
started = time.monotonic()
|
||||
workers = [threading.Thread(target=one, args=(i,)) for i in range(a.concurrency)]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join()
|
||||
wall = time.monotonic() - started
|
||||
time.sleep(1.5)
|
||||
stop.set()
|
||||
for t in pollers:
|
||||
t.join()
|
||||
|
||||
lat = sorted(r["seconds"] for r in results)
|
||||
report = {
|
||||
"label": a.label, "kind": a.kind, "file_bytes": len(data), "concurrency": a.concurrency,
|
||||
"statuses": {str(s): sum(1 for r in results if r["status"] == s) for s in {r["status"] for r in results}},
|
||||
"per_instance": {i: sum(1 for r in results if r["instance"] == i) for i in {r["instance"] for r in results}},
|
||||
"wall_seconds": round(wall, 2), "latency_s": {"p50": statistics.median(lat), "max": lat[-1]},
|
||||
"memory_mib": {names[cid]: {
|
||||
"baseline_anon": round(base[cid]["anon"] / MB, 1), "peak_anon": round(peaks[cid]["anon"] / MB, 1),
|
||||
"delta_anon": round((peaks[cid]["anon"] - base[cid]["anon"]) / MB, 1),
|
||||
"baseline_current": round(base[cid]["current"] / MB, 1), "peak_current": round(peaks[cid]["current"] / MB, 1),
|
||||
"peak_file_cache": round(peaks[cid]["file"] / MB, 1)} for cid in cids},
|
||||
"api_env": {k: dc("exec", "-T", "api", "printenv", k, check=False).stdout.strip() or "default"
|
||||
for k in ("UPLOAD_SPOOL_BYTES", "UPLOAD_CONCURRENCY", "DECODE_CONCURRENCY")},
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=1)
|
||||
print(text)
|
||||
if a.output:
|
||||
(ROOT / a.output).write_text(text + "\n")
|
||||
sys.exit(0 if all(r["status"] == 201 for r in results) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user