ЛР4: S3-хранилище (MinIO) и вложения
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Вложения lab4: позитивный сценарий и негативный набор уровня «4».
|
||||
|
||||
python student-tests/attachments.py --base-url http://localhost:8080
|
||||
|
||||
Проверяет (каждый пользовательский промах — ожидаемый 4xx, НИКОГДА не 500):
|
||||
- PNG и JPEG: 201 ready, sha256/size, скачивание побайтно вторым участником,
|
||||
истинный Content-Type, Unicode filename, 404 постороннему (метаданные и байты);
|
||||
- слишком большой файл: по Content-Length (тело не отправляется), chunked без
|
||||
Content-Length больше лимита, файл ровно в лимит проходит;
|
||||
- «бомба» по пикселям (маленький файл, > 40 млн пикселей) → 413;
|
||||
- повреждённые изображения (усечённый PNG/JPEG, битый CRC, мусор) → 415;
|
||||
- подмена MIME (PNG как image/jpeg, JPEG как image/png, текст/GIF/HTML как png) → 415;
|
||||
- опасные filename (/, \\, NUL, управляющие, bidi, .., пусто, > 255) → 400;
|
||||
- чужое attachment_id / вложение другого чата / несуществующее → 404;
|
||||
дубликаты, > 10 id, не-UUID → 400; пустой текст без вложений → 400;
|
||||
- идемпотентность с attachment_ids: отсутствие поля == [], другой набор → 409.
|
||||
"""
|
||||
import argparse
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from common import (SAMPLE_JPG, SAMPLE_PNG, Api, Report, make_png, raw_http, sha256,
|
||||
upload)
|
||||
|
||||
LIMIT = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
statuses: list[int] = []
|
||||
|
||||
def expect(st, want, name):
|
||||
statuses.append(st)
|
||||
want = want if isinstance(want, tuple) else (want,)
|
||||
r.check(st in want, f"{name} -> {'/'.join(map(str, want))} (got {st})")
|
||||
|
||||
alice, bob, eve = api.new_user("att_a"), api.new_user("att_b"), api.new_user("att_e")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "files", "member_ids": [alice["id"], bob["id"]]},
|
||||
token=alice["token"])
|
||||
st, other, _ = api.call("POST", "/api/v1/chats", {"title": "alice second", "member_ids": [alice["id"]]},
|
||||
token=alice["token"])
|
||||
st, evechat, _ = api.call("POST", "/api/v1/chats", {"title": "eve", "member_ids": [eve["id"]]},
|
||||
token=eve["token"])
|
||||
A, B, E = alice["token"], bob["token"], eve["token"]
|
||||
mpath = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
print("== позитивный сценарий ==")
|
||||
st, png, _ = upload(api, A, chat["id"], SAMPLE_PNG, "sample.png")
|
||||
expect(st, 201, "upload PNG")
|
||||
r.check(png and png["status"] == "ready" and png["variants"] == [] and png["error_code"] is None,
|
||||
"201 ready, variants=[], error_code=null")
|
||||
r.check(png and png["sha256"] == sha256(SAMPLE_PNG) and png["size_bytes"] == len(SAMPLE_PNG),
|
||||
"sha256/size describe the original")
|
||||
r.check(png and "object_key" not in png and "bucket" not in str(png), "no S3 key/bucket in public JSON")
|
||||
st, jpg, _ = upload(api, B, chat["id"], SAMPLE_JPG, "фото 📷 отпуск.jpg", "image/jpeg")
|
||||
expect(st, 201, "upload JPEG with Unicode filename")
|
||||
r.check(jpg and jpg["filename"] == "фото 📷 отпуск.jpg" and jpg["content_type"] == "image/jpeg",
|
||||
"filename returned as is (display only)")
|
||||
st, raw, rh = api.raw("GET", f"/api/v1/attachments/{png['id']}/content", headers={"Authorization": "Bearer " + B})
|
||||
expect(st, 200, "member downloads PNG")
|
||||
r.check(raw == SAMPLE_PNG and sha256(raw) == png["sha256"], "downloaded bytes are identical (sha256)")
|
||||
r.check(rh.get("Content-Type", "").startswith("image/png"), "true Content-Type image/png")
|
||||
r.check(rh.get("X-Content-Type-Options") == "nosniff", "nosniff header")
|
||||
st, raw, rh = api.raw("GET", f"/api/v1/attachments/{jpg['id']}/content?variant=original",
|
||||
headers={"Authorization": "Bearer " + A})
|
||||
expect(st, 200, "member downloads JPEG (variant=original)")
|
||||
r.check(raw == SAMPLE_JPG and rh.get("Content-Type", "").startswith("image/jpeg"), "JPEG bytes and type")
|
||||
st, msg, _ = api.call("POST", mpath, {"text": "", "attachment_ids": [png["id"], jpg["id"]]}, token=A)
|
||||
expect(st, 201, "message with empty text + 2 attachments")
|
||||
r.check(msg and msg["attachment_ids"] == [png["id"], jpg["id"]] and msg["text"] == "",
|
||||
"attachment_ids kept in request order")
|
||||
st, page, _ = api.call("GET", mpath, token=B)
|
||||
got = [m for m in (page or {}).get("items", []) if m["id"] == (msg or {}).get("id")]
|
||||
r.check(len(got) == 1 and got[0]["attachment_ids"] == [png["id"], jpg["id"]], "history shows attachment_ids")
|
||||
st, plain, _ = api.call("POST", mpath, {"text": "просто текст"}, token=B)
|
||||
r.check(st == 201 and plain["attachment_ids"] == [], "text-only POST (lab3) still valid, attachment_ids=[]")
|
||||
st, meta, _ = api.call("GET", f"/api/v1/attachments/{png['id']}", token=B)
|
||||
expect(st, 200, "member reads metadata")
|
||||
st, raw, _ = api.raw("GET", f"/api/v1/attachments/{png['id']}/content?variant=thumbnail",
|
||||
headers={"Authorization": "Bearer " + B})
|
||||
expect(st, 404, "thumbnail variant does not exist in lab4")
|
||||
st, _, _ = api.raw("GET", f"/api/v1/attachments/{png['id']}/content?variant=bogus",
|
||||
headers={"Authorization": "Bearer " + B})
|
||||
expect(st, 400, "unknown variant name")
|
||||
|
||||
print("== доступ ==")
|
||||
for suffix in ("", "/content"):
|
||||
st, _, _ = api.raw("GET", f"/api/v1/attachments/{png['id']}{suffix}", headers={"Authorization": "Bearer " + E})
|
||||
expect(st, 404, f"outsider GET attachment{suffix or ' metadata'}")
|
||||
st, _, _ = api.raw("GET", f"/api/v1/attachments/{uuid.uuid4()}{suffix}", headers={"Authorization": "Bearer " + A})
|
||||
expect(st, 404, f"unknown attachment{suffix or ' metadata'}")
|
||||
st, _, _ = api.raw("GET", f"/api/v1/attachments/{png['id']}/content")
|
||||
expect(st, 401, "anonymous download")
|
||||
st, _, _ = api.raw("GET", "/api/v1/attachments/not-a-uuid", headers={"Authorization": "Bearer " + A})
|
||||
expect(st, 400, "attachment id is not a UUID")
|
||||
st, _, _ = upload(api, E, chat["id"], SAMPLE_PNG)
|
||||
expect(st, 404, "outsider uploads into foreign chat")
|
||||
st, _, _ = api.raw("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=a.png", SAMPLE_PNG,
|
||||
{"Content-Type": "image/png"})
|
||||
expect(st, 401, "anonymous upload")
|
||||
|
||||
print("== привязка к сообщению ==")
|
||||
st, eve_att, _ = upload(api, E, evechat["id"], SAMPLE_PNG)
|
||||
expect(st, 201, "eve uploads into her own chat")
|
||||
st, other_att, _ = upload(api, A, other["id"], SAMPLE_PNG)
|
||||
expect(st, 201, "alice uploads into her second chat")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [eve_att["id"]]}, token=A)
|
||||
expect(st, 404, "foreign attachment_id (eve's chat) in message")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [other_att["id"]]}, token=A)
|
||||
expect(st, 404, "attachment of ANOTHER chat of the same user")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [str(uuid.uuid4())]}, token=A)
|
||||
expect(st, 404, "unknown attachment_id")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [png["id"], eve_att["id"]]}, token=A)
|
||||
expect(st, 404, "one valid + one foreign -> whole message rejected")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [png["id"], png["id"]]}, token=A)
|
||||
expect(st, 400, "duplicate attachment_ids")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [png["id"].upper(), png["id"]]}, token=A)
|
||||
expect(st, 400, "same UUID in different case is a duplicate")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, token=A)
|
||||
expect(st, 400, "more than 10 attachment_ids")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": ["nope"]}, token=A)
|
||||
expect(st, 400, "attachment_id is not a UUID")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "attachment_ids": None}, token=A)
|
||||
expect(st, 400, "attachment_ids: null")
|
||||
st, _, _ = api.call("POST", mpath, {"text": " ", "attachment_ids": []}, token=A)
|
||||
expect(st, 400, "blank text without attachments")
|
||||
st, _, _ = api.call("POST", mpath, {"attachment_ids": [png["id"]]}, token=A)
|
||||
expect(st, 400, "text field is required")
|
||||
st, m2, _ = api.call("POST", mpath, {"text": "ещё раз", "attachment_ids": [png["id"]]}, token=B)
|
||||
expect(st, 201, "any member may reference a chat attachment again")
|
||||
st, _, _ = api.call("POST", f"/api/v1/chats/{evechat['id']}/messages",
|
||||
{"text": "x", "attachment_ids": [png["id"]]}, token=E)
|
||||
expect(st, 404, "eve attaches alice's file to her own chat")
|
||||
|
||||
print("== идемпотентность с вложениями ==")
|
||||
key = uuid.uuid4().hex
|
||||
st, first, _ = api.call("POST", mpath, {"text": "idem"}, token=A, headers={"Idempotency-Key": key})
|
||||
st2, again, _ = api.call("POST", mpath, {"attachment_ids": [], "text": "idem"}, token=A,
|
||||
headers={"Idempotency-Key": key})
|
||||
r.check(st == st2 == 201 and first == again, "missing attachment_ids == [] (same Message)")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "idem", "attachment_ids": [png["id"]]}, token=A,
|
||||
headers={"Idempotency-Key": key})
|
||||
expect(st, 409, "same key, different attachment_ids")
|
||||
key2 = uuid.uuid4().hex
|
||||
st, a1, _ = api.call("POST", mpath, {"text": "", "attachment_ids": [jpg["id"], png["id"]]}, token=A,
|
||||
headers={"Idempotency-Key": key2})
|
||||
st2, a2, _ = api.call("POST", mpath, {"attachment_ids": [jpg["id"], png["id"]], "text": ""}, token=A,
|
||||
headers={"Idempotency-Key": key2})
|
||||
r.check(st == st2 == 201 and a1 == a2, "replay with attachments returns the same Message")
|
||||
|
||||
print("== размер ==")
|
||||
base = f"/api/v1/chats/{chat['id']}/attachments?filename=big.png"
|
||||
auth = {"Authorization": "Bearer " + A, "Content-Type": "image/png"}
|
||||
st, _ = raw_http(args.base_url, "POST", base, {**auth, "Content-Length": str(LIMIT + 1)})
|
||||
expect(st, 413, "Content-Length = 10 MiB + 1, body never sent (limit before reading)")
|
||||
st, _ = raw_http(args.base_url, "POST", base, {**auth, "Content-Length": str(50 * LIMIT)})
|
||||
expect(st, 413, "Content-Length = 500 MiB")
|
||||
st, _ = raw_http(args.base_url, "POST", base, auth, chunks=(b"\0" * 65536 for _ in range(200)), chunked=True)
|
||||
expect(st, 413, "chunked body > 10 MiB without Content-Length (stream cut at limit)")
|
||||
big = make_png(1900, 1900, noise=True) # ≈10,8 МБ настоящего PNG
|
||||
# Шлём кусками и следим за ранним ответом: сервер отвечает 413 по Content-Length,
|
||||
# не дочитывая тело, и urllib получил бы обрыв соединения вместо ответа.
|
||||
st, _ = raw_http(args.base_url, "POST", base, {**auth, "Content-Length": str(len(big))},
|
||||
chunks=(big[i:i + 65536] for i in range(0, len(big), 65536)))
|
||||
expect(st, 413, f"real PNG of {len(big)} bytes")
|
||||
fit = make_png(1860, 1870, noise=True)
|
||||
if len(fit) <= LIMIT:
|
||||
st, body, _ = upload(api, A, chat["id"], fit, "fits.png", timeout=120)
|
||||
expect(st, 201, f"real PNG of {len(fit)} bytes (≤ 10 MiB) accepted")
|
||||
if st == 201:
|
||||
r.check(body["size_bytes"] == len(fit) and body["sha256"] == sha256(fit), "big file sha256/size")
|
||||
st, _, _ = upload(api, A, chat["id"], b"")
|
||||
expect(st, 400, "empty body")
|
||||
|
||||
print("== пиксели ==")
|
||||
bomb = make_png(8000, 8000, color_type=0, rows=(b"\0" * 8001) * 8000) # 64 млн пикс., ~60 КБ
|
||||
st, _, _ = upload(api, A, chat["id"], bomb, "bomb.png")
|
||||
expect(st, 413, f"decompression bomb 8000x8000 in {len(bomb)} bytes")
|
||||
wide = make_png(40001, 1001, color_type=0, rows=(b"\0" * 40002) * 1001) # 40 040 001 пикс.
|
||||
st, _, _ = upload(api, A, chat["id"], wide, "wide.png")
|
||||
expect(st, 413, "40 040 001 pixels (just over the limit)")
|
||||
|
||||
print("== повреждённые файлы ==")
|
||||
corrupt = bytearray(SAMPLE_PNG)
|
||||
corrupt[len(corrupt) // 2] ^= 0xFF
|
||||
cases = [
|
||||
("truncated PNG", SAMPLE_PNG[: len(SAMPLE_PNG) // 2], "image/png"),
|
||||
("PNG with flipped byte (CRC)", bytes(corrupt), "image/png"),
|
||||
("PNG signature only", SAMPLE_PNG[:8], "image/png"),
|
||||
("PNG header + garbage", SAMPLE_PNG[:33] + b"\xde\xad\xbe\xef" * 100, "image/png"),
|
||||
("truncated JPEG", SAMPLE_JPG[: len(SAMPLE_JPG) // 2], "image/jpeg"),
|
||||
("JPEG SOI + garbage", b"\xff\xd8\xff\xe0" + b"\x00" * 300, "image/jpeg"),
|
||||
]
|
||||
for name, data, ctype in cases:
|
||||
st, body, _ = upload(api, A, chat["id"], data, "x", ctype)
|
||||
expect(st, 415, name)
|
||||
r.check(not body or body["error"]["code"] == "unsupported_media_type", f"{name}: error code")
|
||||
|
||||
print("== fuzz: случайные порчи байтов (только 201 или 415, никогда 500) ==")
|
||||
import random
|
||||
rnd = random.Random(2026)
|
||||
fuzz_codes = []
|
||||
for data, ctype in ((SAMPLE_PNG, "image/png"), (SAMPLE_JPG, "image/jpeg")):
|
||||
for _ in range(15):
|
||||
d = bytearray(data)
|
||||
for _ in range(rnd.randint(1, 4)):
|
||||
d[rnd.randrange(8, len(d))] ^= 1 << rnd.randrange(8)
|
||||
if rnd.random() < 0.3:
|
||||
d = d[: rnd.randrange(16, len(d))]
|
||||
st, _, _ = upload(api, A, chat["id"], bytes(d), "fuzz", ctype)
|
||||
statuses.append(st)
|
||||
fuzz_codes.append(st)
|
||||
r.check(set(fuzz_codes) <= {201, 415},
|
||||
f"30 corrupted files -> only 201/415 (got {sorted(set(fuzz_codes), key=str)})")
|
||||
|
||||
print("== подмена MIME ==")
|
||||
spoof = [
|
||||
("PNG bytes sent as image/jpeg", SAMPLE_PNG, "image/jpeg"),
|
||||
("JPEG bytes sent as image/png", SAMPLE_JPG, "image/png"),
|
||||
("text renamed to .png", b"just text, not an image\n" * 20, "image/png"),
|
||||
("GIF sent as image/png", b"GIF89a\x01\x00\x01\x00\x80\x00\x00" + b"\x00" * 40, "image/png"),
|
||||
("HTML sent as image/jpeg", b"<html><script>alert(1)</script></html>", "image/jpeg"),
|
||||
("PNG with Content-Type image/gif", SAMPLE_PNG, "image/gif"),
|
||||
("PNG with Content-Type application/octet-stream", SAMPLE_PNG, "application/octet-stream"),
|
||||
("PNG with Content-Type text/html", SAMPLE_PNG, "text/html"),
|
||||
]
|
||||
for name, data, ctype in spoof:
|
||||
st, _, _ = upload(api, A, chat["id"], data, "evil.png", ctype)
|
||||
expect(st, 415, name)
|
||||
|
||||
print("== опасные filename ==")
|
||||
bad_names = ["../../etc/passwd", "dir/a.png", "C:\\Windows\\a.png", "a\x00.png", "a\nb.png",
|
||||
"tab\t.png", "\x1b[31mred.png", "photo\u202egnp.exe", "..", ".", " ", "x" * 256]
|
||||
for name in bad_names:
|
||||
st, _, _ = upload(api, A, chat["id"], SAMPLE_PNG, name)
|
||||
expect(st, 400, f"filename {name[:20]!r}")
|
||||
st, _, _ = api.raw("POST", f"/api/v1/chats/{chat['id']}/attachments", SAMPLE_PNG,
|
||||
{"Authorization": "Bearer " + A, "Content-Type": "image/png"})
|
||||
expect(st, 400, "filename missing")
|
||||
st, ok, _ = upload(api, A, chat["id"], SAMPLE_PNG, "x" * 255)
|
||||
expect(st, 201, "filename of exactly 255 chars")
|
||||
st, ok, _ = upload(api, A, chat["id"], SAMPLE_PNG, "отчёт (финал) v2 — 100%.png")
|
||||
expect(st, 201, "filename with spaces, Unicode and punctuation")
|
||||
st, _, _ = api.raw("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={quote('a.png')}", SAMPLE_PNG,
|
||||
{"Authorization": "Bearer " + A, "Content-Type": "image/png; charset=binary"})
|
||||
expect(st, 201, "media type parameters are ignored")
|
||||
|
||||
r.check(500 not in statuses and all(s is not None for s in statuses),
|
||||
f"no 500 and no dropped connection among {len(statuses)} checked responses")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Прогон ВСЕХ проверок lab4 с сохранением вывода в evidence/ (Windows/macOS/Linux).
|
||||
Стенд должен быть запущен: docker compose --env-file .env up -d --build
|
||||
|
||||
python student-tests/collect_evidence.py --base-url http://localhost:8080
|
||||
python student-tests/collect_evidence.py --only smoke,attachments # выборочно
|
||||
|
||||
Каждый шаг пишет evidence/<имя>.txt (команда, время, stdout/stderr, код выхода).
|
||||
Ошибка одного шага не останавливает остальные; в конце — сводка PASS/FAIL.
|
||||
Hook-и: на Windows scripts/*.cmd, иначе scripts/*.sh. Секреты не печатаются.
|
||||
"""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
PY = sys.executable
|
||||
WIN = os.name == "nt"
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
SAMPLE_SHA = hashlib.sha256((ROOT / "tests/fixtures/sample.png").read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def hook(name: str) -> str:
|
||||
return str(ROOT / "scripts" / (name + (".cmd" if WIN else ".sh")))
|
||||
|
||||
|
||||
# Публичные tests/ читают JSON без явной кодировки: на Windows (cp1251) это падает.
|
||||
# UTF-8 mode Python для всех дочерних процессов, сами тесты не меняем.
|
||||
ENV = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
|
||||
|
||||
|
||||
def run(cmd: list[str], log, timeout: int = 900) -> int:
|
||||
log.write(f"\n$ {' '.join(cmd)}\n")
|
||||
log.flush()
|
||||
try:
|
||||
p = subprocess.run(cmd, cwd=ROOT, env=ENV, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
log.write("TIMEOUT\n")
|
||||
return 124
|
||||
log.write(p.stdout)
|
||||
log.write(f"[exit {p.returncode}]\n")
|
||||
return p.returncode
|
||||
|
||||
|
||||
def ports_closed(log) -> int:
|
||||
"""MinIO (9000 API, 9001 консоль) не опубликован на хосте."""
|
||||
bad = 0
|
||||
for port in (9000, 9001):
|
||||
s = socket.socket()
|
||||
s.settimeout(1)
|
||||
try:
|
||||
s.connect(("127.0.0.1", port))
|
||||
log.write(f"127.0.0.1:{port} OPEN <- не должно быть\n")
|
||||
bad += 1
|
||||
except OSError as exc:
|
||||
log.write(f"127.0.0.1:{port} closed ({type(exc).__name__}) ok\n")
|
||||
finally:
|
||||
s.close()
|
||||
return bad
|
||||
|
||||
|
||||
def steps(base: str):
|
||||
t = ["--base-url", base]
|
||||
yield "check", [[PY, "scripts/check_contract.py"]]
|
||||
yield "stand", [COMPOSE + ["ps"], COMPOSE + ["config", "--images"],
|
||||
COMPOSE + ["exec", "-T", "api", "python", "-m", "app.migrate"]]
|
||||
yield "smoke", [[PY, "tests/smoke.py", *t]]
|
||||
yield "student-tests", [[PY, "student-tests/run.py", *t], [PY, "student-tests/idempotency.py", *t]]
|
||||
yield "attachments", [[PY, "student-tests/attachments.py", *t]]
|
||||
yield "s3-bootstrap", [COMPOSE + ["run", "--rm", "s3-init"], COMPOSE + ["run", "--rm", "s3-init"]]
|
||||
yield "s3-private", [COMPOSE + ["exec", "-T", "api", "python", "-m", "app.tools", "private-check"],
|
||||
"PORTS"]
|
||||
yield "no-local-file", [COMPOSE + ["exec", "-T", "--index", str(i), "api", "python", "-m", "app.tools",
|
||||
"find-local", SAMPLE_SHA] for i in (1, 2)] + [
|
||||
["docker", "inspect", "-f", "{{.Name}} mounts={{json .Mounts}}"] + "API_IDS".split()]
|
||||
yield "orphans", [COMPOSE + ["--profile", "fault", "up", "-d", "api-fault"], "SLEEP",
|
||||
[PY, "student-tests/orphans.py", *t, "--fault-url", "http://localhost:8082"],
|
||||
COMPOSE + ["--profile", "fault", "stop", "api-fault"]]
|
||||
yield "s3-outage", [[PY, "student-tests/s3_outage.py", *t]]
|
||||
yield "upload-memory", [[PY, "student-tests/upload_memory.py", *t, "--concurrency", "10",
|
||||
"--output", "evidence/upload-memory-10.json"],
|
||||
[PY, "student-tests/upload_memory.py", *t, "--concurrency", "20",
|
||||
"--output", "evidence/upload-memory-20.json"]]
|
||||
yield "persistence", [COMPOSE + ["ps"], [PY, "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", hook("restart"), *t], COMPOSE + ["ps"]]
|
||||
yield "failover", [[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), *t],
|
||||
[hook("restore-api")], "SLEEP",
|
||||
[PY, "tests/resilience.py", "--mode", "failover", "--action-script", hook("stop-one"), *t],
|
||||
[hook("restore-api")]]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--only", default="")
|
||||
args = ap.parse_args()
|
||||
only = {x.strip() for x in args.only.split(",") if x.strip()}
|
||||
EVIDENCE.mkdir(exist_ok=True)
|
||||
commit = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=ROOT, capture_output=True,
|
||||
text=True).stdout.strip() or "no-git"
|
||||
summary = []
|
||||
for name, cmds in steps(args.base_url):
|
||||
if only and name not in only:
|
||||
continue
|
||||
path = EVIDENCE / f"{name}.txt"
|
||||
print(f"== {name} -> {path.relative_to(ROOT)}")
|
||||
with open(path, "w", encoding="utf-8") as log:
|
||||
log.write(f"# {name}\n# date: {dt.datetime.now().isoformat(timespec='seconds')} commit: {commit}\n")
|
||||
failed = 0
|
||||
for cmd in cmds:
|
||||
if cmd == "SLEEP":
|
||||
time.sleep(8)
|
||||
continue
|
||||
if cmd == "PORTS":
|
||||
failed += ports_closed(log)
|
||||
continue
|
||||
if "API_IDS" in cmd:
|
||||
ids = subprocess.run(COMPOSE + ["ps", "-q", "api"], cwd=ROOT, capture_output=True,
|
||||
text=True).stdout.split()
|
||||
cmd = [c for c in cmd if c != "API_IDS"] + ids
|
||||
code = run(cmd, log)
|
||||
failed += 1 if code else 0
|
||||
status = "PASS" if not failed else f"FAIL ({failed})"
|
||||
summary.append((name, status))
|
||||
print(" ", status)
|
||||
print("\nSummary:")
|
||||
for name, status in summary:
|
||||
print(f" {name:15} {status}")
|
||||
sys.exit(0 if all(s == "PASS" for _, s in summary) else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,202 @@
|
||||
from __future__ import annotations
|
||||
"""Общий HTTP-клиент для собственных тестов (только стандартная библиотека)."""
|
||||
import base64
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
PASSWORD = "Test-password-" + uuid.uuid4().hex[:8]
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self, base: str):
|
||||
self.base = base.rstrip("/")
|
||||
|
||||
def raw(self, method, path, data=None, headers=None, timeout=10):
|
||||
req = urllib.request.Request(self.base + path, data=data, headers=headers or {}, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read(), r.headers
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read(), e.headers
|
||||
|
||||
def call(self, method, path, body=None, token=None, headers=None, timeout=10):
|
||||
h = dict(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
# С lab3 POST сообщения требует Idempotency-Key; если тест не задал свой — новый ключ.
|
||||
if method == "POST" and path.split("?")[0].endswith("/messages"):
|
||||
h.setdefault("Idempotency-Key", uuid.uuid4().hex)
|
||||
st, raw, rh = self.raw(method, path, data, h, timeout=timeout)
|
||||
try:
|
||||
return st, json.loads(raw or b"null"), rh
|
||||
except ValueError:
|
||||
return st, None, rh
|
||||
|
||||
def register(self, prefix: str, password: str = PASSWORD) -> dict:
|
||||
name = (prefix + "_" + uuid.uuid4().hex[:10])[:32]
|
||||
st, user, _ = self.call("POST", "/api/v1/users",
|
||||
{"username": name, "display_name": prefix, "password": password})
|
||||
assert st == 201, f"register {name}: {st} {user}"
|
||||
user["password"] = password
|
||||
return user
|
||||
|
||||
def login(self, username: str, password: str):
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
st, body, rh = self.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
return st, body, rh
|
||||
|
||||
def new_user(self, prefix: str) -> dict:
|
||||
user = self.register(prefix)
|
||||
st, sess, _ = self.login(user["username"], user["password"])
|
||||
assert st == 201, f"login: {st}"
|
||||
user["token"] = sess["token"]
|
||||
return user
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self):
|
||||
self.passed = self.failed = 0
|
||||
|
||||
def check(self, cond, name):
|
||||
if cond:
|
||||
self.passed += 1
|
||||
print(f" ok - {name}")
|
||||
else:
|
||||
self.failed += 1
|
||||
print(f" FAIL - {name}")
|
||||
|
||||
def finish(self):
|
||||
print(f"\n{self.passed} passed, {self.failed} failed")
|
||||
raise SystemExit(1 if self.failed else 0)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- lab4: файлы
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import select
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
FIXTURES = Path(__file__).resolve().parent / "fixtures"
|
||||
SAMPLE_PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
SAMPLE_JPG = (FIXTURES / "sample.jpg").read_bytes()
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def sha256(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def make_png(width: int, height: int, *, noise: bool = False, color_type: int = 2,
|
||||
rows: bytes | None = None) -> bytes:
|
||||
"""Синтетический PNG только средствами stdlib.
|
||||
noise=True — случайные пиксели (почти не сжимаются: так получаем файл нужного размера).
|
||||
rows — готовые распакованные данные (для «бомб» и битых файлов)."""
|
||||
channels = {0: 1, 2: 3, 6: 4}[color_type]
|
||||
if rows is None:
|
||||
line = width * channels
|
||||
rows = b"".join(b"\x00" + (os.urandom(line) if noise else bytes(line)) for _ in range(height))
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
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", zlib.compress(rows, 1 if noise else 9)) + chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def upload(api, token: str, chat_id: str, data: bytes, filename: str = "image.png",
|
||||
content_type: str = "image/png", headers: dict | None = None, timeout: int = 60):
|
||||
from urllib.parse import quote
|
||||
h = {"Authorization": "Bearer " + token, "Content-Type": content_type, **(headers or {})}
|
||||
path = f"/api/v1/chats/{chat_id}/attachments?filename={quote(filename, safe='')}"
|
||||
st, raw, rh = api.raw("POST", path, data, h, timeout=timeout)
|
||||
try:
|
||||
body = json.loads(raw or b"null")
|
||||
except ValueError:
|
||||
body = None
|
||||
return st, body, rh
|
||||
|
||||
|
||||
def raw_http(base: str, method: str, path: str, headers: dict, chunks=(), chunked: bool = False,
|
||||
close_after_send: bool = False, timeout: float = 30):
|
||||
"""HTTP/1.1 «руками» через сокет — для сценариев, которые urllib не умеет:
|
||||
заявить Content-Length и не прислать тело, прислать chunked больше лимита,
|
||||
оборвать загрузку на середине. Пока шлём тело, следим, не ответил ли сервер
|
||||
раньше (413 до конца тела) — тогда прекращаем отправку и читаем ответ.
|
||||
Возвращает (status | None, body_bytes)."""
|
||||
u = urlparse(base)
|
||||
sock = socket.create_connection((u.hostname, u.port or 80), timeout=timeout)
|
||||
try:
|
||||
lines = [f"{method} {path} HTTP/1.1", f"Host: {u.hostname}:{u.port or 80}", "Connection: close"]
|
||||
lines += [f"{k}: {v}" for k, v in headers.items()]
|
||||
if chunked:
|
||||
lines.append("Transfer-Encoding: chunked")
|
||||
sock.sendall(("\r\n".join(lines) + "\r\n\r\n").encode("latin-1"))
|
||||
for part in chunks:
|
||||
ready, _, _ = select.select([sock], [], [], 0)
|
||||
if ready:
|
||||
break # сервер уже ответил — дальше не шлём
|
||||
try:
|
||||
sock.sendall(f"{len(part):x}\r\n".encode() + part + b"\r\n" if chunked else part)
|
||||
except (BrokenPipeError, ConnectionResetError):
|
||||
break
|
||||
else:
|
||||
if chunked and not close_after_send:
|
||||
try:
|
||||
sock.sendall(b"0\r\n\r\n")
|
||||
except OSError:
|
||||
pass
|
||||
if close_after_send:
|
||||
return None, b"" # обрыв загрузки: ответ не ждём
|
||||
data = b""
|
||||
try:
|
||||
while True:
|
||||
piece = sock.recv(65536)
|
||||
if not piece:
|
||||
break
|
||||
data += piece
|
||||
except (ConnectionResetError, socket.timeout):
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
m = re.match(rb"HTTP/1\.[01] (\d{3})", data)
|
||||
return (int(m.group(1)) if m else None), data.split(b"\r\n\r\n", 1)[-1]
|
||||
|
||||
|
||||
def compose(*args: str, check: bool = True) -> str:
|
||||
out = subprocess.run(COMPOSE + list(args), cwd=ROOT, capture_output=True, text=True)
|
||||
if check and out.returncode != 0:
|
||||
raise RuntimeError(f"docker compose {' '.join(args)} failed: {out.stderr.strip()[-300:]}")
|
||||
return out.stdout
|
||||
|
||||
|
||||
def tool(*args: str) -> dict:
|
||||
"""python -m app.tools … внутри контейнера api → последняя строка JSON."""
|
||||
out = compose("exec", "-T", "api", "python", "-m", "app.tools", *args)
|
||||
return json.loads(out.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def janitor(*args: str, attempts: int = 10) -> dict:
|
||||
"""Один проход очистки внутри api. Если advisory lock занят фоновым
|
||||
проходом другой реплики — повторяем."""
|
||||
import time
|
||||
for _ in range(attempts):
|
||||
out = compose("exec", "-T", "api", "python", "-m", "app.janitor", "--once", *args)
|
||||
stats = json.loads(out.strip().splitlines()[-1])
|
||||
if stats.get("locked"):
|
||||
return stats
|
||||
time.sleep(1)
|
||||
raise RuntimeError("janitor lock is busy")
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Истечение сессии при коротком SESSION_TTL_SECONDS (=2).
|
||||
Запускается против отдельного экземпляра API с коротким TTL:
|
||||
docker compose --env-file .env --profile ttl up -d api-ttl
|
||||
python student-tests/expiry.py --base-url http://localhost:8081
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8081")
|
||||
ap.add_argument("--ttl", type=float, default=2)
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
# Экземпляр с коротким TTL мог только что стартовать: ждём готовности до 60 с.
|
||||
deadline = time.time() + 60
|
||||
while True:
|
||||
try:
|
||||
if api.raw("GET", "/health/ready", timeout=2)[0] == 200:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
if time.time() > deadline:
|
||||
raise SystemExit("API is not ready at " + args.base_url)
|
||||
time.sleep(1)
|
||||
|
||||
user = api.register("ttl")
|
||||
st, sess, _ = api.login(user["username"], user["password"])
|
||||
r.check(st == 201, "login -> 201")
|
||||
exp = datetime.fromisoformat(sess["expires_at"].replace("Z", "+00:00"))
|
||||
left = (exp - datetime.now(timezone.utc)).total_seconds()
|
||||
r.check(0 < left <= args.ttl + 1, f"expires_at is about {args.ttl}s ahead (got {left:.2f}s)")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=sess["token"])
|
||||
r.check(st == 200, "token works before expiry") # заодно кладёт сессию в кэш Redis
|
||||
time.sleep(args.ttl + 1.5)
|
||||
st, _, rh = api.call("GET", "/api/v1/users/me", token=sess["token"])
|
||||
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"),
|
||||
"expired token -> 401 (cache does not extend the session)")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,60 @@
|
||||
-- План запроса истории на ≥10 000 сообщениях (уровень «4»).
|
||||
-- Всё внутри транзакции с ROLLBACK: учебные данные не остаются в базе.
|
||||
-- Запуск (одинаково в PowerShell и sh):
|
||||
-- docker compose cp student-tests/explain.sql postgres:/tmp/explain.sql
|
||||
-- docker compose exec postgres psql -U messenger -d messenger -f /tmp/explain.sql
|
||||
BEGIN;
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ('00000000-0000-4000-8000-000000000001', 'explain_seed', 'Seed', 'x', now());
|
||||
|
||||
-- Чат, историю которого читаем, и 9 «соседних» чатов, чтобы в таблице были чужие сообщения.
|
||||
INSERT INTO chats (id, title, created_by, created_at)
|
||||
SELECT ('00000000-0000-4000-8000-0000000001' || lpad(g::text, 2, '0'))::uuid, 'seed ' || g,
|
||||
'00000000-0000-4000-8000-000000000001', now()
|
||||
FROM generate_series(0, 9) g;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
SELECT ('00000000-0000-4000-8000-0000000001' || lpad(g::text, 2, '0'))::uuid,
|
||||
'00000000-0000-4000-8000-000000000001', 0
|
||||
FROM generate_series(0, 9) g;
|
||||
|
||||
-- 12 000 сообщений в целевом чате + 48 000 в соседних = 60 000 строк.
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT gen_random_uuid(),
|
||||
('00000000-0000-4000-8000-0000000001' || lpad((CASE WHEN g <= 12000 THEN 0 ELSE g % 9 + 1 END)::text, 2, '0'))::uuid,
|
||||
'00000000-0000-4000-8000-000000000001',
|
||||
'msg ' || g,
|
||||
now() - interval '1 day' + g * interval '1 millisecond'
|
||||
FROM generate_series(1, 60000) g;
|
||||
|
||||
ANALYZE messages;
|
||||
|
||||
SELECT count(*) AS messages_in_target_chat
|
||||
FROM messages WHERE chat_id = '00000000-0000-4000-8000-000000000100';
|
||||
|
||||
\echo '=== 1. Первая страница (limit 50 + 1) ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000100'
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo '=== 2. Страница из середины истории (keyset-курсор после ~6000-го сообщения) ==='
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000100'
|
||||
AND (created_at, id) > (now() - interval '1 day' + 6000 * interval '1 millisecond',
|
||||
'00000000-0000-0000-0000-000000000000')
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
\echo '=== 3. Для сравнения: та же страница, если запретить индекс ==='
|
||||
SET LOCAL enable_indexscan = off;
|
||||
SET LOCAL enable_bitmapscan = off;
|
||||
EXPLAIN (ANALYZE, BUFFERS)
|
||||
SELECT id, chat_id, sender_id, text, created_at FROM messages
|
||||
WHERE chat_id = '00000000-0000-4000-8000-000000000100'
|
||||
AND (created_at, id) > (now() - interval '1 day' + 6000 * interval '1 millisecond',
|
||||
'00000000-0000-0000-0000-000000000000')
|
||||
ORDER BY created_at, id LIMIT 51;
|
||||
|
||||
ROLLBACK;
|
||||
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Поочерёдная остановка КАЖДОЙ реплики API под нагрузкой (lab3, уровень «4»).
|
||||
|
||||
Для каждой реплики: дождаться, что LB обслуживает все реплики → запустить
|
||||
нагрузку записи → через --before секунд остановить реплику (docker stop, SIGTERM)
|
||||
→ ещё --after секунд нагрузки → собрать RPS, ошибки, время восстановления →
|
||||
проверить сохранность и отсутствие дублей → вернуть реплику и дождаться,
|
||||
что LB снова её обслуживает.
|
||||
|
||||
python student-tests/failover_each.py --base-url http://localhost:8080 --output evidence/failover-each.json
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from common import Api, Report
|
||||
from loadgen import LoadGen
|
||||
|
||||
COMPOSE = "docker compose --env-file .env"
|
||||
|
||||
|
||||
def run(cmd: str, **fmt) -> str:
|
||||
out = subprocess.run(shlex.split(cmd.format(**fmt)), check=True, capture_output=True, text=True)
|
||||
return out.stdout
|
||||
|
||||
|
||||
def served_instances(api: Api, n: int = 30) -> set:
|
||||
seen = set()
|
||||
for _ in range(n):
|
||||
try:
|
||||
st, _, rh = api.call("GET", "/health/live", timeout=2)
|
||||
if st == 200:
|
||||
seen.add(rh.get("X-Instance-Id", ""))
|
||||
except OSError:
|
||||
pass
|
||||
return seen
|
||||
|
||||
|
||||
def wait_served(api: Api, iid: str, seconds: float = 60) -> float:
|
||||
start = time.monotonic()
|
||||
while time.monotonic() - start < seconds:
|
||||
if iid in served_instances(api, 10):
|
||||
return round(time.monotonic() - start, 2)
|
||||
time.sleep(0.5)
|
||||
return -1
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--before", type=float, default=4, help="секунд нагрузки до остановки")
|
||||
ap.add_argument("--after", type=float, default=12, help="секунд нагрузки после остановки")
|
||||
ap.add_argument("--list-cmd", default=f"{COMPOSE} ps -q api")
|
||||
ap.add_argument("--stop-cmd", default="docker stop -t 8 {id}")
|
||||
ap.add_argument("--start-cmd", default="docker start {id}")
|
||||
ap.add_argument("--output", default=None)
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
replicas = [line.strip() for line in run(args.list_cmd).splitlines() if line.strip()]
|
||||
r.check(len(replicas) >= 2, f"at least 2 API replicas running ({len(replicas)})")
|
||||
results = []
|
||||
user = api.new_user("failover")
|
||||
for cid in replicas:
|
||||
iid = cid[:12] # X-Instance-Id = hostname контейнера = короткий ID
|
||||
print(f"== реплика {iid} ==")
|
||||
r.check(wait_served(api, iid) >= 0, f"LB serves {iid} before the test")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": f"failover {iid}", "member_ids": [user["id"]]},
|
||||
token=user["token"])
|
||||
gen = LoadGen(api, user["token"], chat["id"], workers=args.workers)
|
||||
gen.start()
|
||||
time.sleep(args.before)
|
||||
t_stop = time.monotonic()
|
||||
run(args.stop_cmd, id=cid)
|
||||
stop_cmd_seconds = round(time.monotonic() - t_stop, 2)
|
||||
time.sleep(args.after)
|
||||
gen.stop()
|
||||
rel = t_stop - gen.t0
|
||||
later = gen.instances_after(t_stop + 3)
|
||||
res = {
|
||||
"stopped_instance": iid,
|
||||
"stop_command_seconds": stop_cmd_seconds,
|
||||
"before": gen.window(0, rel),
|
||||
"first_10s_after_stop": gen.window(rel, rel + 10),
|
||||
"first_success_after_stop_s": gen.first_success_after(t_stop),
|
||||
"max_gap_without_success_after_stop_s": gen.max_gap_after(t_stop),
|
||||
"stopped_instance_served_after_3s": later.count(iid),
|
||||
"instances_after_stop": sorted(set(later)),
|
||||
**gen.verify(),
|
||||
}
|
||||
t_start = time.monotonic()
|
||||
run(args.start_cmd, id=cid)
|
||||
res["rejoin_seconds"] = wait_served(api, iid)
|
||||
res["rejoin_including_start_s"] = round(time.monotonic() - t_start, 2)
|
||||
results.append(res)
|
||||
print(json.dumps(res, ensure_ascii=False, indent=2))
|
||||
r.check(res["max_gap_without_success_after_stop_s"] <= 10, f"writes resumed within 10 s after stopping {iid}")
|
||||
r.check(res["stopped_instance_served_after_3s"] == 0, f"stopped {iid} not served after detection")
|
||||
r.check(res["lost_or_changed"] == 0, "confirmed messages preserved")
|
||||
r.check(res["duplicate_texts"] == 0, "no duplicates despite retries with the same key")
|
||||
r.check(res["rejoin_seconds"] >= 0, f"{iid} rejoined the LB after restart")
|
||||
if args.output:
|
||||
with open(args.output, "w", encoding="utf-8") as f:
|
||||
json.dump({"workload": f"{args.workers} closed-loop writers, retry same key on failure, "
|
||||
f"{args.before}s before + {args.after}s after stop",
|
||||
"replicas": results}, f, ensure_ascii=False, indent=2)
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
# Собственные fixtures
|
||||
|
||||
- `sample.jpg` — синтетический JPEG 240×160 (линии и рамка), создан программно, без EXIF и персональных данных.
|
||||
|
||||
Остальные файлы для негативных тестов (oversized, битые, «бомба» по пикселям,
|
||||
подмена MIME, шум ~9,5 МБ для эксперимента памяти) генерируются тестами
|
||||
на лету (`student-tests/common.py: make_png`) — большие файлы в Git не храним.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Общая идемпотентность POST сообщения через LB (lab3).
|
||||
|
||||
python student-tests/idempotency.py --base-url http://localhost:8080
|
||||
|
||||
Проверяет: параллельные запросы с ОДНИМ ключом через разные реплики дают одно
|
||||
сообщение; другой body с тем же ключом → 409; ключ без/неверного формата → 400;
|
||||
порядок/пробелы в JSON не важны; область ключа — пользователь + чат.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--parallel", type=int, default=20)
|
||||
api, r = Api(ap.parse_args().base_url), Report()
|
||||
args = ap.parse_args()
|
||||
|
||||
alice, bob = api.new_user("idem_a"), api.new_user("idem_b")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "idem", "member_ids": [alice["id"], bob["id"]]},
|
||||
token=alice["token"])
|
||||
st, chat2, _ = api.call("POST", "/api/v1/chats", {"title": "idem2", "member_ids": [alice["id"]]},
|
||||
token=alice["token"])
|
||||
path, path2 = f"/api/v1/chats/{chat['id']}/messages", f"/api/v1/chats/{chat2['id']}/messages"
|
||||
|
||||
def history(p, token):
|
||||
st, page, _ = api.call("GET", p + "?limit=100", token=token)
|
||||
return page["items"]
|
||||
|
||||
print(f"== {args.parallel} параллельных запросов с одним ключом ==")
|
||||
key, text = uuid.uuid4().hex, "одно сообщение " + uuid.uuid4().hex[:6]
|
||||
|
||||
def send(_):
|
||||
return api.call("POST", path, {"text": text}, token=alice["token"], headers={"Idempotency-Key": key})
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.parallel) as pool:
|
||||
res = list(pool.map(send, range(args.parallel)))
|
||||
codes = [x[0] for x in res]
|
||||
ids = {x[1]["id"] for x in res if x[0] == 201}
|
||||
instances = {x[2].get("X-Instance-Id") for x in res}
|
||||
r.check(codes.count(201) == args.parallel, f"all parallel repeats -> 201 (got {sorted(set(codes))})")
|
||||
r.check(len(ids) == 1, f"all responses carry the same message id ({len(ids)} distinct)")
|
||||
r.check(len(instances) >= 2, f"requests were served by >=2 replicas ({len(instances)})")
|
||||
r.check(sum(m["text"] == text for m in history(path, alice["token"])) == 1, "exactly one message in history")
|
||||
first = res[0][1]
|
||||
r.check(all(x[1] == first for x in res), "every replay returns the identical Message")
|
||||
|
||||
print("== семантика ключа ==")
|
||||
st, _, _ = api.call("POST", path, {"text": "другой текст"}, token=alice["token"], headers={"Idempotency-Key": key})
|
||||
r.check(st == 409, f"same key, different body -> 409 (got {st})")
|
||||
raw = ('{ "text" : ' + json.dumps(text, ensure_ascii=False) + ' }').encode()
|
||||
st, body, _ = api.raw("POST", path, raw, {"Content-Type": "application/json", "Idempotency-Key": key,
|
||||
"Authorization": "Bearer " + alice["token"]})
|
||||
r.check(st == 201 and json.loads(body)["id"] == first["id"], f"other JSON formatting = same request (got {st})")
|
||||
st, other, _ = api.call("POST", path2, {"text": text}, token=alice["token"], headers={"Idempotency-Key": key})
|
||||
r.check(st == 201 and other["id"] != first["id"], "same key in another chat is independent")
|
||||
st, bobs, _ = api.call("POST", path, {"text": text}, token=bob["token"], headers={"Idempotency-Key": key})
|
||||
r.check(st == 201 and bobs["id"] != first["id"] and bobs["sender_id"] == bob["id"],
|
||||
"same key from another user is independent")
|
||||
st, _, _ = api.raw("POST", path, json.dumps({"text": "без ключа"}).encode(),
|
||||
{"Content-Type": "application/json", "Authorization": "Bearer " + alice["token"]})
|
||||
r.check(st == 400, f"missing Idempotency-Key -> 400 (got {st})")
|
||||
for bad in ("has space", "x" * 129, "slash/key"):
|
||||
st, _, _ = api.call("POST", path, {"text": "bad key"}, token=alice["token"],
|
||||
headers={"Idempotency-Key": bad})
|
||||
r.check(st == 400, f"invalid key {bad[:12]!r}... -> 400 (got {st})")
|
||||
st, _, _ = api.call("POST", path, {"text": text}, headers={"Idempotency-Key": key})
|
||||
r.check(st == 401, f"replay without session -> 401, access re-checked (got {st})")
|
||||
|
||||
print("== неопределённый результат: клиент повторяет с тем же ключом ==")
|
||||
key2 = uuid.uuid4().hex
|
||||
try:
|
||||
api.call("POST", path, {"text": "таймаут?"}, token=alice["token"], headers={"Idempotency-Key": key2},
|
||||
timeout=0.001)
|
||||
except OSError:
|
||||
pass # ответ не дождались: записано или нет — неизвестно
|
||||
st, again, _ = api.call("POST", path, {"text": "таймаут?"}, token=alice["token"], headers={"Idempotency-Key": key2})
|
||||
r.check(st == 201, "retry after uncertain result -> 201")
|
||||
r.check(sum(m["text"] == "таймаут?" for m in history(path, alice["token"])) == 1, "still exactly one message")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
Генератор записей для экспериментов отказа и rolling update (lab3, уровень «4»).
|
||||
|
||||
Несколько потоков в замкнутом цикле отправляют сообщения через LB. У каждого
|
||||
сообщения свой Idempotency-Key; если ответ не получен (ошибка/таймаут/5xx),
|
||||
поток повторяет ТОТ ЖЕ запрос с ТЕМ ЖЕ ключом — так проверяется, что
|
||||
неопределённая запись безопасно повторяется и не даёт дублей.
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from common import Api
|
||||
|
||||
|
||||
class LoadGen:
|
||||
def __init__(self, api: Api, token: str, chat_id: str, workers: int = 4, timeout: float = 2.0):
|
||||
self.api, self.token, self.chat_id = api, token, chat_id
|
||||
self.path = f"/api/v1/chats/{chat_id}/messages"
|
||||
self.workers, self.timeout = workers, timeout
|
||||
self.stop_event = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.ok = [] # (t, instance, message)
|
||||
self.errors = [] # (t, reason)
|
||||
self.retried = 0 # сколько раз повторяли тот же ключ
|
||||
self.threads = []
|
||||
self.t0 = None
|
||||
|
||||
def _worker(self, w: int):
|
||||
i = 0
|
||||
while not self.stop_event.is_set():
|
||||
key = uuid.uuid4().hex
|
||||
text = f"load-{w}-{i}-{key[:8]}"
|
||||
first = True
|
||||
while not self.stop_event.is_set():
|
||||
if not first:
|
||||
with self.lock:
|
||||
self.retried += 1
|
||||
first = False
|
||||
try:
|
||||
st, body, rh = self.api.call("POST", self.path, {"text": text}, token=self.token,
|
||||
headers={"Idempotency-Key": key}, timeout=self.timeout)
|
||||
except OSError as exc:
|
||||
st, body, rh = None, None, None
|
||||
reason = type(exc).__name__
|
||||
else:
|
||||
reason = f"HTTP {st}"
|
||||
now = time.monotonic()
|
||||
if st == 201:
|
||||
with self.lock:
|
||||
self.ok.append((now, rh.get("X-Instance-Id", ""), body))
|
||||
break
|
||||
with self.lock:
|
||||
self.errors.append((now, reason))
|
||||
time.sleep(0.1) # повтор с тем же ключом
|
||||
i += 1
|
||||
|
||||
def start(self):
|
||||
self.t0 = time.monotonic()
|
||||
for w in range(self.workers):
|
||||
t = threading.Thread(target=self._worker, args=(w,), daemon=True)
|
||||
t.start()
|
||||
self.threads.append(t)
|
||||
|
||||
def stop(self):
|
||||
self.stop_event.set()
|
||||
for t in self.threads:
|
||||
t.join(timeout=self.timeout + 2)
|
||||
|
||||
# ---------------------------------------------------------------- метрики
|
||||
def window(self, a: float, b: float) -> dict:
|
||||
"""Успехи/ошибки в окне [a, b) секунд от старта нагрузки."""
|
||||
ok = [x for x in self.ok if a <= x[0] - self.t0 < b]
|
||||
err = [x for x in self.errors if a <= x[0] - self.t0 < b]
|
||||
dur = max(b - a, 1e-9)
|
||||
return {"successful": len(ok), "errors": len(err), "successful_rps": round(len(ok) / dur, 1)}
|
||||
|
||||
def max_gap_after(self, t_abs: float) -> float:
|
||||
"""Самый длинный промежуток без успешной записи после момента t_abs (сек)."""
|
||||
times = [t_abs] + sorted(x[0] for x in self.ok if x[0] >= t_abs)
|
||||
if len(times) == 1:
|
||||
return float("inf")
|
||||
return round(max(b - a for a, b in zip(times, times[1:])), 3)
|
||||
|
||||
def first_success_after(self, t_abs: float):
|
||||
later = sorted(x[0] for x in self.ok if x[0] >= t_abs)
|
||||
return round(later[0] - t_abs, 3) if later else None
|
||||
|
||||
def instances_after(self, t_abs: float) -> list:
|
||||
return [x[1] for x in sorted(self.ok) if x[0] >= t_abs]
|
||||
|
||||
def verify(self) -> dict:
|
||||
"""Все подтверждённые сообщения есть в истории без изменений, дублей нет."""
|
||||
items, cursor = [], None
|
||||
while True:
|
||||
q = "?limit=100" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
st, page, _ = self.api.call("GET", self.path + q, token=self.token)
|
||||
assert st == 200, f"history read failed: {st}"
|
||||
items += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
by_id = {m["id"]: m for m in items}
|
||||
texts = [m["text"] for m in items]
|
||||
confirmed = [x[2] for x in self.ok]
|
||||
lost = [m for m in confirmed if by_id.get(m["id"]) != m]
|
||||
return {"history_messages": len(items), "confirmed": len(confirmed),
|
||||
"lost_or_changed": len(lost), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"retries_with_same_key": self.retried}
|
||||
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Logout при приостановленном Redis (замечание к app/sessions.py).
|
||||
|
||||
Сценарий преподавателя: прогреть сессию в кэше, приостановить Redis, сделать
|
||||
logout, восстановить Redis и проверить старый токен.
|
||||
Требование: 204 только при гарантированном отзыве; после 204 старый токен
|
||||
никогда не принимается, в том числе после восстановления Redis.
|
||||
|
||||
python student-tests/logout_cache.py --base-url http://localhost:8080
|
||||
(по умолчанию сам делает docker compose pause/unpause redis)
|
||||
"""
|
||||
import argparse
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
COMPOSE = "docker compose --env-file .env"
|
||||
|
||||
|
||||
def sh(cmd: str):
|
||||
print(f" $ {cmd}")
|
||||
subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--pause-redis", default=f"{COMPOSE} pause redis")
|
||||
ap.add_argument("--unpause-redis", default=f"{COMPOSE} unpause redis")
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
user = api.new_user("logoutcache")
|
||||
token = user["token"]
|
||||
for _ in range(2): # первый запрос кладёт сессию в Redis, второй читает из кэша
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=token)
|
||||
r.check(st == 200, "session is warmed up in cache")
|
||||
|
||||
print("== Redis приостановлен ==")
|
||||
sh(args.pause_redis)
|
||||
try:
|
||||
st_logout, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=token)
|
||||
r.check(st_logout != 204,
|
||||
f"logout is NOT confirmed while cache cannot be invalidated (got {st_logout}, expected 503)")
|
||||
finally:
|
||||
sh(args.unpause_redis)
|
||||
time.sleep(0.5)
|
||||
|
||||
print("== Redis восстановлен ==")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=token)
|
||||
if st_logout == 204:
|
||||
r.check(st == 401, f"after a 204 the old token is rejected after Redis recovery (got {st})")
|
||||
else:
|
||||
r.check(st == 200, f"unconfirmed logout left the session consistent and valid (got {st})")
|
||||
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=token)
|
||||
r.check(st == 204, f"retry logout after Redis recovery -> 204 (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=token)
|
||||
r.check(st == 401, f"old token after confirmed logout -> 401, no stale cache copy (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=token)
|
||||
r.check(st == 401, f"old token still rejected on repeat (got {st})")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Согласованность S3 ↔ PostgreSQL при сбоях (lab4, уровень «4»).
|
||||
Сам управляет контейнерами через docker compose; запускать из корня репозитория:
|
||||
|
||||
docker compose --env-file .env --profile fault up -d api-fault
|
||||
python student-tests/orphans.py --base-url http://localhost:8080 --fault-url http://localhost:8082
|
||||
|
||||
Сценарии:
|
||||
1. Прерванная загрузка (клиент оборвал тело) → в S3 и журнале ничего не появилось.
|
||||
2. PUT в S3 прошёл, запись в БД упала (db-error-after-s3-put) → 503, API сразу
|
||||
компенсирует: объект и строка журнала удалены, вложения нет.
|
||||
3. PUT прошёл, процесс убит до COMMIT (crash-after-s3-put, os._exit) → остаётся
|
||||
объект + строка upload_intents (известная сирота). Janitor:
|
||||
- с рабочим grace period (900 c) её НЕ трогает (может быть живая загрузка);
|
||||
- dry-run показывает, что удалит, и ничего не меняет;
|
||||
- после истечения grace удаляет объект и строку; повтор — без изменений.
|
||||
4. Объект без журнала и без метаданных (страховка) → находится обходом bucket
|
||||
(--scan-bucket) и удаляется только после grace.
|
||||
5. Готовые вложения не удаляются никогда: после всех проходов скачиваются, sha256 совпадает.
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
from common import SAMPLE_PNG, Api, Report, compose, janitor, raw_http, sha256, tool, upload
|
||||
|
||||
|
||||
def wait_ready(api: Api, seconds: int = 60) -> bool:
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if api.raw("GET", "/health/ready", timeout=3)[0] == 200:
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--fault-url", default="http://localhost:8082")
|
||||
ap.add_argument("--grace", type=int, default=5, help="маленький grace для теста (с)")
|
||||
args = ap.parse_args()
|
||||
api, fault, r = Api(args.base_url), Api(args.fault_url), Report()
|
||||
r.check(wait_ready(fault, 60), "fault replica (profile fault) is ready on --fault-url")
|
||||
|
||||
user = api.new_user("orphan")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "orphans", "member_ids": [user["id"]]},
|
||||
token=user["token"])
|
||||
st, keep, _ = upload(api, user["token"], chat["id"], SAMPLE_PNG, "keep.png")
|
||||
r.check(st == 201, "committed attachment that must survive every cleanup")
|
||||
# Сначала дочищаем всё старое, чтобы считать объекты от нуля.
|
||||
janitor("--grace-seconds", "0", "--scan-bucket")
|
||||
base = tool("stats")
|
||||
print(" baseline:", base)
|
||||
|
||||
print("== 1. прерванная загрузка ==")
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=cut.png"
|
||||
raw_http(args.base_url, "POST", path,
|
||||
{"Authorization": "Bearer " + user["token"], "Content-Type": "image/png",
|
||||
"Content-Length": str(len(SAMPLE_PNG))},
|
||||
chunks=[SAMPLE_PNG[:20000]], close_after_send=True)
|
||||
time.sleep(2)
|
||||
now = tool("stats")
|
||||
r.check(now == base, f"no object, no metadata, no journal row after interrupted upload ({now})")
|
||||
|
||||
print("== 2. отказ БД после PUT: немедленная компенсация ==")
|
||||
st, body, _ = upload(fault, user["token"], chat["id"], SAMPLE_PNG, "dbfail.png",
|
||||
headers={"X-Fault-Inject": "db-error-after-s3-put"})
|
||||
r.check(st == 503, f"upload answered 503, not 201 (got {st})")
|
||||
now = tool("stats")
|
||||
r.check(now == base, f"object deleted by compensation, journal clean ({now})")
|
||||
|
||||
print("== 3. процесс убит между PUT и COMMIT ==")
|
||||
try:
|
||||
st, _, _ = upload(fault, user["token"], chat["id"], SAMPLE_PNG, "crash.png",
|
||||
headers={"X-Fault-Inject": "crash-after-s3-put"}, timeout=20)
|
||||
except OSError:
|
||||
st = None
|
||||
r.check(st != 201, f"client did NOT get 201 (got {st})")
|
||||
time.sleep(1)
|
||||
now = tool("stats")
|
||||
r.check(now["objects"] == base["objects"] + 1 and now["upload_intents"] == base["upload_intents"] + 1
|
||||
and now["attachments"] == base["attachments"],
|
||||
f"orphan object + journal row left behind, no metadata ({now})")
|
||||
s = janitor() # рабочий grace period
|
||||
r.check(s["objects_deleted"] == 0 and tool("stats") == now,
|
||||
f"default grace {s['grace_seconds']} s: fresh upload is NOT touched")
|
||||
time.sleep(args.grace + 1)
|
||||
s = janitor("--grace-seconds", str(args.grace), "--dry-run")
|
||||
r.check(s["would_delete_objects"] == 1 and tool("stats") == now, "dry-run reports 1 object, changes nothing")
|
||||
s = janitor("--grace-seconds", str(args.grace))
|
||||
after = tool("stats")
|
||||
r.check(s["objects_deleted"] == 1 and after == base, f"janitor removed orphan + journal row ({s})")
|
||||
s = janitor("--grace-seconds", str(args.grace))
|
||||
r.check(s["objects_deleted"] == 0 and tool("stats") == base, "second run is a no-op (idempotent)")
|
||||
|
||||
print("== 4. объект без журнала (страховочный обход bucket) ==")
|
||||
compose("exec", "-T", "api", "python", "-c",
|
||||
"import uuid; from app import storage; storage.init(); "
|
||||
"storage.client().put_object(Bucket=storage.settings.s3_bucket, "
|
||||
"Key=storage.object_key(uuid.uuid4()), Body=b'lost')")
|
||||
r.check(tool("stats")["objects"] == base["objects"] + 1, "untracked object planted")
|
||||
s = janitor("--scan-bucket", "--grace-seconds", "3600")
|
||||
r.check(s["orphans_found"] == 0, "scan with grace 1 h ignores a fresh object")
|
||||
time.sleep(args.grace + 1)
|
||||
s = janitor("--scan-bucket", "--grace-seconds", str(args.grace), "--dry-run")
|
||||
r.check(s["orphans_found"] == 1 and tool("stats")["objects"] == base["objects"] + 1, "scan dry-run finds 1")
|
||||
s = janitor("--scan-bucket", "--grace-seconds", str(args.grace))
|
||||
r.check(s["objects_deleted"] == 1 and tool("stats") == base, f"scan deletes the untracked object ({s})")
|
||||
|
||||
print("== 5. готовые вложения не тронуты ==")
|
||||
st, raw, _ = api.raw("GET", f"/api/v1/attachments/{keep['id']}/content",
|
||||
headers={"Authorization": "Bearer " + user["token"]})
|
||||
r.check(st == 200 and sha256(raw) == keep["sha256"], "committed attachment still downloads, sha256 matches")
|
||||
state = tool("state", keep["id"])
|
||||
r.check(state == {"object_exists": True, "attachment_row": True, "upload_intent": False},
|
||||
f"object + metadata, no journal row ({state})")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Недоступность зависимостей (уровень «4»). Сам останавливает и запускает контейнеры:
|
||||
python student-tests/outage.py --base-url http://localhost:8080
|
||||
|
||||
1. Redis остановлен → API работает в обход кэша (сессии читаются из PostgreSQL).
|
||||
2. PostgreSQL остановлен → защищённые запросы получают ограниченную ошибку 503,
|
||||
неизвестный токен НЕ принимается (никогда 200), /health/ready = 503.
|
||||
3. PostgreSQL запущен снова → тот же токен снова работает, данные на месте.
|
||||
"""
|
||||
import argparse
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from common import Api, Report
|
||||
|
||||
COMPOSE = "docker compose --env-file .env"
|
||||
|
||||
|
||||
def sh(cmd: str):
|
||||
print(f" $ {cmd}")
|
||||
subprocess.run(shlex.split(cmd), check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(api: Api, seconds=90):
|
||||
deadline = time.time() + seconds
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if api.raw("GET", "/health/ready", timeout=3)[0] == 200:
|
||||
return True
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--stop-redis", default=f"{COMPOSE} stop redis")
|
||||
ap.add_argument("--start-redis", default=f"{COMPOSE} start redis")
|
||||
ap.add_argument("--stop-db", default=f"{COMPOSE} stop postgres")
|
||||
ap.add_argument("--start-db", default=f"{COMPOSE} start postgres")
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
user = api.new_user("outage")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "outage", "member_ids": [user["id"]]}, token=user["token"])
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
api.call("POST", path, {"text": "before outage"}, token=user["token"])
|
||||
|
||||
print("== 1. Redis недоступен ==")
|
||||
sh(args.stop_redis)
|
||||
try:
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=user["token"])
|
||||
r.check(st == 200, "valid token still works without Redis (cache bypassed)")
|
||||
st, _, _ = api.call("POST", path, {"text": "without redis"}, token=user["token"])
|
||||
r.check(st == 201, "writes still work without Redis")
|
||||
fresh = api.register("noredis")
|
||||
st, sess, _ = api.login(fresh["username"], fresh["password"])
|
||||
r.check(st == 201, "login works without Redis")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st == 401, "forged token still rejected without Redis")
|
||||
finally:
|
||||
sh(args.start_redis)
|
||||
|
||||
print("== 2. PostgreSQL недоступен ==")
|
||||
sh(args.stop_db)
|
||||
try:
|
||||
time.sleep(1)
|
||||
st, _, _ = api.call("GET", path, token=user["token"])
|
||||
r.check(st == 503, f"history without DB -> 503, not a hang (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st in (401, 503), f"unknown token is never trusted without DB (got {st})")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me")
|
||||
r.check(st == 401, "anonymous request -> 401")
|
||||
st = api.raw("GET", "/health/ready")[0]
|
||||
r.check(st == 503, "/health/ready -> 503")
|
||||
st = api.raw("GET", "/health/live")[0]
|
||||
r.check(st == 200, "/health/live -> 200 (process is alive)")
|
||||
finally:
|
||||
sh(args.start_db)
|
||||
|
||||
print("== 3. восстановление ==")
|
||||
r.check(wait_ready(api), "/health/ready back to 200")
|
||||
st, page, _ = api.call("GET", path, token=user["token"])
|
||||
texts = [m["text"] for m in (page or {}).get("items", [])]
|
||||
r.check(st == 200 and "before outage" in texts and "without redis" in texts,
|
||||
"same token reads the same history after DB is back")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Конкурентная запись: 10 клиентов параллельно отправляют по 10 сообщений.
|
||||
Ожидаем ровно 100 уникальных сообщений в истории.
|
||||
python student-tests/race.py --base-url http://localhost:8080
|
||||
"""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import Api
|
||||
|
||||
CLIENTS, PER_CLIENT = 10, 10
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
api = Api(ap.parse_args().base_url)
|
||||
user = api.new_user("race")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "race", "member_ids": [user["id"]]}, token=user["token"])
|
||||
mpath = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
def worker(w):
|
||||
return [api.call("POST", mpath, {"text": f"c{w}-m{i}"}, token=user["token"])[0] for i in range(PER_CLIENT)]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
codes = [c for batch in pool.map(worker, range(CLIENTS)) for c in batch]
|
||||
|
||||
ids, texts, cursor = [], [], None
|
||||
while True:
|
||||
st, page, _ = api.call("GET", f"{mpath}?limit=50" + (f"&cursor={cursor}" if cursor else ""), token=user["token"])
|
||||
ids += [m["id"] for m in page["items"]]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
expected = {f"c{w}-m{i}" for w in range(CLIENTS) for i in range(PER_CLIENT)}
|
||||
ok = codes.count(201) == 100 and len(ids) == 100 and len(set(ids)) == 100 and set(texts) == expected
|
||||
print(f"sent=100 accepted={codes.count(201)} received={len(ids)} unique_ids={len(set(ids))} "
|
||||
f"all_texts_present={set(texts) == expected}")
|
||||
print("PASS" if ok else "FAIL")
|
||||
raise SystemExit(0 if ok else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""
|
||||
Rollback составной операции «создать чат + участников» (уровень «4»).
|
||||
|
||||
Создаём чат, где последний участник — несуществующий пользователь. Проверку
|
||||
приложения нарочно обходим и вызываем запись напрямую: первый INSERT в chats
|
||||
проходит, а вставка участника падает на внешнем ключе. Ожидаем, что транзакция
|
||||
откатилась целиком: ни чата, ни участников в базе нет.
|
||||
|
||||
Запуск внутри контейнера API (у него есть доступ к БД и коду):
|
||||
docker compose cp student-tests/rollback_check.py api:/tmp/rollback_check.py
|
||||
docker compose exec api python /tmp/rollback_check.py
|
||||
Локально без Docker: python student-tests/rollback_check.py
|
||||
"""
|
||||
import asyncio
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path.cwd()))
|
||||
import psycopg # noqa: E402
|
||||
|
||||
from app import repo # noqa: E402
|
||||
from app.config import settings # noqa: E402
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
async with await psycopg.AsyncConnection.connect(settings.database_url) as conn:
|
||||
creator = await repo.create_user(conn, "rb_" + uuid.uuid4().hex[:10], "rb", "x")
|
||||
await conn.commit()
|
||||
ghost = uuid.uuid4() # такого пользователя нет
|
||||
try:
|
||||
async with conn.transaction():
|
||||
await repo.insert_chat(conn, title, [uuid.UUID(creator["id"]), ghost], creator["id"])
|
||||
print("FAIL - insert unexpectedly succeeded")
|
||||
return 1
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
print(" ok - insert of unknown member failed on foreign key")
|
||||
cur = await conn.execute(
|
||||
"SELECT count(*) FROM chats WHERE title = %s", (title,))
|
||||
chats = (await cur.fetchone())[0]
|
||||
cur = await conn.execute(
|
||||
"SELECT count(*) FROM chat_members m JOIN chats c ON c.id = m.chat_id WHERE c.title = %s", (title,))
|
||||
members = (await cur.fetchone())[0]
|
||||
ok = chats == 0 and members == 0
|
||||
print(f" {'ok ' if ok else 'FAIL'} - after rollback: chats={chats}, members={members} (expected 0, 0)")
|
||||
print("PASS" if ok else "FAIL")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(asyncio.run(main()))
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Поочерёдная замена реплик API (rolling update) под нагрузкой (lab3, уровень «4»).
|
||||
|
||||
Compose не делает rolling update сам, поэтому замена выполняется по шагам:
|
||||
1. собрать новый образ (docker compose build api);
|
||||
2. для каждой старой реплики:
|
||||
поднять ОДНУ новую (up --scale api=N+1 --no-recreate) → дождаться healthy
|
||||
и того, что LB её обслуживает → остановить старую (SIGTERM, graceful) → удалить;
|
||||
3. всё это время нагрузка пишет сообщения через LB и повторяет неудачные
|
||||
запросы с тем же Idempotency-Key.
|
||||
Итог: ошибки/RPS во время замены, все реплики на новом образе, нет потерь и дублей.
|
||||
|
||||
Миграции: перед заменой выполняется сервис migrate (однократно). Новые миграции
|
||||
должны быть совместимы с ещё работающей старой версией (только добавление).
|
||||
|
||||
python student-tests/rolling_update.py --base-url http://localhost:8080 --output evidence/rolling-update.json
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from common import Api, Report
|
||||
from failover_each import served_instances
|
||||
from loadgen import LoadGen
|
||||
|
||||
COMPOSE = "docker compose --env-file .env"
|
||||
|
||||
|
||||
def sh(cmd: str) -> str:
|
||||
print(f" $ {cmd}")
|
||||
return subprocess.run(shlex.split(cmd), check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def api_ids() -> list:
|
||||
return [x.strip() for x in sh(f"{COMPOSE} ps -q api").splitlines() if x.strip()]
|
||||
|
||||
|
||||
def image_of(cid: str) -> str:
|
||||
return sh(f"docker inspect -f {{{{.Image}}}} {cid}").strip()
|
||||
|
||||
|
||||
def wait_healthy(cid: str, seconds: float = 90) -> bool:
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if sh(f"docker inspect -f {{{{.State.Health.Status}}}} {cid}").strip() == "healthy":
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def wait_served(api: Api, iid: str, seconds: float = 60) -> bool:
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if iid in served_instances(api, 10):
|
||||
return True
|
||||
time.sleep(0.5)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--no-build", action="store_true", help="не пересобирать образ")
|
||||
ap.add_argument("--output", default=None)
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
if not args.no_build:
|
||||
sh(f"{COMPOSE} build api")
|
||||
sh(f"{COMPOSE} run --rm migrate") # однократные миграции до замены
|
||||
new_image = sh("docker image inspect -f {{.Id}} mtusi-messenger:lab4").strip()
|
||||
old = api_ids()
|
||||
n = len(old)
|
||||
r.check(n >= 2, f"{n} replicas before update")
|
||||
old_images = {cid[:12]: image_of(cid) for cid in old}
|
||||
|
||||
user = api.new_user("rolling")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "rolling", "member_ids": [user["id"]]},
|
||||
token=user["token"])
|
||||
gen = LoadGen(api, user["token"], chat["id"], workers=args.workers)
|
||||
gen.start()
|
||||
time.sleep(3)
|
||||
t_begin = time.monotonic()
|
||||
steps = []
|
||||
for cid in old:
|
||||
before = set(api_ids())
|
||||
sh(f"{COMPOSE} up -d --no-deps --no-recreate --scale api={len(before) + 1} api")
|
||||
new = sorted(set(api_ids()) - before)
|
||||
r.check(len(new) == 1, f"one new replica started for {cid[:12]}")
|
||||
new_id = new[0]
|
||||
healthy = wait_healthy(new_id)
|
||||
served = wait_served(api, new_id[:12])
|
||||
t0 = time.monotonic()
|
||||
sh(f"docker stop -t 15 {cid}")
|
||||
sh(f"docker rm {cid}")
|
||||
steps.append({"old": cid[:12], "new": new_id[:12], "new_healthy": healthy, "new_served_by_lb": served,
|
||||
"old_stop_seconds": round(time.monotonic() - t0, 2)})
|
||||
r.check(healthy and served, f"new replica {new_id[:12]} healthy and in LB before old {cid[:12]} stops")
|
||||
t_end = time.monotonic()
|
||||
time.sleep(3)
|
||||
gen.stop()
|
||||
|
||||
final = api_ids()
|
||||
rel_a, rel_b = t_begin - gen.t0, t_end - gen.t0
|
||||
result = {
|
||||
"replicas_before": sorted(old_images), "replicas_after": sorted(c[:12] for c in final),
|
||||
"all_on_new_image": all(image_of(c) == new_image for c in final),
|
||||
"steps": steps,
|
||||
"update_duration_s": round(t_end - t_begin, 1),
|
||||
"before_update": gen.window(0, rel_a),
|
||||
"during_update": gen.window(rel_a, rel_b),
|
||||
"after_update": gen.window(rel_b, rel_b + 3),
|
||||
"max_gap_without_success_s": gen.max_gap_after(t_begin),
|
||||
"instances_serving_at_end": sorted(set(gen.instances_after(t_end))),
|
||||
**gen.verify(),
|
||||
}
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
r.check(len(final) == n, f"replica count restored to {n}")
|
||||
r.check(result["all_on_new_image"], "all replicas run the new image")
|
||||
r.check(not set(result["instances_serving_at_end"]) & set(old_images), "old replicas no longer serve traffic")
|
||||
r.check(result["lost_or_changed"] == 0 and result["duplicate_texts"] == 0, "no lost or duplicated writes")
|
||||
if args.output:
|
||||
with open(args.output, "w", encoding="utf-8") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Собственные тесты lab2 (запуск одной командой):
|
||||
python student-tests/run.py --base-url http://localhost:8080
|
||||
|
||||
Негативные сценарии lab1 на новой аутентификации + проверки уровня «4»:
|
||||
неверный пароль, logout, X-User-Id/Basic не дают доступ, гонка регистрации.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import PASSWORD, Api, Report
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
api = Api(ap.parse_args().base_url)
|
||||
r = Report()
|
||||
|
||||
alice, bob, eve = api.new_user("alice"), api.new_user("bob"), api.new_user("eve")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats",
|
||||
{"title": "own tests", "member_ids": [alice["id"], bob["id"]]}, token=alice["token"])
|
||||
assert st == 201, st
|
||||
mpath = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
print("== аутентификация ==")
|
||||
st, _, rh = api.login(alice["username"], "Wrong-password-123")
|
||||
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Basic"), "wrong password -> 401 + Basic challenge")
|
||||
st, _, _ = api.login("no_such_user_" + uuid.uuid4().hex[:8], PASSWORD)
|
||||
r.check(st == 401, "unknown user -> 401 (same as wrong password)")
|
||||
st, _, rh = api.call("GET", "/api/v1/users/me")
|
||||
r.check(st == 401 and rh.get("WWW-Authenticate", "").startswith("Bearer"), "no token -> 401 + Bearer challenge")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", headers={"X-User-Id": alice["id"]})
|
||||
r.check(st == 401, "X-User-Id alone gives no access")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token="forged-" + uuid.uuid4().hex)
|
||||
r.check(st == 401, "unknown/forged token -> 401")
|
||||
basic = base64.b64encode(f"{alice['username']}:{alice['password']}".encode()).decode()
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", headers={"Authorization": "Basic " + basic})
|
||||
r.check(st == 401, "Basic on business endpoint -> 401")
|
||||
st, me, _ = api.call("GET", "/api/v1/users/me", token=alice["token"], headers={"X-User-Id": eve["id"]})
|
||||
r.check(st == 200 and me["id"] == alice["id"], "X-User-Id cannot override bearer identity")
|
||||
st, _, _ = api.call("POST", "/api/v1/users", {"username": "short_pw_" + uuid.uuid4().hex[:6],
|
||||
"display_name": "x", "password": "short"})
|
||||
r.check(st == 400, "password shorter than 12 -> 400")
|
||||
|
||||
print("== logout ==")
|
||||
tmp = api.new_user("logout")
|
||||
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"])
|
||||
r.check(st == 204, "logout -> 204")
|
||||
st, _, _ = api.call("GET", "/api/v1/users/me", token=tmp["token"])
|
||||
r.check(st == 401, "token after logout -> 401")
|
||||
st, _, _ = api.call("DELETE", "/api/v1/auth/sessions/current", token=tmp["token"])
|
||||
r.check(st == 401, "second logout -> 401")
|
||||
|
||||
print("== гонка регистрации одного username ==")
|
||||
name = "race_" + uuid.uuid4().hex[:10]
|
||||
|
||||
def reg(_):
|
||||
st, _, _ = api.call("POST", "/api/v1/users", {"username": name, "display_name": "r", "password": PASSWORD})
|
||||
return st
|
||||
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
codes = list(pool.map(reg, range(20)))
|
||||
r.check(codes.count(201) == 1 and codes.count(409) == 19,
|
||||
f"20 parallel registrations -> one 201, nineteen 409 (got {sorted(codes)})")
|
||||
|
||||
print("== ошибки и доступ (из lab1) ==")
|
||||
st, _, _ = api.raw("POST", "/api/v1/users", b"{not json", {"Content-Type": "application/json"})
|
||||
r.check(st == 400, "malformed JSON -> 400")
|
||||
st, _, _ = api.call("POST", "/api/v1/users", {"username": alice["username"], "display_name": "d", "password": PASSWORD})
|
||||
r.check(st == 409, "duplicate username -> 409")
|
||||
st, _, _ = api.call("POST", mpath, {"text": " "}, token=alice["token"])
|
||||
r.check(st == 400, "blank message -> 400")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "x", "sender_id": eve["id"]}, token=alice["token"])
|
||||
r.check(st == 400, "sender_id in body is rejected")
|
||||
st, _, _ = api.call("POST", mpath, {"text": "чужое"}, token=eve["token"])
|
||||
r.check(st == 404, "outsider POST to foreign chat -> 404")
|
||||
st, _, _ = api.call("GET", mpath, token=eve["token"])
|
||||
r.check(st == 404, "outsider GET foreign history -> 404")
|
||||
st, _, _ = api.call("GET", "/api/v1/chats/not-a-uuid", token=alice["token"])
|
||||
r.check(st == 400, "invalid chat uuid -> 400")
|
||||
|
||||
print("== пагинация ==")
|
||||
for i in range(5):
|
||||
api.call("POST", mpath, {"text": f"m{i}"}, token=bob["token"])
|
||||
seen, cursor, pages = [], None, 0
|
||||
while pages < 10:
|
||||
st, page, _ = api.call("GET", f"{mpath}?limit=2" + (f"&cursor={cursor}" if cursor else ""), token=alice["token"])
|
||||
pages += 1
|
||||
seen += [m["id"] for m in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
r.check(len(seen) == 5 and len(set(seen)) == 5 and pages == 3, "5 messages / limit 2 -> 3 pages, no duplicates")
|
||||
st, other, _ = api.call("POST", "/api/v1/chats", {"title": "other", "member_ids": [alice["id"]]}, token=alice["token"])
|
||||
st, p, _ = api.call("GET", f"{mpath}?limit=1", token=alice["token"])
|
||||
st, _, _ = api.call("GET", f"/api/v1/chats/{other['id']}/messages?cursor={p['next_cursor']}", token=alice["token"])
|
||||
r.check(st == 400, "cursor from another chat -> 400")
|
||||
|
||||
print("== Content-Type ==")
|
||||
body = json.dumps({"username": "ct_" + uuid.uuid4().hex[:8], "display_name": "c", "password": PASSWORD}).encode()
|
||||
st, _, _ = api.raw("POST", "/api/v1/users", body, {"Content-Type": "text/plain"})
|
||||
r.check(st == 415, f"valid JSON with text/plain -> 415 (got {st})")
|
||||
st, _, _ = api.raw("POST", mpath, json.dumps({"text": "x"}).encode(),
|
||||
{"Content-Type": "text/plain", "Authorization": "Bearer " + alice["token"]})
|
||||
r.check(st == 415, f"message with text/plain -> 415 (got {st})")
|
||||
st, _, _ = api.raw("POST", "/api/v1/chats", b"{}", {"Content-Type": "text/plain"})
|
||||
r.check(st == 401, f"text/plain without token -> 401 first (got {st})")
|
||||
st, _, _ = api.raw("POST", mpath, json.dumps({"text": "utf8"}).encode(),
|
||||
{"Content-Type": "application/json; charset=utf-8", "Authorization": "Bearer " + alice["token"],
|
||||
"Idempotency-Key": uuid.uuid4().hex})
|
||||
r.check(st == 201, f"application/json; charset=utf-8 accepted (got {st})")
|
||||
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Недоступность S3 (lab4). Сам останавливает и запускает MinIO; из корня репозитория:
|
||||
|
||||
python student-tests/s3_outage.py --base-url http://localhost:8080
|
||||
|
||||
Ожидание: пока MinIO остановлен, загрузка и скачивание дают быстрый 503 в формате
|
||||
контракта (не зависание и не 500), а текстовая часть мессенджера, метаданные
|
||||
вложений и /health/ready работают (S3 не критичен для обязательного текстового пути).
|
||||
После старта MinIO всё снова работает, ранее загруженный файл не изменился.
|
||||
Брошенная во время отказа запись журнала дочищается janitor после grace period.
|
||||
"""
|
||||
import argparse
|
||||
import time
|
||||
|
||||
from common import SAMPLE_PNG, Api, Report, compose, janitor, sha256, tool, upload
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
u = api.new_user("s3down")
|
||||
T = u["token"]
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "s3 outage", "member_ids": [u["id"]]}, token=T)
|
||||
st, before, _ = upload(api, T, chat["id"], SAMPLE_PNG, "before.png")
|
||||
r.check(st == 201, "upload before outage")
|
||||
content = f"/api/v1/attachments/{before['id']}/content"
|
||||
|
||||
print("== MinIO остановлен ==")
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
t0 = time.monotonic()
|
||||
st, body, _ = upload(api, T, chat["id"], SAMPLE_PNG, "during.png", timeout=30)
|
||||
took = time.monotonic() - t0
|
||||
r.check(st == 503 and body and body["error"]["code"] == "unavailable", f"upload -> 503 unavailable (got {st})")
|
||||
r.check(took < 15, f"bounded by timeouts, not a hang ({took:.1f} s)")
|
||||
st, _, _ = api.raw("GET", content, headers={"Authorization": "Bearer " + T}, timeout=30)
|
||||
r.check(st == 503, f"download -> 503 (got {st})")
|
||||
st, meta, _ = api.call("GET", f"/api/v1/attachments/{before['id']}", token=T)
|
||||
r.check(st == 200 and meta["sha256"] == before["sha256"], "metadata still served from PostgreSQL")
|
||||
st, _, _ = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "S3 лежит, а чат работает"}, token=T)
|
||||
r.check(st == 201, "text messages still work")
|
||||
st, _, _ = api.call("POST", f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": "с вложением", "attachment_ids": [before["id"]]}, token=T)
|
||||
r.check(st == 201, "message referencing an existing attachment still works (metadata only)")
|
||||
r.check(api.raw("GET", "/health/ready")[0] == 200, "/health/ready = 200 (S3 is not critical for text path)")
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
|
||||
print("== MinIO снова работает ==")
|
||||
# После старта MinIO каждая реплика может ещё до S3_BREAKER_SECONDS (5 c) отвечать 503:
|
||||
# предохранитель закрывается по таймеру. Поэтому ждём, пока ОБЕ реплики восстановятся:
|
||||
# несколько успешных загрузок подряд (LB чередует реплики).
|
||||
t0 = time.monotonic()
|
||||
ok = False
|
||||
for _ in range(40):
|
||||
st, raw, _ = api.raw("GET", content, headers={"Authorization": "Bearer " + T})
|
||||
if st == 200:
|
||||
ok = sha256(raw) == before["sha256"]
|
||||
break
|
||||
time.sleep(0.5)
|
||||
r.check(ok, "file uploaded before outage downloads unchanged")
|
||||
streak, codes = 0, []
|
||||
while time.monotonic() - t0 < 40 and streak < 4:
|
||||
st, _, rh = upload(api, T, chat["id"], SAMPLE_PNG, "after.png")
|
||||
codes.append(st)
|
||||
streak = streak + 1 if st == 201 else 0
|
||||
if st != 201:
|
||||
time.sleep(0.5)
|
||||
recovered = time.monotonic() - t0
|
||||
r.check(streak >= 4, f"uploads work again on all replicas: 4 x 201 in a row after {recovered:.1f} s "
|
||||
f"(codes during recovery: {codes})")
|
||||
stats = tool("stats")
|
||||
print(" stats:", stats)
|
||||
s = janitor("--grace-seconds", "0")
|
||||
r.check(s["errors"] == 0, f"janitor cleaned journal rows left by failed uploads ({s})")
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Эксперимент: пик памяти API при N одновременных загрузках (lab4, уровень «4»).
|
||||
|
||||
python student-tests/upload_memory.py --base-url http://localhost:8080 \
|
||||
--concurrency 10 --output evidence/upload-memory-10.json
|
||||
|
||||
Гипотеза: память реплики почти не зависит от размера и числа одновременных
|
||||
загрузок, потому что тело не копится в RAM (≤ UPLOAD_SPOOL_MEMORY_BYTES в памяти,
|
||||
остальное во временном файле), проверка изображения потоковая, в S3 уходит поток.
|
||||
Наивная реализация (`await request.body()` + `Image.open().load()`) держала бы
|
||||
≥ размер файла × 2…4 на каждую загрузку: 10 × 9,5 МБ → 200–400 МБ, что больше
|
||||
лимита контейнера 256 МБ (OOM).
|
||||
|
||||
Методика: генерируется настоящий PNG из шума ≈9,5 МБ (почти не сжимается),
|
||||
N потоков одновременно отправляют его через LB (несколько раундов), параллельно
|
||||
каждые ~0,3 с читается память cgroup v2 всех контейнеров api (usage как в docker stats, anon, memory.peak). Фиксируются память
|
||||
до нагрузки, пик во время и после, время ответа, коды ответов и sha256.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from common import ROOT, Api, Report, compose, make_png, sha256, upload
|
||||
|
||||
# Печатаем «имя значение»: cgroup v2, иначе v1 (старые ядра/Docker Desktop с cgroup v1).
|
||||
CGROUP = (
|
||||
"if [ -f /sys/fs/cgroup/memory.current ]; then "
|
||||
"echo current $(cat /sys/fs/cgroup/memory.current); "
|
||||
"grep -E '^(anon|inactive_file) ' /sys/fs/cgroup/memory.stat; "
|
||||
"[ -f /sys/fs/cgroup/memory.peak ] && echo peak $(cat /sys/fs/cgroup/memory.peak); "
|
||||
"else M=/sys/fs/cgroup/memory; "
|
||||
"echo current $(cat $M/memory.usage_in_bytes); "
|
||||
"grep -E '^total_(rss|inactive_file) ' $M/memory.stat | sed -e 's/^total_rss/anon/' -e 's/^total_//'; "
|
||||
"echo peak $(cat $M/memory.max_usage_in_bytes); fi")
|
||||
UNITS = {"B": 1, "KiB": 1024, "MiB": 1024 ** 2, "GiB": 1024 ** 3, "kB": 1000, "MB": 1000 ** 2, "GB": 1000 ** 3}
|
||||
|
||||
|
||||
def api_containers() -> list[str]:
|
||||
return [c[:12] for c in compose("ps", "-q", "api").split()]
|
||||
|
||||
|
||||
def _docker_stats(cid: str) -> dict:
|
||||
"""Запасной путь: docker stats (usage без файлового кэша)."""
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}", cid],
|
||||
capture_output=True, text=True, cwd=ROOT).stdout
|
||||
m = re.match(r"\s*([\d.]+)\s*([A-Za-z]+)", out)
|
||||
usage = round(float(m.group(1)) * UNITS[m.group(2)] / 1024 ** 2, 1) if m else 0.0
|
||||
return {"usage": usage, "anon": usage, "peak": None}
|
||||
|
||||
|
||||
_warned: list = []
|
||||
|
||||
|
||||
def read_cgroup(cid: str) -> dict:
|
||||
"""Память контейнера (MiB): usage как в docker stats (current − inactive_file),
|
||||
anon — память процессов без файлового кэша, peak — максимум за жизнь cgroup."""
|
||||
p = subprocess.run(["docker", "exec", cid, "sh", "-c", CGROUP],
|
||||
capture_output=True, text=True, cwd=ROOT)
|
||||
vals = {}
|
||||
for line in p.stdout.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[1].isdigit():
|
||||
vals[parts[0]] = int(parts[1])
|
||||
if "current" not in vals:
|
||||
if not _warned:
|
||||
_warned.append(1)
|
||||
print(f" cgroup read failed (exit {p.returncode}: {p.stderr.strip()[:200]!r}); using docker stats")
|
||||
return _docker_stats(cid)
|
||||
mib = 1024 ** 2
|
||||
return {"usage": round((vals["current"] - vals.get("inactive_file", 0)) / mib, 1),
|
||||
"anon": round(vals.get("anon", vals["current"]) / mib, 1),
|
||||
"peak": round(vals["peak"] / mib, 1) if "peak" in vals else None}
|
||||
|
||||
|
||||
def sample_mem(ids: list[str]) -> dict:
|
||||
with ThreadPoolExecutor(max_workers=len(ids) or 1) as pool:
|
||||
return dict(zip(ids, pool.map(read_cgroup, ids)))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--concurrency", type=int, default=10)
|
||||
ap.add_argument("--rounds", type=int, default=3)
|
||||
ap.add_argument("--width", type=int, default=1780, help="PNG width/height: 1780 → ≈9,5 МБ")
|
||||
ap.add_argument("--output", default=None)
|
||||
args = ap.parse_args()
|
||||
api, r = Api(args.base_url), Report()
|
||||
|
||||
data = make_png(args.width, args.width, noise=True)
|
||||
digest = sha256(data)
|
||||
print(f"file: {len(data)} bytes ({len(data) / 1024 ** 2:.2f} MiB), sha256 {digest[:12]}…")
|
||||
u = api.new_user("memexp")
|
||||
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "memory", "member_ids": [u["id"]]}, token=u["token"])
|
||||
|
||||
ids = api_containers()
|
||||
idle = sample_mem(ids)
|
||||
print("idle MiB:", idle)
|
||||
peak = {k: {"usage": v["usage"], "anon": v["anon"]} for k, v in idle.items()}
|
||||
samples = []
|
||||
stop = threading.Event()
|
||||
|
||||
def sampler():
|
||||
t0 = time.monotonic()
|
||||
while not stop.is_set():
|
||||
m = sample_mem(ids)
|
||||
samples.append({"t": round(time.monotonic() - t0, 2), **m})
|
||||
for k, v in m.items():
|
||||
for f in ("usage", "anon"):
|
||||
peak[k][f] = max(peak[k][f], v[f])
|
||||
time.sleep(0.2)
|
||||
|
||||
th = threading.Thread(target=sampler, daemon=True)
|
||||
th.start()
|
||||
results = []
|
||||
|
||||
def one(i):
|
||||
t = time.monotonic()
|
||||
try:
|
||||
st, body, rh = upload(api, u["token"], chat["id"], data, f"noise-{i}.png", timeout=120)
|
||||
except OSError as exc:
|
||||
return {"status": None, "error": type(exc).__name__, "seconds": round(time.monotonic() - t, 2)}
|
||||
return {"status": st, "seconds": round(time.monotonic() - t, 2),
|
||||
"sha_ok": bool(body) and body.get("sha256") == digest,
|
||||
"instance": rh.get("X-Instance-Id"), "id": (body or {}).get("id")}
|
||||
|
||||
t_start = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
for rnd in range(args.rounds):
|
||||
results += list(pool.map(one, range(rnd * args.concurrency, (rnd + 1) * args.concurrency)))
|
||||
elapsed = time.monotonic() - t_start
|
||||
time.sleep(2)
|
||||
stop.set()
|
||||
th.join()
|
||||
after = sample_mem(ids)
|
||||
|
||||
ok = [x for x in results if x["status"] == 201]
|
||||
lat = sorted(x["seconds"] for x in ok)
|
||||
summary = {
|
||||
"file_bytes": len(data), "concurrency": args.concurrency, "rounds": args.rounds,
|
||||
"uploads": len(results), "status_counts": {str(s): sum(1 for x in results if x["status"] == s)
|
||||
for s in sorted({x["status"] for x in results}, key=str)},
|
||||
"sha256_ok": sum(1 for x in ok if x["sha_ok"]),
|
||||
"instances": sorted({x["instance"] for x in ok if x["instance"]}),
|
||||
"elapsed_s": round(elapsed, 2),
|
||||
"throughput_MiB_s": round(len(ok) * len(data) / 1024 ** 2 / elapsed, 1) if elapsed else None,
|
||||
"latency_s": {"p50": lat[len(lat) // 2] if lat else None, "max": lat[-1] if lat else None},
|
||||
"memory_MiB": {"idle": idle, "sampled_peak": peak, "after": after,
|
||||
"max_growth_usage": round(max(peak[k]["usage"] - idle[k]["usage"] for k in peak), 1),
|
||||
"max_growth_anon": round(max(peak[k]["anon"] - idle[k]["anon"] for k in peak), 1),
|
||||
"cgroup_peak_after": {k: v["peak"] for k, v in after.items()}},
|
||||
"container_limit_MiB": 256, "samples": len(samples),
|
||||
}
|
||||
print(json.dumps({k: v for k, v in summary.items() if k != "samples"}, ensure_ascii=False, indent=2))
|
||||
|
||||
# Проверка, что сохранены настоящие байты (выборочно).
|
||||
for x in ok[:3]:
|
||||
st, raw, _ = api.raw("GET", f"/api/v1/attachments/{x['id']}/content",
|
||||
headers={"Authorization": "Bearer " + u["token"]}, timeout=60)
|
||||
r.check(st == 200 and sha256(raw) == digest, f"download {x['id'][:8]} sha256 matches")
|
||||
r.check(len(ok) == len(results), f"all {len(results)} uploads -> 201")
|
||||
r.check(summary["sha256_ok"] == len(ok), "sha256 of every upload matches")
|
||||
growth = summary["memory_MiB"]["max_growth_usage"]
|
||||
r.check(growth < 100,
|
||||
f"peak growth per replica {growth} MiB < 100 MiB "
|
||||
f"(naive buffering: ≥ {args.concurrency // 2} × {len(data) / 1024 ** 2:.1f} MiB × 2)")
|
||||
if args.output:
|
||||
with open(args.output, "w", encoding="utf-8") as f:
|
||||
json.dump({**summary, "raw_samples": samples}, f, ensure_ascii=False, indent=2)
|
||||
print("saved", args.output)
|
||||
r.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user