forked from mtusi2026/mtusi2026lab4
ЛР 4 — БПИ2303 — Лазарев — на 4
Перенос lab3 и вложения в приватном S3 (SeaweedFS 4.50).
- POST /chats/{id}/attachments: потоковый приём PNG/JPEG в безымянный
временный файл, SHA-256 на лету, лимиты 10 MiB / 40 Мпикс до чтения
и декодирования, проверка MIME по содержимому, валидация filename.
- Порядок записи pending -> S3 PUT -> ready с компенсацией; janitor
сверяет БД и bucket (dry-run, grace period, advisory lock).
- GET /attachments/{id} и /content только участникам чата, без redirect;
attachment_ids в сообщениях с проверкой принадлежности чату.
- Отдельные S3-ключи api/janitor/admin с ограниченными правами,
идемпотентный bootstrap bucket, служебные порты SeaweedFS закрыты.
- Ограничение параллельных S3 PUT и MALLOC_ARENA_MAX: пик RSS API
178-189 -> 95-102 MiB; лимиты памяти и restart для SeaweedFS после OOM.
- Тесты уровня 4 (негативные, failover вложений, отказы S3/БД, память)
и доказательства в evidence/, заполнен REPORT.md.
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload -> остановка ИМЕННО обслужившей upload реплики -> download через другую.
|
||||
|
||||
python3 student-tests/attachment_failover.py [--output evidence/attachment-failover.json]
|
||||
|
||||
Для каждой API-реплики по очереди: загрузить файл так, чтобы его обслужила эта реплика
|
||||
(round-robin LB, повторяем до попадания), остановить её scripts/stop-one.sh
|
||||
(SIGTERM, контейнер остаётся остановленным), затем 5 раз скачать оригинал через LB и
|
||||
проверить SHA-256 и что отвечает уже другая реплика. Восстановление — scripts/start-all.sh.
|
||||
Доказывает, что на API нет обязательного локального файла оригинала.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
CONTENT = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
instances = set()
|
||||
for _ in range(10):
|
||||
instances.add(c.call("GET", "/health/ready")["headers"]["X-Instance-Id"])
|
||||
check(len(instances) >= 2, "need >=2 replicas")
|
||||
rounds = []
|
||||
for target in sorted(instances):
|
||||
for _ in range(20): # round-robin: попадаем в нужную реплику за пару попыток
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=failover.png" % chat["id"], 201, actor=alice,
|
||||
raw=CONTENT, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
if r["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise SystemExit("could not hit replica " + target)
|
||||
att = r["json"]
|
||||
stop = subprocess.run([str(ROOT / "scripts/stop-one.sh")], env=dict(os.environ, TARGET_INSTANCE_ID=target),
|
||||
capture_output=True, text=True, timeout=60)
|
||||
check(stop.returncode == 0, "stop-one failed")
|
||||
downloads = []
|
||||
for _ in range(5):
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
|
||||
downloads.append({"instance": d["headers"]["X-Instance-Id"],
|
||||
"sha256_ok": hashlib.sha256(d["bytes"]).hexdigest() == att["sha256"] == hashlib.sha256(CONTENT).hexdigest(),
|
||||
"ms": round(d["elapsed"] * 1000, 1)})
|
||||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
ok = all(x["sha256_ok"] and x["instance"] != target for x in downloads) and meta["status"] == "ready"
|
||||
rounds.append({"uploaded_by": target, "stopped": target, "downloads": downloads, "pass": ok})
|
||||
print(json.dumps(rounds[-1]), flush=True)
|
||||
subprocess.run([str(ROOT / "scripts/start-all.sh")], capture_output=True, timeout=120, check=True)
|
||||
time.sleep(4) # HAProxy: rise 2 * inter 1s
|
||||
summary = {"replicas": sorted(instances), "rounds": rounds, "pass": all(r["pass"] for r in rounds)}
|
||||
print(json.dumps({"pass": summary["pass"], "rounds": len(rounds)}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (уровень 4). Запуск на учебном стенде:
|
||||
|
||||
python3 student-tests/attachments_negative.py [--base-url http://localhost:8080] [--output evidence/attachments-negative.json]
|
||||
|
||||
Использует публичный tests/client.py: каждый ответ проверяется на код, X-Request-Id,
|
||||
X-Instance-Id и (для ошибок) формат {"error":{code,message,request_id}}. Отдельно
|
||||
проверяется, что ни один пользовательский ввод не дал 5xx. Все файлы синтетические и
|
||||
генерируются на лету (большие в Git не хранятся).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
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, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
JPEG = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes()
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
results = []
|
||||
|
||||
|
||||
def chunk(ctype, data):
|
||||
return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width, height, raw, color_type=2, depth=8):
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", raw) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Несжимаемый RGB PNG размером чуть меньше target_bytes (zlib level 0)."""
|
||||
width = 1024
|
||||
row = 1 + width * 3
|
||||
height = (target_bytes - 200) // (row + 6 * 0 + 1)
|
||||
while True:
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
data = png(width, height, zlib.compress(raw, 0))
|
||||
if len(data) <= target_bytes:
|
||||
return data
|
||||
height -= 16
|
||||
|
||||
|
||||
class Suite:
|
||||
def __init__(self, c):
|
||||
self.c = c
|
||||
|
||||
def case(self, name, method, path, expected, actor=None, **kw):
|
||||
try:
|
||||
r = self.c.call(method, path, expected, actor=actor, **kw)
|
||||
code = r["json"]["error"]["code"] if r["json"] and "error" in r["json"] else None
|
||||
results.append({"case": name, "expected": expected, "status": r["status"], "error_code": code, "pass": True})
|
||||
return r
|
||||
except Failure as exc:
|
||||
results.append({"case": name, "expected": expected, "error": str(exc), "pass": False})
|
||||
return None
|
||||
|
||||
def upload(self, name, actor, chat, data, expected, ctype="image/png", filename="f.png", raw_query=None):
|
||||
q = raw_query if raw_query is not None else "filename=" + quote(filename, safe="")
|
||||
return self.case(name, "POST", "/api/v1/chats/%s/attachments?%s" % (chat["id"], q), expected,
|
||||
actor=actor, raw=data, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=60)
|
||||
s = Suite(c)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "второй чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
||||
eve_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "чат Евы", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
|
||||
# --- позитивные контрольные ---
|
||||
ok_png = s.upload("valid PNG fixture", alice, chat, PNG, 201)
|
||||
ok_jpg = s.upload("valid JPEG", bob, chat, JPEG, 201, ctype="image/jpeg", filename="photo.jpg")
|
||||
uni = s.upload("unicode filename", alice, chat, PNG, 201, filename="фото отпуска 🙂.png")
|
||||
if uni:
|
||||
check(uni["json"]["filename"] == "фото отпуска 🙂.png", "unicode filename changed")
|
||||
if ok_jpg:
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % ok_jpg["json"]["id"], actor=alice)
|
||||
check(d["bytes"] == JPEG and d["headers"].get_content_type() == "image/jpeg", "jpeg download mismatch")
|
||||
check(d["headers"].get("X-Content-Type-Options") == "nosniff", "nosniff missing")
|
||||
near = noise_png(MAX_BYTES)
|
||||
big = s.upload("PNG near 10 MiB limit (%d B)" % len(near), alice, chat, near, 201, filename="big.png")
|
||||
if big:
|
||||
check(big["json"]["sha256"] == hashlib.sha256(near).hexdigest(), "big sha mismatch")
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % big["json"]["id"], actor=bob)
|
||||
check(hashlib.sha256(d["bytes"]).hexdigest() == big["json"]["sha256"], "big download mismatch")
|
||||
|
||||
# --- размер и пиксели ---
|
||||
s.upload("too large: 10 MiB + 1 B", alice, chat, near + b"\0" * (MAX_BYTES + 1 - len(near)), 413)
|
||||
s.upload("pixel bomb header 100000x100000", alice, chat, png(100000, 100000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("PNG 7000x6000 = 42 Mpx (> 40 Mpx)", alice, chat, png(7000, 6000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("zlib bomb: 100x100 header, 50 MB inflated", alice, chat,
|
||||
png(100, 100, zlib.compress(b"\0" * 50_000_000, 9), color_type=0), 415)
|
||||
|
||||
# --- повреждённые изображения ---
|
||||
flipped = bytearray(PNG); flipped[5000] ^= 0xFF
|
||||
s.upload("corrupted PNG (byte flipped, bad CRC)", alice, chat, bytes(flipped), 415)
|
||||
s.upload("truncated PNG", alice, chat, PNG[:-4000], 415)
|
||||
s.upload("PNG without IEND", alice, chat, PNG[:-12], 415)
|
||||
s.upload("PNG with appended ZIP (polyglot)", alice, chat, PNG + b"PK\x03\x04" + os.urandom(64), 415)
|
||||
s.upload("truncated JPEG", alice, chat, JPEG[:len(JPEG) // 2], 415, ctype="image/jpeg")
|
||||
s.upload("JPEG header only", alice, chat, JPEG[:200], 415, ctype="image/jpeg")
|
||||
s.upload("empty body", alice, chat, b"", 415)
|
||||
|
||||
# --- подмена MIME ---
|
||||
s.upload("JPEG bytes declared image/png", alice, chat, JPEG, 415)
|
||||
s.upload("PNG bytes declared image/jpeg", alice, chat, PNG, 415, ctype="image/jpeg")
|
||||
s.upload("text declared image/png", alice, chat, b"<html><script>alert(1)</script></html>" * 4, 415)
|
||||
s.upload("GIF declared image/png", alice, chat, b"GIF89a" + os.urandom(200), 415)
|
||||
s.upload("PNG declared text/html", alice, chat, PNG, 415, ctype="text/html")
|
||||
s.upload("PNG declared image/svg+xml", alice, chat, PNG, 415, ctype="image/svg+xml")
|
||||
s.upload("multipart/form-data instead of raw", alice, chat, b"--x\r\n\r\n" + PNG + b"\r\n--x--", 415,
|
||||
ctype="multipart/form-data; boundary=x")
|
||||
|
||||
# --- опасные filename ---
|
||||
for label, query in (("../etc/passwd", "filename=" + quote("../passwd.png", safe="")),
|
||||
("slash", "filename=" + quote("a/b.png", safe="")),
|
||||
("backslash", "filename=" + quote("a\\b.png", safe="")),
|
||||
("NUL", "filename=a%00.png"),
|
||||
("newline", "filename=a%0A.png"),
|
||||
("bidi override U+202E", "filename=" + quote("gnp.exe", safe="")),
|
||||
("..", "filename=.."),
|
||||
("empty", "filename="),
|
||||
("whitespace only", "filename=%20%20"),
|
||||
("256 code points", "filename=" + quote("я" * 256, safe="")),
|
||||
("missing filename", ""),
|
||||
("filename twice", "filename=a.png&filename=b.png"),
|
||||
("invalid UTF-8", "filename=%FF%FE.png")):
|
||||
s.upload("filename: " + label, alice, chat, PNG, 400, raw_query=query)
|
||||
|
||||
# --- доступ и чужие объекты ---
|
||||
eve_att = s.upload("eve uploads to her own chat", eve, eve_chat, PNG, 201)
|
||||
s.upload("non-member uploads to alice chat", eve, chat, PNG, 404)
|
||||
s.case("upload without session", "POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 401,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
s.upload("upload to unknown chat", alice, {"id": str(uuid.uuid4())}, PNG, 404)
|
||||
if eve_att and ok_png:
|
||||
eid, aid = eve_att["json"]["id"], ok_png["json"]["id"]
|
||||
s.case("foreign attachment metadata", "GET", "/api/v1/attachments/" + eid, 404, actor=alice)
|
||||
s.case("foreign attachment content", "GET", "/api/v1/attachments/%s/content" % eid, 404, actor=alice)
|
||||
s.case("eve reads alice attachment", "GET", "/api/v1/attachments/%s/content" % aid, 404, actor=eve)
|
||||
key = lambda: {"Idempotency-Key": uuid.uuid4().hex} # noqa: E731
|
||||
s.case("message with foreign attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [eid]}, headers=key())
|
||||
s.case("message mixing own and foreign ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid, eid]}, headers=key())
|
||||
s.case("attachment of OTHER chat of the same user", "POST", "/api/v1/chats/%s/messages" % chat2["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid]}, headers=key())
|
||||
s.case("unknown attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4())]}, headers=key())
|
||||
s.case("malformed attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": ["not-a-uuid"]}, headers=key())
|
||||
s.case("duplicate attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [aid, aid]}, headers=key())
|
||||
s.case("11 attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, headers=key())
|
||||
s.case("attachment_ids not a list", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": aid}, headers=key())
|
||||
s.case("empty text without attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
||||
actor=alice, body={"text": " "}, headers=key())
|
||||
m = s.case("empty text with attachment (bob links alice's file)", "POST",
|
||||
"/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob,
|
||||
body={"text": "", "attachment_ids": [aid]}, headers=key(), schema="Message")
|
||||
if m:
|
||||
check(m["json"]["attachment_ids"] == [aid], "attachment_ids lost")
|
||||
k = key()
|
||||
s.case("idempotent send with attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"attachment_ids": [aid], "text": "повтор"}, headers=k, schema="Message")
|
||||
s.case("same key, same body (key order changed)", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": [aid]}, headers=k, schema="Message")
|
||||
s.case("same key, different attachment_ids -> 409", "POST", "/api/v1/chats/%s/messages" % chat["id"], 409,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": []}, headers=k)
|
||||
s.case("variant=thumbnail (no variants in lab4)", "GET",
|
||||
"/api/v1/attachments/%s/content?variant=thumbnail" % aid, 404, actor=bob)
|
||||
s.case("variant=bogus", "GET", "/api/v1/attachments/%s/content?variant=bogus" % aid, 400, actor=bob)
|
||||
s.case("variant=original", "GET", "/api/v1/attachments/%s/content?variant=original" % aid, 200, actor=bob)
|
||||
s.case("malformed attachment id in path", "GET", "/api/v1/attachments/zzz", 400, actor=bob)
|
||||
s.case("unknown attachment id", "GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=bob)
|
||||
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
server_errors = [r for r in results if r.get("status", 0) >= 500]
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-55s -> %s %s" % (
|
||||
r["case"], r.get("status", "-"), r.get("error_code") or r.get("error", "")))
|
||||
summary = {"cases": len(results), "failed": len(failed), "server_errors_5xx": len(server_errors),
|
||||
"pass": not failed and not server_errors}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"summary": summary, "results": results}, ensure_ascii=False, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказы между записью в S3 и PostgreSQL и очистка janitor (уровень 4).
|
||||
|
||||
Требует API с FAULT_INJECTION=1 (учебный хук, по умолчанию выключен):
|
||||
FAULT_INJECTION=1 docker compose --env-file .env up -d --wait api
|
||||
python3 student-tests/consistency_faults.py --output evidence/consistency-faults.json
|
||||
docker compose --env-file .env up -d --wait api # вернуть FAULT_INJECTION=0
|
||||
|
||||
Сценарии (каждый — реальный HTTP upload через LB):
|
||||
db-fail-after-s3-put PUT прошёл, «COMMIT» ready упал -> 503; компенсация удаляет объект
|
||||
и pending-строку -> ничего не остаётся;
|
||||
crash-after-s3-put процесс API умирает (os._exit) после PUT -> pending + объект;
|
||||
crash-after-pending процесс умирает до PUT -> pending без объекта;
|
||||
обрыв клиента Content-Length 5 MiB, отправлен 1 MiB, сокет закрыт -> ничего;
|
||||
orphan pending-строку удаляем вручную -> объект без строки;
|
||||
missing объект ready-вложения удаляем в S3 -> только отчёт, download = 503.
|
||||
Затем janitor: dry-run и боевой проход с grace 3600 (свежее не трогает), ожидание
|
||||
grace-seconds, dry-run -> боевой -> повторный (идемпотентность). Контрольное ready-вложение
|
||||
должно остаться доступным побайтно.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
log = []
|
||||
|
||||
|
||||
def sh(*cmd, timeout=120):
|
||||
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit("command failed: %s\n%s" % (" ".join(cmd[:4]), r.stderr[-500:]))
|
||||
return r.stdout
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return sh("docker", "compose", "exec", "-T", "db", "sh", "-c",
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tAc "$0"', sql).strip()
|
||||
|
||||
|
||||
def janitor(grace, dry_run):
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "janitor", "python", "/app/src/janitor.py",
|
||||
"--once", "--grace-seconds", str(grace)] + (["--dry-run"] if dry_run else [])
|
||||
out = sh(*cmd)
|
||||
report = json.loads([line for line in out.splitlines() if line.startswith("{")][-1])
|
||||
keep = ("dry_run", "grace_seconds", "rows_by_status", "objects_total", "abandoned_pending",
|
||||
"orphan_objects", "missing_objects", "deleted_objects", "deleted_rows", "errors", "duration_ms")
|
||||
return {k: report.get(k) for k in keep}
|
||||
|
||||
|
||||
def step(name, **data):
|
||||
entry = dict(step=name, t=round(time.time(), 1), **data)
|
||||
log.append(entry)
|
||||
print(json.dumps(entry, ensure_ascii=False), flush=True)
|
||||
return entry
|
||||
|
||||
|
||||
def wait_api_healthy():
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
states = sh("docker", "compose", "ps", "-a", "--format", "{{.Health}}", "api").split()
|
||||
if states and all(s == "healthy" for s in states):
|
||||
time.sleep(3) # HAProxy rise
|
||||
return
|
||||
time.sleep(1)
|
||||
raise SystemExit("api did not become healthy")
|
||||
|
||||
|
||||
def upload(c, actor, chat, fault=None, expected=201):
|
||||
h = {"Content-Type": "image/png"}
|
||||
if fault:
|
||||
h["X-Fault-Inject"] = fault
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=f.png" % chat["id"], expected,
|
||||
actor=actor, raw=PNG, headers=h, schema="Attachment" if expected == 201 else None)
|
||||
return r["status"], r["json"]
|
||||
except Exception as exc: # обрыв соединения при crash-* тоже допустимый исход
|
||||
return type(exc).__name__, str(exc)[:120]
|
||||
|
||||
|
||||
def interrupted_upload(base, token, chat_id):
|
||||
host, port = base.split("//")[1].split(":")
|
||||
s = socket.create_connection((host, int(port)), timeout=10)
|
||||
s.sendall(("POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: %d\r\n\r\n"
|
||||
% (chat_id, host, token, 5 * 1024 * 1024)).encode())
|
||||
s.sendall(PNG[:8] + b"\0" * (1024 * 1024 - 8))
|
||||
s.close() # клиент «пропал» на середине
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--grace-seconds", type=int, default=20)
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
env = sh("docker", "compose", "exec", "-T", "api", "printenv", "FAULT_INJECTION").strip()
|
||||
check(env == "1", "start api with FAULT_INJECTION=1 first (see docstring)")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
started = psql("SELECT now()")
|
||||
base = janitor(3600, True)
|
||||
step("baseline janitor dry-run", report=base)
|
||||
|
||||
_, control = upload(c, alice, chat)
|
||||
_, victim = upload(c, alice, chat)
|
||||
step("control + victim uploaded (ready)", control=control["id"], victim=victim["id"])
|
||||
|
||||
st, body = upload(c, alice, chat, "db-fail-after-s3-put", expected=503)
|
||||
after_comp = janitor(3600, True)
|
||||
step("db-fail-after-s3-put -> compensation", status=st, report=after_comp,
|
||||
leftover_pending=after_comp["rows_by_status"].get("pending", 0) - base["rows_by_status"].get("pending", 0),
|
||||
leftover_objects=after_comp["objects_total"] - base["objects_total"] - 2)
|
||||
|
||||
for fault in ("crash-after-s3-put", "crash-after-s3-put", "crash-after-pending"):
|
||||
st, body = upload(c, alice, chat, fault, expected=[502, 503])
|
||||
step(fault, client_saw=st)
|
||||
wait_api_healthy()
|
||||
|
||||
interrupted_upload(args.base_url, alice["token"], chat["id"])
|
||||
time.sleep(2)
|
||||
step("client aborted upload at 1 of 5 MiB", report=janitor(3600, True))
|
||||
|
||||
pending = psql("SELECT id || ' ' || (object_key IS NOT NULL) FROM attachments WHERE status='pending' "
|
||||
"AND created_at >= '%s' ORDER BY created_at" % started).splitlines()
|
||||
step("pending rows left by crashes", pending=len(pending))
|
||||
check(len(pending) == 3, "expected 3 pending rows from crashes")
|
||||
orphan_id = pending[0].split()[0]
|
||||
psql("DELETE FROM attachments WHERE id = '%s'" % orphan_id)
|
||||
step("orphan injected: pending row deleted, object kept", row=orphan_id)
|
||||
victim_key = psql("SELECT object_key FROM attachments WHERE id = '%s'" % victim["id"])
|
||||
sh("docker", "compose", "--profile", "tools", "run", "--rm", "--entrypoint", "python", "s3-check", "-c",
|
||||
"import sys; sys.argv=['x']; exec(open('/app/student-tests/s3_private_check.py').read().split('results = []')[0]);"
|
||||
"client('api').remove_object(BUCKET, %r)" % victim_key)
|
||||
dl = c.call("GET", "/api/v1/attachments/%s/content" % victim["id"], 503, actor=bob)
|
||||
step("missing injected: victim object deleted in S3", download_status=dl["status"])
|
||||
|
||||
fresh_dry = janitor(3600, True)
|
||||
fresh_run = janitor(3600, False)
|
||||
step("janitor grace=3600 (all fresh): dry-run", report=fresh_dry)
|
||||
step("janitor grace=3600 (all fresh): real run deletes nothing", report=fresh_run)
|
||||
check(fresh_run["deleted_objects"] == 0 and fresh_run["deleted_rows"] == 0, "fresh data deleted")
|
||||
|
||||
time.sleep(args.grace_seconds + 2)
|
||||
dry = janitor(args.grace_seconds, True)
|
||||
step("after grace: dry-run", report=dry)
|
||||
real = janitor(args.grace_seconds, False)
|
||||
step("after grace: real run", report=real)
|
||||
again = janitor(args.grace_seconds, False)
|
||||
step("after grace: repeated run (idempotent)", report=again)
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % control["id"], actor=bob)
|
||||
control_ok = hashlib.sha256(d["bytes"]).hexdigest() == control["sha256"]
|
||||
still = psql("SELECT count(*) FROM attachments WHERE status='pending' AND created_at >= '%s'" % started)
|
||||
step("control attachment still intact", sha256_ok=control_ok, pending_left=int(still))
|
||||
|
||||
ok = (log[2]["leftover_pending"] == 0 and log[2]["leftover_objects"] == 0
|
||||
and dry["abandoned_pending"] >= 2 and dry["orphan_objects"] >= 1 and dry["missing_objects"] >= 1
|
||||
and dry["deleted_objects"] == 0
|
||||
and real["deleted_rows"] >= 2 and again["abandoned_pending"] == 0 and again["orphan_objects"] == 0
|
||||
and again["deleted_objects"] == 0 and again["missing_objects"] >= 1
|
||||
and control_ok and int(still) == 0)
|
||||
print(json.dumps({"pass": ok}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"pass": ok, "steps": log}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка диапазона дат cursor: некорректная дата должна давать 400, а не 500."""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, ca_file=args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
checks = 0
|
||||
for kind, scope, path in (
|
||||
("messages", chat["id"], "/api/v1/chats/" + chat["id"] + "/messages"),
|
||||
("chats", alice["id"], "/api/v1/chats"),
|
||||
):
|
||||
for timestamp, expected in ((-10**17, 400), (-62135596800000001, 400), (0, 200)):
|
||||
payload = {"k": kind, "s": scope, "t": timestamp, "i": str(uuid.uuid4())}
|
||||
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
client.call("GET", path + "?cursor=" + quote(cursor, safe=""), expected, actor=alice)
|
||||
checks += 1
|
||||
print("PASS: %d cursor date boundary checks; invalid dates return 400." % checks)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказ/замена API-реплики ПОД НАГРУЗКОЙ: RPS, ошибки, время обнаружения и восстановления (lab3, уровень 4).
|
||||
|
||||
Что делает:
|
||||
* CONCURRENCY потоков в closed-loop шлют смесь запросов через LB: POST сообщения
|
||||
(с Idempotency-Key) и GET истории (limit=20) в пропорции 1:1;
|
||||
* после неуспешного/неопределённого POST поток повторяет ТОТ ЖЕ ключ и тело (как
|
||||
требует контракт), поэтому подтверждённых дублей быть не должно;
|
||||
* на секунде --action-at запускается --action (например, docker stop/kill контейнера
|
||||
или scripts/rolling-update.sh), его stdout/stderr пишутся в отдельный лог;
|
||||
* параллельно каждые 200 мс опрашивается CSV статистики HAProxy: фиксируются моменты
|
||||
UP -> DOWN / DOWN -> UP серверов backend (время обнаружения отказа LB);
|
||||
* в конце читается вся история чата (тем же токеном) и проверяется: все подтверждённые
|
||||
сообщения на месте, дублей нет.
|
||||
|
||||
Метрики (все времена — от старта action):
|
||||
errors_total / error_rate — неуспешные попытки (HTTP != ожидаемого, timeout, разрыв);
|
||||
error_window_s — от первой до последней ошибки после старта action;
|
||||
recovery_s — конец окна ошибок (дальше все запросы успешны), 0 если ошибок нет;
|
||||
post_action_ok_rps/capacity_ratio — успешный RPS после действия и его доля от базового;
|
||||
lb_down_detected_s — когда HAProxy пометил сервер DOWN;
|
||||
target_last_seen_s — последний ответ от остановленной реплики.
|
||||
|
||||
Ограничения: closed-loop генератор (coordinated omission), клиент на том же хосте, что и
|
||||
стенд; цифры RPS сравнимы только между прогонами этого же скрипта на этом же ноутбуке.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
TIMEOUT = 2.0
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
s = sorted(values)
|
||||
return round(s[min(len(s) - 1, int(round(p / 100 * (len(s) - 1))))] * 1000, 1)
|
||||
|
||||
|
||||
class Bench:
|
||||
def __init__(self, a):
|
||||
self.a = a
|
||||
self.base = a.base_url.rstrip("/")
|
||||
self.lock = threading.Lock()
|
||||
self.t0 = None
|
||||
self.stop = threading.Event()
|
||||
self.per_sec = defaultdict(lambda: {"ok": 0, "err": 0, "inst": Counter(), "ver": Counter()})
|
||||
self.errors = [] # (t, kind)
|
||||
self.lat = [] # успешные задержки, с
|
||||
self.confirmed = {} # message id -> text
|
||||
self.retried_posts = 0
|
||||
self.lb_events = []
|
||||
self.inst_last_seen = {}
|
||||
|
||||
def now(self):
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def record(self, ok, dt, inst=None, ver=None, kind=None):
|
||||
t = self.now()
|
||||
with self.lock:
|
||||
b = self.per_sec[int(t)]
|
||||
if ok:
|
||||
b["ok"] += 1
|
||||
self.lat.append(dt)
|
||||
if inst:
|
||||
b["inst"][inst] += 1
|
||||
self.inst_last_seen[inst] = t
|
||||
if ver:
|
||||
b["ver"][ver] += 1
|
||||
else:
|
||||
b["err"] += 1
|
||||
self.errors.append((round(t, 3), kind))
|
||||
|
||||
def request(self, method, path, body=None, headers=None, expected=200):
|
||||
h = {"Authorization": "Bearer " + self.token}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(self.base + path, data=data, method=method, headers=h)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
payload = json.loads(r.read())
|
||||
ok = r.status == expected
|
||||
self.record(ok, time.monotonic() - start, r.headers.get("X-Instance-Id"),
|
||||
r.headers.get("X-App-Version"), None if ok else "http_%d" % r.status)
|
||||
return payload if ok else None
|
||||
except urllib.error.HTTPError as e:
|
||||
self.record(False, 0, kind="http_%d" % e.code)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.record(False, 0, kind=type(e).__name__)
|
||||
return None
|
||||
|
||||
def worker(self, n):
|
||||
chat_path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
key = text = None
|
||||
i = 0
|
||||
while not self.stop.is_set():
|
||||
i += 1
|
||||
if i % 2:
|
||||
if key is None: # новый логический запрос; после ошибки ключ НЕ меняется
|
||||
key = "bench-%d-%s" % (n, uuid.uuid4().hex)
|
||||
text = "Нагрузка " + key
|
||||
else:
|
||||
with self.lock:
|
||||
self.retried_posts += 1
|
||||
msg = self.request("POST", chat_path, {"text": text}, {"Idempotency-Key": key}, 201)
|
||||
if msg is not None:
|
||||
with self.lock:
|
||||
self.confirmed[msg["id"]] = msg["text"]
|
||||
key = None
|
||||
else:
|
||||
self.request("GET", chat_path + "?limit=20")
|
||||
|
||||
def poll_lb(self):
|
||||
prev = {}
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
with urllib.request.urlopen(self.a.stats_url, timeout=1) as r:
|
||||
rows = list(csv.reader(io.StringIO(r.read().decode().lstrip("# "))))
|
||||
head = rows[0]
|
||||
ix = {k: head.index(k) for k in ("pxname", "svname", "status", "addr")}
|
||||
for row in rows[1:]:
|
||||
if len(row) <= ix["addr"] or row[ix["pxname"]] != "be_api" or row[ix["svname"]] == "BACKEND":
|
||||
continue
|
||||
sv, st, addr = row[ix["svname"]], row[ix["status"]].split(" ")[0], row[ix["addr"]]
|
||||
if sv in prev and prev[sv] != (st, addr):
|
||||
self.lb_events.append({"t": round(self.now(), 2), "server": sv, "addr": addr,
|
||||
"from": prev[sv][0], "to": st})
|
||||
prev[sv] = (st, addr)
|
||||
except Exception: # noqa: BLE001 — статистика вспомогательная
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
def history(self):
|
||||
c, path, items = self.client, "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100", []
|
||||
while True:
|
||||
page = c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
if page["next_cursor"] is None:
|
||||
return items
|
||||
path = "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
def run(self):
|
||||
a = self.a
|
||||
self.client = Client(self.base, timeout=10)
|
||||
self.alice, _bob, _eve, self.chat = self.client.bootstrap()
|
||||
self.token = self.alice["token"]
|
||||
self.t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(a.concurrency)]
|
||||
threads.append(threading.Thread(target=self.poll_lb, daemon=True))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.action_at)
|
||||
action = {"command": a.action, "started_s": round(self.now(), 3)}
|
||||
log = open(a.action_log, "w", encoding="utf-8") if a.action_log else subprocess.DEVNULL
|
||||
proc = subprocess.Popen(shlex.split(a.action), stdout=log, stderr=subprocess.STDOUT)
|
||||
rc = proc.wait(timeout=a.duration)
|
||||
action.update(finished_s=round(self.now(), 3), exit_code=rc)
|
||||
remaining = a.duration - self.now()
|
||||
if remaining > 0:
|
||||
time.sleep(remaining)
|
||||
self.stop.set()
|
||||
for t in threads:
|
||||
t.join(timeout=TIMEOUT + 1)
|
||||
return self.summarize(action)
|
||||
|
||||
def summarize(self, action):
|
||||
a, t_act = self.a, action["started_s"]
|
||||
secs = sorted(self.per_sec)
|
||||
base = [self.per_sec[s]["ok"] for s in secs if 1 <= s < int(t_act)] # 1-я секунда — прогрев
|
||||
baseline = sum(base) / len(base) if base else 0
|
||||
after = [(round(t - t_act, 3), k) for t, k in self.errors if t >= t_act]
|
||||
# Восстановление = конец окна ошибок: после этого момента все запросы до конца
|
||||
# прогона успешны. Если ошибок не было — 0. Мощность после отказа меряем отдельно:
|
||||
# при меньшем числе реплик RPS законно ниже (лимиты CPU на реплику).
|
||||
recovery = after[-1][0] if after else 0.0
|
||||
tail_secs = [s for s in secs if int(action.get("finished_s", t_act)) + 2 <= s < a.duration - 1]
|
||||
post = [self.per_sec[s]["ok"] for s in tail_secs]
|
||||
post_rps = sum(post) / len(post) if post else 0
|
||||
writes_after = any(self.per_sec[s]["ok"] > 0 for s in tail_secs)
|
||||
target = a.target_instance
|
||||
hist = self.history()
|
||||
ids = [m["id"] for m in hist]
|
||||
texts = [m["text"] for m in hist]
|
||||
lost = [i for i in self.confirmed if i not in set(ids)]
|
||||
timeline = [{"t": s, "ok": self.per_sec[s]["ok"], "err": self.per_sec[s]["err"],
|
||||
"instances": dict(self.per_sec[s]["inst"]), "versions": dict(self.per_sec[s]["ver"])}
|
||||
for s in secs]
|
||||
total_ok = sum(b["ok"] for b in self.per_sec.values())
|
||||
total_err = len(self.errors)
|
||||
summary = {
|
||||
"label": a.label,
|
||||
"concurrency": a.concurrency, "duration_s": a.duration, "request_timeout_s": TIMEOUT,
|
||||
"action": action,
|
||||
"baseline_ok_rps": round(baseline, 1),
|
||||
"overall_ok_rps": round(total_ok / a.duration, 1),
|
||||
"requests_ok": total_ok, "errors_total": total_err,
|
||||
"error_rate": round(total_err / max(1, total_ok + total_err), 5),
|
||||
"errors_by_kind": dict(Counter(k for _, k in self.errors)),
|
||||
"error_window_s": [after[0][0], after[-1][0]] if after else None,
|
||||
"recovery_s": recovery,
|
||||
"post_action_ok_rps": round(post_rps, 1),
|
||||
"capacity_ratio": round(post_rps / baseline, 2) if baseline else None,
|
||||
"latency_ok_ms": {"p50": percentile(self.lat, 50), "p95": percentile(self.lat, 95),
|
||||
"p99": percentile(self.lat, 99)},
|
||||
"target_instance": target,
|
||||
"target_last_seen_s": (round(self.inst_last_seen[target] - t_act, 3)
|
||||
if target in self.inst_last_seen else None),
|
||||
"lb_events": [dict(e, t=round(e["t"] - t_act, 2)) for e in self.lb_events],
|
||||
"posts_retried_same_key": self.retried_posts,
|
||||
"confirmed_messages": len(self.confirmed),
|
||||
"history_messages": len(hist), "lost_confirmed": len(lost),
|
||||
"duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"timeline": timeline,
|
||||
}
|
||||
summary["pass"] = (summary["lost_confirmed"] == 0 and summary["duplicate_ids"] == 0
|
||||
and summary["duplicate_texts"] == 0 and action["exit_code"] == 0
|
||||
and writes_after and recovery <= 10)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Отказ/замена реплики под нагрузкой")
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--stats-url", default="http://127.0.0.1:8404/stats;csv")
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--duration", type=float, default=40)
|
||||
p.add_argument("--action-at", type=float, default=10)
|
||||
p.add_argument("--action", required=True, help="команда без shell, например 'docker stop -t 20 <id>'")
|
||||
p.add_argument("--action-log")
|
||||
p.add_argument("--target-instance", help="X-Instance-Id реплики, которую останавливает action")
|
||||
p.add_argument("--label", default="")
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
s = Bench(a).run()
|
||||
brief = {k: v for k, v in s.items() if k != "timeline"}
|
||||
print(json.dumps(brief, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(s, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if s["pass"] else "FAIL")
|
||||
return 0 if s["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4).
|
||||
|
||||
Сценарий на каждый раунд:
|
||||
A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело.
|
||||
Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик,
|
||||
в истории ровно одно сообщение с этим текстом.
|
||||
B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно
|
||||
тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет.
|
||||
|
||||
Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их
|
||||
по репликам. Токены только в памяти; синтетические пользователи создаются заново.
|
||||
|
||||
python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата)
|
||||
|
||||
|
||||
def post(base, token, chat_id, key, text, barrier, out, idx):
|
||||
data = json.dumps({"text": text}).encode()
|
||||
req = urllib.request.Request(
|
||||
base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json",
|
||||
"Idempotency-Key": key, "Connection": "close"})
|
||||
barrier.wait()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text)
|
||||
except urllib.error.HTTPError as e:
|
||||
out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text)
|
||||
except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку
|
||||
out[idx] = (0, repr(e), None, text)
|
||||
|
||||
|
||||
def burst(base, token, chat_id, key, texts):
|
||||
barrier = threading.Barrier(len(texts))
|
||||
out = [None] * len(texts)
|
||||
threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i))
|
||||
for i, t in enumerate(texts)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return out
|
||||
|
||||
|
||||
def history_texts(c, actor, chat):
|
||||
from urllib.parse import quote
|
||||
texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
while True:
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
if page["next_cursor"] is None:
|
||||
return texts
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--rounds", type=int, default=20)
|
||||
p.add_argument("--parallel", type=int, default=16)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
c = Client(base)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
token = alice["token"]
|
||||
problems, instances = [], Counter()
|
||||
stats = {"same_body": Counter(), "conflicting_body": Counter()}
|
||||
|
||||
for rnd in range(a.rounds):
|
||||
# A) одинаковое тело
|
||||
key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex
|
||||
res = burst(base, token, chat["id"], key, [text] * a.parallel)
|
||||
stats["same_body"].update(str(r[0]) for r in res)
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
seen = {r[2] for r in res if r[2]}
|
||||
instances.update(r[2] for r in res if r[2])
|
||||
if any(r[0] != 201 for r in res) or len(ids) != 1:
|
||||
problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids)))
|
||||
if len(seen) < 2:
|
||||
problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen)))
|
||||
|
||||
# B) тот же ключ, два разных тела вперемешку
|
||||
key = "mixed-" + uuid.uuid4().hex
|
||||
t1, t2 = "Тело A " + key, "Тело B " + key
|
||||
res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2))
|
||||
stats["conflicting_body"].update(str(r[0]) for r in res)
|
||||
winners = {r[3] for r in res if r[0] == 201}
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
bad = [r[0] for r in res if r[0] not in (201, 409)]
|
||||
losers_ok = all(r[0] == 409 for r in res if r[3] not in winners)
|
||||
if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok:
|
||||
problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad))
|
||||
|
||||
texts = history_texts(c, alice, chat)
|
||||
dupes = [t for t, n in Counter(texts).items() if n > 1]
|
||||
if dupes:
|
||||
problems.append("duplicated messages in history: %d" % len(dupes))
|
||||
summary = {
|
||||
"rounds": a.rounds, "parallel_per_burst": a.parallel,
|
||||
"requests_total": a.rounds * a.parallel * 2,
|
||||
"status_counts": {k: dict(v) for k, v in stats.items()},
|
||||
"replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()),
|
||||
"messages_in_history": len(texts), "expected_messages": a.rounds * 2,
|
||||
"duplicates": len(dupes), "problems": problems,
|
||||
}
|
||||
if len(texts) != a.rounds * 2:
|
||||
problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2))
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if not problems else "FAIL")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Шторм входов: много параллельных POST /auth/sessions с неверным паролем через LB.
|
||||
|
||||
Зачем: scrypt (N=2^15, r=8) берёт ~32 MiB на одну проверку пароля, лимит API-реплики
|
||||
256 MiB. Без ограничения параллельных проверок несколько одновременных входов
|
||||
приводят к OOM-kill реплики. Скрипт показывает, переживают ли реплики такой шторм.
|
||||
|
||||
Что измеряется:
|
||||
* статусы ответов шторма (ожидаем 401 и, при перегрузке, 503 с Retry-After) и
|
||||
ответы не в JSON-формате ошибки контракта (например HTML-страницы HAProxy);
|
||||
* «жертва»: параллельный поток раз в 50 мс читает /users/me действующим токеном —
|
||||
обычные пользователи не должны получать ошибки из-за шторма входов;
|
||||
* состояние API-контейнеров до/после: OOMKilled, RestartCount, StartedAt.
|
||||
|
||||
Пример: python3 student-tests/login_flood.py --parallel 24 --duration 20 --output evidence/login-flood.json
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
TIMEOUT = 10.0
|
||||
|
||||
|
||||
def http(base, method, path, headers=None, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = dict(headers or {})
|
||||
if data is not None:
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
return r.status, r.headers, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers, e.read()
|
||||
|
||||
|
||||
def is_contract_error(headers, raw):
|
||||
if not (headers.get("Content-Type") or "").startswith("application/json"):
|
||||
return False
|
||||
try:
|
||||
err = json.loads(raw)["error"]
|
||||
return bool(err["code"] and err["message"] and err["request_id"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def api_containers():
|
||||
ids = subprocess.run(["docker", "compose", "ps", "-a", "-q", "api"], capture_output=True,
|
||||
text=True, check=True).stdout.split()
|
||||
out = {}
|
||||
for cid in ids:
|
||||
info = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, text=True,
|
||||
check=True).stdout)[0]
|
||||
out[info["Name"].lstrip("/")] = {
|
||||
"status": info["State"]["Status"], "oom_killed": info["State"]["OOMKilled"],
|
||||
"restart_count": info["RestartCount"], "started_at": info["State"]["StartedAt"]}
|
||||
return out
|
||||
|
||||
|
||||
def oom_events(since):
|
||||
"""Имена контейнеров, получивших OOM с момента since (unix time): флаг OOMKilled
|
||||
сбрасывается после рестарта по restart-policy, поэтому смотрим события Docker."""
|
||||
out = subprocess.run(["docker", "events", "--since", str(int(since)), "--until", str(int(time.time()) + 1),
|
||||
"--filter", "type=container", "--filter", "event=oom",
|
||||
"--format", "{{.Actor.Attributes.name}}"], capture_output=True, text=True).stdout
|
||||
return sorted(Counter(out.split()).items())
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--parallel", type=int, default=24)
|
||||
p.add_argument("--duration", type=float, default=20)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
|
||||
username = "flood_" + uuid.uuid4().hex[:10]
|
||||
password = "correct-horse-" + uuid.uuid4().hex[:8]
|
||||
st, _, _ = http(base, "POST", "/api/v1/users",
|
||||
body={"username": username, "display_name": "Flood", "password": password})
|
||||
assert st == 201, st
|
||||
basic = base64.b64encode(("%s:%s" % (username, password)).encode()).decode()
|
||||
st, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
assert st == 201, st
|
||||
token = json.loads(raw)["token"]
|
||||
bad = base64.b64encode(("%s:wrong-password-123" % username).encode()).decode()
|
||||
|
||||
before = api_containers()
|
||||
wall0 = time.time()
|
||||
stop = threading.Event()
|
||||
lock = threading.Lock()
|
||||
flood, victim = Counter(), Counter()
|
||||
non_json_errors = Counter()
|
||||
retry_after_503 = [0, 0] # [503 всего, из них с Retry-After]
|
||||
|
||||
def record(counter, status, headers, raw):
|
||||
with lock:
|
||||
counter[str(status)] += 1
|
||||
if status >= 400 and not is_contract_error(headers, raw):
|
||||
non_json_errors[str(status)] += 1
|
||||
if status == 503 and counter is flood:
|
||||
retry_after_503[0] += 1
|
||||
retry_after_503[1] += bool(headers.get("Retry-After"))
|
||||
|
||||
def flooder():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(flood, *http(base, "POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + bad}))
|
||||
except Exception as exc: # обрыв соединения, timeout
|
||||
with lock:
|
||||
flood["exc:" + type(exc).__name__] += 1
|
||||
|
||||
def prober():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(victim, *http(base, "GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token}))
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
victim["exc:" + type(exc).__name__] += 1
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=flooder, daemon=True) for _ in range(a.parallel)]
|
||||
threads.append(threading.Thread(target=prober, daemon=True))
|
||||
t0 = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.duration)
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join(TIMEOUT + 1)
|
||||
elapsed = time.monotonic() - t0
|
||||
time.sleep(3) # дать restart-policy отработать, если реплика упала
|
||||
after = api_containers()
|
||||
|
||||
restarted = [n for n in after if n in before and (
|
||||
after[n]["restart_count"] != before[n]["restart_count"]
|
||||
or after[n]["started_at"] != before[n]["started_at"])]
|
||||
victim_ok = victim.get("200", 0)
|
||||
victim_total = sum(victim.values())
|
||||
summary = {
|
||||
"parallel": a.parallel, "duration_s": round(elapsed, 1),
|
||||
"flood_statuses": dict(flood), "flood_rps": round(sum(flood.values()) / elapsed, 1),
|
||||
"flood_503_with_retry_after": "%d/%d" % (retry_after_503[1], retry_after_503[0]),
|
||||
"victim_statuses": dict(victim),
|
||||
"victim_error_rate": round(1 - victim_ok / victim_total, 4) if victim_total else None,
|
||||
"non_contract_error_bodies": dict(non_json_errors),
|
||||
"containers_before": before, "containers_after": after,
|
||||
"oom_events": dict(oom_events(wall0)),
|
||||
"restarted": restarted,
|
||||
}
|
||||
summary["pass"] = (not summary["oom_events"] and not restarted and victim_total > 0
|
||||
and victim_ok == victim_total and not non_json_errors)
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
with open(a.output, "w", encoding="utf-8") as f:
|
||||
f.write(text + "\n")
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Недоступность S3: stop (порт закрыт) и pause (S3 «завис», TCP не отвечает).
|
||||
|
||||
python3 student-tests/s3_outage.py [--output evidence/s3-outage.json]
|
||||
|
||||
Ожидания: upload и download — быстрый 503 unavailable c Retry-After (не 500 и не
|
||||
таймаут LB), текстовые сообщения и /health/ready продолжают работать (S3 не входит в
|
||||
readiness), после восстановления S3 загрузка снова 201 без перезапуска API.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
log = []
|
||||
|
||||
|
||||
def probe(c, alice, chat, att):
|
||||
out = {}
|
||||
for name, args in (
|
||||
("upload", ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"])),
|
||||
("download", ("GET", "/api/v1/attachments/%s/content" % att["id"])),
|
||||
("text_message", ("POST", "/api/v1/chats/%s/messages" % chat["id"])),
|
||||
("ready", ("GET", "/health/ready"))):
|
||||
kw = {}
|
||||
if name == "upload":
|
||||
kw = {"raw": PNG, "headers": {"Content-Type": "image/png"}}
|
||||
if name == "text_message":
|
||||
kw = {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}
|
||||
t = time.monotonic()
|
||||
r = c.call(*args, [200, 201, 503, 502, 504], actor=alice if name != "ready" else None, **kw)
|
||||
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
|
||||
"code": (r["json"] or {}).get("error", {}).get("code"),
|
||||
"retry_after": r["headers"].get("Retry-After")}
|
||||
return out
|
||||
|
||||
|
||||
def phase(name, c, alice, chat, att):
|
||||
entry = {"phase": name, "probe": probe(c, alice, chat, att)}
|
||||
log.append(entry)
|
||||
print(json.dumps(entry, ensure_ascii=False), flush=True)
|
||||
return entry
|
||||
|
||||
|
||||
def recover(c, alice, chat, started):
|
||||
while time.monotonic() - started < 120:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=r.png" % chat["id"], [201, 503], actor=alice,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
if r["status"] == 201:
|
||||
return round(time.monotonic() - started, 1)
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 201, actor=alice, raw=PNG,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||
phase("baseline", c, alice, chat, att)
|
||||
for action, undo in ((["stop", "s3"], ["start", "s3"]), (["pause", "s3"], ["unpause", "s3"])):
|
||||
subprocess.run(["docker", "compose"] + action, cwd=ROOT, check=True, capture_output=True)
|
||||
time.sleep(1)
|
||||
phase("immediately after `%s` (S3Health not yet stale)" % " ".join(action), c, alice, chat, att)
|
||||
time.sleep(4)
|
||||
phase("S3 down for 5 s (`%s`)" % " ".join(action), c, alice, chat, att)
|
||||
subprocess.run(["docker", "compose"] + undo, cwd=ROOT, check=True, capture_output=True)
|
||||
t0 = time.monotonic()
|
||||
rec = recover(c, alice, chat, t0)
|
||||
log.append({"phase": "recovery after `%s`" % " ".join(undo), "upload_201_after_s": rec})
|
||||
print(json.dumps(log[-1]), flush=True)
|
||||
down = [e for e in log if e.get("phase", "").startswith("S3 down")]
|
||||
ok = all(e["probe"]["upload"]["status"] == 503 and e["probe"]["download"]["status"] == 503
|
||||
and e["probe"]["text_message"]["status"] == 201 and e["probe"]["ready"]["status"] == 200
|
||||
for e in down) and all(e.get("upload_201_after_s") is not None for e in log if "upload_201_after_s" in e)
|
||||
no5xx = all(p["status"] in (200, 201, 503) for e in log if "probe" in e for p in e["probe"].values())
|
||||
print(json.dumps({"pass": ok and no5xx, "only_200_201_503": no5xx}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"pass": ok and no5xx, "phases": log}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok and no5xx else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка приватности bucket и ограничений ключей ВНЕ API (внутри backend-сети).
|
||||
|
||||
docker compose --profile tools run --rm s3-check
|
||||
|
||||
Проверяет напрямую на S3 (минуя API и его ACL):
|
||||
* анонимные GET объекта / ListBucket / PUT -> 403;
|
||||
* ключ api: Put/Get/Delete своего тестового объекта можно; ListBucket, CreateBucket,
|
||||
DeleteBucket, PutBucketPolicy — AccessDenied; другой bucket — AccessDenied;
|
||||
* ключ janitor: List и Delete можно; GetObject (чтение содержимого) — AccessDenied;
|
||||
* служебные порты SeaweedFS (master 9333, volume 8080, filer 8888, IAM 8111,
|
||||
Iceberg 8181, Lance 9101) из backend-сети недоступны — открыт только S3 :8333.
|
||||
Выход 0 только если все ожидания выполнены. Ключи не печатаются.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
sys.path.insert(0, "/app/src")
|
||||
from minio import Minio # noqa: E402
|
||||
from minio.error import S3Error # noqa: E402
|
||||
|
||||
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
HOST = urlsplit(ENDPOINT).netloc
|
||||
|
||||
|
||||
def key(name):
|
||||
with open("/run/secrets/" + name) as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
def client(who):
|
||||
return Minio(HOST, access_key=key("s3_%s_access_key" % who), secret_key=key("s3_%s_secret_key" % who),
|
||||
secure=False, region=os.environ.get("S3_REGION", "us-east-1"))
|
||||
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
def expect(name, should_succeed, fn):
|
||||
try:
|
||||
fn()
|
||||
ok, got = should_succeed, "allowed"
|
||||
except S3Error as exc:
|
||||
ok, got = not should_succeed, exc.code
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok, got = False, type(exc).__name__
|
||||
results.append({"check": name, "expected": "allowed" if should_succeed else "denied", "got": got, "pass": ok})
|
||||
|
||||
|
||||
def http_status(method, url, data=None):
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=3) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
api, janitor = client("api"), client("janitor")
|
||||
probe = "originals/s3check-" + uuid.uuid4().hex
|
||||
expect("api: PutObject в свой bucket", True, lambda: api.put_object(BUCKET, probe, io.BytesIO(b"x" * 16), 16))
|
||||
for name, method, url, data in (
|
||||
("anonymous GET object", "GET", "%s/%s/%s" % (ENDPOINT, BUCKET, probe), None),
|
||||
("anonymous ListBucket", "GET", "%s/%s?list-type=2" % (ENDPOINT, BUCKET), None),
|
||||
("anonymous ListAllMyBuckets", "GET", ENDPOINT + "/", None),
|
||||
("anonymous PUT object", "PUT", "%s/%s/anon-%s" % (ENDPOINT, BUCKET, uuid.uuid4().hex), b"z")):
|
||||
code = http_status(method, url, data)
|
||||
results.append({"check": name, "expected": "403", "got": code, "pass": code in (401, 403)})
|
||||
expect("api: GetObject", True, lambda: api.get_object(BUCKET, probe).read())
|
||||
expect("api: ListBucket", False, lambda: list(api.list_objects(BUCKET, recursive=True)))
|
||||
expect("api: CreateBucket", False, lambda: api.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteBucket", False, lambda: api.remove_bucket(BUCKET))
|
||||
expect("api: PutBucketPolicy (сделать публичным)", False, lambda: api.set_bucket_policy(BUCKET, json.dumps({
|
||||
"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": "*", "Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::%s/*" % BUCKET]}]})))
|
||||
expect("janitor: GetObject (чтение содержимого)", False, lambda: janitor.get_object(BUCKET, probe).read())
|
||||
expect("janitor: ListBucket", True, lambda: list(janitor.list_objects(BUCKET, prefix="originals/", recursive=True)))
|
||||
expect("janitor: CreateBucket", False, lambda: janitor.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteObject (компенсация)", True, lambda: api.remove_object(BUCKET, probe))
|
||||
s3_host = HOST.split(":")[0]
|
||||
for port, role in ((9333, "master UI/API"), (8080, "volume"), (8888, "filer UI/API"), (8111, "IAM API"),
|
||||
(8181, "Iceberg"), (9101, "Lance"), (8333, "S3 API")):
|
||||
try:
|
||||
socket.create_connection((s3_host, port), timeout=2).close()
|
||||
got = "open"
|
||||
except OSError:
|
||||
got = "closed"
|
||||
want = "open" if port == 8333 else "closed"
|
||||
results.append({"check": "port %d (%s) из backend-сети" % (port, role), "expected": want, "got": got,
|
||||
"pass": got == want})
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-45s expected=%-8s got=%s" % (r["check"], r["expected"], r["got"]))
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
print(json.dumps({"checks": len(results), "failed": len(failed)}))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/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 и draft-декодирование JPEG держат RAM реплики ограниченной и не
|
||||
зависящей линейно от числа одновременных загрузок; 10+ загрузок по ~10 MiB не
|
||||
приближают процесс к лимиту контейнера 256 MiB.
|
||||
|
||||
Методика: перед прогоном 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()
|
||||
|
||||
|
||||
def make_jpeg():
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
return None
|
||||
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:
|
||||
return b.getvalue()
|
||||
return None
|
||||
|
||||
|
||||
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("--output")
|
||||
args = ap.parse_args()
|
||||
files = [("image/png", noise_png(10 * 1024 * 1024))]
|
||||
jpeg = make_jpeg()
|
||||
if jpeg:
|
||||
files.append(("image/jpeg", jpeg))
|
||||
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"], 201, actor=alice, raw=data,
|
||||
headers={"Content-Type": ctype})
|
||||
cids = containers()
|
||||
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), [201, 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:
|
||||
results.append({"type": ctype, "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"] == 201)
|
||||
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(len(files[i % len(files)][1]) for i, r in enumerate(results)
|
||||
if r["status"] == 201) / 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(),
|
||||
}
|
||||
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 __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user