ЛР 5 — БПИ2303 — Лазарев — на 4
Асинхронная обработка вложений: RabbitMQ 4.1 (quorum-очереди, publisher confirms, manual ack, DLQ), transactional outbox, отдельный worker. - upload: оригинал в staging S3, затем одной транзакцией queued + jobs + outbox -> 202; API к брокеру не подключается - relay: публикация outbox с confirm, reaper истёкших аренд, redrive - worker: claim по строке jobs, аренда с heartbeat и fencing по lease_token, transform в подпроцессе с RLIMIT_AS/RLIMIT_CPU/таймаутом, thumbnail 256, crop 128, WebP 1280 по детерминированным ключам - retry с backoff и jitter, постоянные/временные ошибки, реестр failed, ops replay (ready не повторяется), DLQ для невалидных сообщений - janitor: очистка staging и сирот; миграция 004 с backfill вложений lab4 - тесты отказов: окна COMMIT/publish, крахи worker до/после S3 и ack, заморозка worker, всплеск загрузок, права брокера; evidence/ и REPORT.md
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload -> остановка ИМЕННО обслужившей upload реплики -> download через другую.
|
||||
|
||||
python3 student-tests/attachment_failover.py [--output evidence/attachment-failover.json]
|
||||
|
||||
Для каждой API-реплики по очереди: загрузить файл так, чтобы его обслужила эта реплика
|
||||
(round-robin LB, повторяем до попадания), остановить её scripts/stop-one.sh
|
||||
(SIGTERM, контейнер остаётся остановленным), затем 5 раз скачать оригинал через LB и
|
||||
проверить SHA-256 и что отвечает уже другая реплика. Восстановление — scripts/start-all.sh.
|
||||
Доказывает, что на API нет обязательного локального файла оригинала.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
CONTENT = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
instances = set()
|
||||
for _ in range(10):
|
||||
instances.add(c.call("GET", "/health/ready")["headers"]["X-Instance-Id"])
|
||||
check(len(instances) >= 2, "need >=2 replicas")
|
||||
rounds = []
|
||||
for target in sorted(instances):
|
||||
for _ in range(20): # round-robin: попадаем в нужную реплику за пару попыток
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=failover.png" % chat["id"], 202, actor=alice,
|
||||
raw=CONTENT, headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
if r["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise SystemExit("could not hit replica " + target)
|
||||
att = c.wait_ready(alice, r["json"]) # lab5: 202 queued -> ждём ready, затем отказ реплики
|
||||
stop = subprocess.run([str(ROOT / "scripts/stop-one.sh")], env=dict(os.environ, TARGET_INSTANCE_ID=target),
|
||||
capture_output=True, text=True, timeout=60)
|
||||
check(stop.returncode == 0, "stop-one failed")
|
||||
downloads = []
|
||||
for _ in range(5):
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)
|
||||
downloads.append({"instance": d["headers"]["X-Instance-Id"],
|
||||
"sha256_ok": hashlib.sha256(d["bytes"]).hexdigest() == att["sha256"] == hashlib.sha256(CONTENT).hexdigest(),
|
||||
"ms": round(d["elapsed"] * 1000, 1)})
|
||||
meta = c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
ok = all(x["sha256_ok"] and x["instance"] != target for x in downloads) and meta["status"] == "ready"
|
||||
rounds.append({"uploaded_by": target, "stopped": target, "downloads": downloads, "pass": ok})
|
||||
print(json.dumps(rounds[-1]), flush=True)
|
||||
subprocess.run([str(ROOT / "scripts/start-all.sh")], capture_output=True, timeout=120, check=True)
|
||||
time.sleep(4) # HAProxy: rise 2 * inter 1s
|
||||
summary = {"replicas": sorted(instances), "rounds": rounds, "pass": all(r["pass"] for r in rounds)}
|
||||
print(json.dumps({"pass": summary["pass"], "rounds": len(rounds)}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Негативные и граничные сценарии вложений (из lab4; в lab5 upload -> 202, затем ready). Запуск на учебном стенде:
|
||||
|
||||
python3 student-tests/attachments_negative.py [--base-url http://localhost:8080] [--output evidence/attachments-negative.json]
|
||||
|
||||
Использует публичный tests/client.py: каждый ответ проверяется на код, X-Request-Id,
|
||||
X-Instance-Id и (для ошибок) формат {"error":{code,message,request_id}}. Отдельно
|
||||
проверяется, что ни один пользовательский ввод не дал 5xx. Все файлы синтетические и
|
||||
генерируются на лету (большие в Git не хранятся).
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
JPEG = (ROOT / "student-tests/fixtures/sample.jpg").read_bytes()
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
results = []
|
||||
|
||||
|
||||
def chunk(ctype, data):
|
||||
return struct.pack(">I", len(data)) + ctype + data + struct.pack(">I", zlib.crc32(ctype + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width, height, raw, color_type=2, depth=8):
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", raw) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def noise_png(target_bytes):
|
||||
"""Несжимаемый RGB PNG размером чуть меньше target_bytes (zlib level 0)."""
|
||||
width = 1024
|
||||
row = 1 + width * 3
|
||||
height = (target_bytes - 200) // (row + 6 * 0 + 1)
|
||||
while True:
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
data = png(width, height, zlib.compress(raw, 0))
|
||||
if len(data) <= target_bytes:
|
||||
return data
|
||||
height -= 16
|
||||
|
||||
|
||||
class Suite:
|
||||
def __init__(self, c):
|
||||
self.c = c
|
||||
|
||||
def case(self, name, method, path, expected, actor=None, **kw):
|
||||
try:
|
||||
r = self.c.call(method, path, expected, actor=actor, **kw)
|
||||
code = r["json"]["error"]["code"] if r["json"] and "error" in r["json"] else None
|
||||
results.append({"case": name, "expected": expected, "status": r["status"], "error_code": code, "pass": True})
|
||||
return r
|
||||
except Failure as exc:
|
||||
results.append({"case": name, "expected": expected, "error": str(exc), "pass": False})
|
||||
return None
|
||||
|
||||
def upload(self, name, actor, chat, data, expected, ctype="image/png", filename="f.png", raw_query=None):
|
||||
q = raw_query if raw_query is not None else "filename=" + quote(filename, safe="")
|
||||
return self.case(name, "POST", "/api/v1/chats/%s/attachments?%s" % (chat["id"], q), expected,
|
||||
actor=actor, raw=data, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 202 else None)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=60)
|
||||
s = Suite(c)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
chat2 = c.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": "второй чат", "member_ids": [alice["id"], bob["id"]]}, schema="Chat")["json"]
|
||||
eve_chat = c.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "чат Евы", "member_ids": [eve["id"]]}, schema="Chat")["json"]
|
||||
|
||||
# --- позитивные контрольные ---
|
||||
ok_png = s.upload("valid PNG fixture", alice, chat, PNG, 202)
|
||||
ok_jpg = s.upload("valid JPEG", bob, chat, JPEG, 202, ctype="image/jpeg", filename="photo.jpg")
|
||||
uni = s.upload("unicode filename", alice, chat, PNG, 202, filename="фото отпуска 🙂.png")
|
||||
if uni:
|
||||
check(uni["json"]["filename"] == "фото отпуска 🙂.png", "unicode filename changed")
|
||||
def ready(r): # lab5: upload -> 202 queued, байты доступны после ready
|
||||
if r:
|
||||
c.wait_ready(alice if r["json"]["owner_id"] == alice["id"] else bob, r["json"])
|
||||
for r in (ok_png, ok_jpg):
|
||||
ready(r)
|
||||
if ok_jpg:
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % ok_jpg["json"]["id"], actor=alice)
|
||||
check(d["bytes"] == JPEG and d["headers"].get_content_type() == "image/jpeg", "jpeg download mismatch")
|
||||
check(d["headers"].get("X-Content-Type-Options") == "nosniff", "nosniff missing")
|
||||
near = noise_png(MAX_BYTES)
|
||||
big = s.upload("PNG near 10 MiB limit (%d B)" % len(near), alice, chat, near, 202, filename="big.png")
|
||||
if big:
|
||||
check(big["json"]["sha256"] == hashlib.sha256(near).hexdigest(), "big sha mismatch")
|
||||
ready(big)
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % big["json"]["id"], actor=bob)
|
||||
check(hashlib.sha256(d["bytes"]).hexdigest() == big["json"]["sha256"], "big download mismatch")
|
||||
|
||||
# --- размер и пиксели ---
|
||||
s.upload("too large: 10 MiB + 1 B", alice, chat, near + b"\0" * (MAX_BYTES + 1 - len(near)), 413)
|
||||
s.upload("pixel bomb header 100000x100000", alice, chat, png(100000, 100000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("PNG 7000x6000 = 42 Mpx (> 40 Mpx)", alice, chat, png(7000, 6000, zlib.compress(b"\0" * 1000)), 413)
|
||||
s.upload("zlib bomb: 100x100 header, 50 MB inflated", alice, chat,
|
||||
png(100, 100, zlib.compress(b"\0" * 50_000_000, 9), color_type=0), 415)
|
||||
|
||||
# --- повреждённые изображения ---
|
||||
flipped = bytearray(PNG); flipped[5000] ^= 0xFF
|
||||
s.upload("corrupted PNG (byte flipped, bad CRC)", alice, chat, bytes(flipped), 415)
|
||||
s.upload("truncated PNG", alice, chat, PNG[:-4000], 415)
|
||||
s.upload("PNG without IEND", alice, chat, PNG[:-12], 415)
|
||||
s.upload("PNG with appended ZIP (polyglot)", alice, chat, PNG + b"PK\x03\x04" + os.urandom(64), 415)
|
||||
s.upload("truncated JPEG", alice, chat, JPEG[:len(JPEG) // 2], 415, ctype="image/jpeg")
|
||||
s.upload("JPEG header only", alice, chat, JPEG[:200], 415, ctype="image/jpeg")
|
||||
s.upload("empty body", alice, chat, b"", 415)
|
||||
|
||||
# --- подмена MIME ---
|
||||
s.upload("JPEG bytes declared image/png", alice, chat, JPEG, 415)
|
||||
s.upload("PNG bytes declared image/jpeg", alice, chat, PNG, 415, ctype="image/jpeg")
|
||||
s.upload("text declared image/png", alice, chat, b"<html><script>alert(1)</script></html>" * 4, 415)
|
||||
s.upload("GIF declared image/png", alice, chat, b"GIF89a" + os.urandom(200), 415)
|
||||
s.upload("PNG declared text/html", alice, chat, PNG, 415, ctype="text/html")
|
||||
s.upload("PNG declared image/svg+xml", alice, chat, PNG, 415, ctype="image/svg+xml")
|
||||
s.upload("multipart/form-data instead of raw", alice, chat, b"--x\r\n\r\n" + PNG + b"\r\n--x--", 415,
|
||||
ctype="multipart/form-data; boundary=x")
|
||||
|
||||
# --- опасные filename ---
|
||||
for label, query in (("../etc/passwd", "filename=" + quote("../passwd.png", safe="")),
|
||||
("slash", "filename=" + quote("a/b.png", safe="")),
|
||||
("backslash", "filename=" + quote("a\\b.png", safe="")),
|
||||
("NUL", "filename=a%00.png"),
|
||||
("newline", "filename=a%0A.png"),
|
||||
("bidi override U+202E", "filename=" + quote("gnp.exe", safe="")),
|
||||
("..", "filename=.."),
|
||||
("empty", "filename="),
|
||||
("whitespace only", "filename=%20%20"),
|
||||
("256 code points", "filename=" + quote("я" * 256, safe="")),
|
||||
("missing filename", ""),
|
||||
("filename twice", "filename=a.png&filename=b.png"),
|
||||
("invalid UTF-8", "filename=%FF%FE.png")):
|
||||
s.upload("filename: " + label, alice, chat, PNG, 400, raw_query=query)
|
||||
|
||||
# --- доступ и чужие объекты ---
|
||||
eve_att = s.upload("eve uploads to her own chat", eve, eve_chat, PNG, 202)
|
||||
s.upload("non-member uploads to alice chat", eve, chat, PNG, 404)
|
||||
s.case("upload without session", "POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 401,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
s.upload("upload to unknown chat", alice, {"id": str(uuid.uuid4())}, PNG, 404)
|
||||
if eve_att and ok_png:
|
||||
eid, aid = eve_att["json"]["id"], ok_png["json"]["id"]
|
||||
s.case("foreign attachment metadata", "GET", "/api/v1/attachments/" + eid, 404, actor=alice)
|
||||
s.case("foreign attachment content", "GET", "/api/v1/attachments/%s/content" % eid, 404, actor=alice)
|
||||
s.case("eve reads alice attachment", "GET", "/api/v1/attachments/%s/content" % aid, 404, actor=eve)
|
||||
key = lambda: {"Idempotency-Key": uuid.uuid4().hex} # noqa: E731
|
||||
s.case("message with foreign attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [eid]}, headers=key())
|
||||
s.case("message mixing own and foreign ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid, eid]}, headers=key())
|
||||
s.case("attachment of OTHER chat of the same user", "POST", "/api/v1/chats/%s/messages" % chat2["id"], 404,
|
||||
actor=alice, body={"text": "x", "attachment_ids": [aid]}, headers=key())
|
||||
s.case("unknown attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 404, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4())]}, headers=key())
|
||||
s.case("malformed attachment_id", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": ["not-a-uuid"]}, headers=key())
|
||||
s.case("duplicate attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [aid, aid]}, headers=key())
|
||||
s.case("11 attachment_ids", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, headers=key())
|
||||
s.case("attachment_ids not a list", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400, actor=alice,
|
||||
body={"text": "x", "attachment_ids": aid}, headers=key())
|
||||
s.case("empty text without attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 400,
|
||||
actor=alice, body={"text": " "}, headers=key())
|
||||
m = s.case("empty text with attachment (bob links alice's file)", "POST",
|
||||
"/api/v1/chats/%s/messages" % chat["id"], 201, actor=bob,
|
||||
body={"text": "", "attachment_ids": [aid]}, headers=key(), schema="Message")
|
||||
if m:
|
||||
check(m["json"]["attachment_ids"] == [aid], "attachment_ids lost")
|
||||
k = key()
|
||||
s.case("idempotent send with attachments", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"attachment_ids": [aid], "text": "повтор"}, headers=k, schema="Message")
|
||||
s.case("same key, same body (key order changed)", "POST", "/api/v1/chats/%s/messages" % chat["id"], 201,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": [aid]}, headers=k, schema="Message")
|
||||
s.case("same key, different attachment_ids -> 409", "POST", "/api/v1/chats/%s/messages" % chat["id"], 409,
|
||||
actor=alice, body={"text": "повтор", "attachment_ids": []}, headers=k)
|
||||
s.case("variant=thumbnail (ready, lab5)", "GET",
|
||||
"/api/v1/attachments/%s/content?variant=thumbnail" % aid, 200, actor=bob)
|
||||
s.case("variant=bogus", "GET", "/api/v1/attachments/%s/content?variant=bogus" % aid, 400, actor=bob)
|
||||
s.case("variant=original", "GET", "/api/v1/attachments/%s/content?variant=original" % aid, 200, actor=bob)
|
||||
s.case("malformed attachment id in path", "GET", "/api/v1/attachments/zzz", 400, actor=bob)
|
||||
s.case("unknown attachment id", "GET", "/api/v1/attachments/" + str(uuid.uuid4()), 404, actor=bob)
|
||||
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
server_errors = [r for r in results if r.get("status", 0) >= 500]
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-55s -> %s %s" % (
|
||||
r["case"], r.get("status", "-"), r.get("error_code") or r.get("error", "")))
|
||||
summary = {"cases": len(results), "failed": len(failed), "server_errors_5xx": len(server_errors),
|
||||
"pass": not failed and not server_errors}
|
||||
print(json.dumps(summary, ensure_ascii=False))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"summary": summary, "results": results}, ensure_ascii=False, indent=1))
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Права пользователей RabbitMQ (минимальные привилегии). Хост-оркестратор:
|
||||
|
||||
python3 student-tests/broker_permissions.py --output evidence/broker-permissions.json
|
||||
|
||||
Внутри контейнеров relay, worker и ops (каждый — со СВОИМ BROKER_URL_FILE) выполняется
|
||||
проба (--probe): publish в exchange attachments (с mandatory и неизвестным routing key —
|
||||
сообщение никуда не попадает, но право write проверяется), basic.get из рабочей очереди и
|
||||
из DLQ (право read), queue.declare (право configure). Ожидаемая матрица:
|
||||
relay — publish; worker — read рабочей очереди; ops — publish + read DLQ; configure — никто.
|
||||
Также: пользователя guest нет; порты брокера на хост не опубликованы.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
EXPECT = {
|
||||
"relay": {"publish": True, "get_work_queue": False, "get_dlq": False, "declare_queue": False},
|
||||
"worker": {"publish": False, "get_work_queue": True, "get_dlq": False, "declare_queue": False},
|
||||
"ops": {"publish": True, "get_work_queue": False, "get_dlq": True, "declare_queue": False},
|
||||
}
|
||||
|
||||
|
||||
def probe():
|
||||
sys.path.insert(0, "/app/src")
|
||||
import pika
|
||||
import common
|
||||
out = {}
|
||||
conn = pika.BlockingConnection(common.broker_parameters())
|
||||
|
||||
def attempt(name, fn):
|
||||
ch = conn.channel()
|
||||
try:
|
||||
fn(ch)
|
||||
out[name] = True
|
||||
except pika.exceptions.UnroutableError:
|
||||
out[name] = True # write разрешён, просто нет binding
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
out[name] = False if exc.reply_code == 403 else "error %d" % exc.reply_code
|
||||
finally:
|
||||
if ch.is_open:
|
||||
ch.close()
|
||||
|
||||
def publish(ch):
|
||||
ch.confirm_delivery()
|
||||
ch.basic_publish(common.EXCHANGE, "permission.check.unbound", b"{}", mandatory=True)
|
||||
|
||||
def get(queue):
|
||||
def fn(ch):
|
||||
m, _p, _b = ch.basic_get(queue, auto_ack=False)
|
||||
if m is not None:
|
||||
ch.basic_nack(m.delivery_tag, requeue=True)
|
||||
return fn
|
||||
|
||||
attempt("publish", publish)
|
||||
attempt("get_work_queue", get(common.QUEUE))
|
||||
attempt("get_dlq", get(common.DLQ))
|
||||
attempt("declare_queue", lambda ch: ch.queue_declare("evil-queue", durable=True))
|
||||
conn.close()
|
||||
print(json.dumps(out))
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--probe", action="store_true")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
if args.probe:
|
||||
return probe()
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
script = (root / "student-tests/broker_permissions.py").read_text()
|
||||
results, ok = {}, True
|
||||
runners = {"relay": ["docker", "compose", "exec", "-T", "relay", "python", "-", "--probe"],
|
||||
"worker": ["docker", "compose", "exec", "-T", "worker", "python", "-", "--probe"],
|
||||
"ops": ["docker", "compose", "--profile", "tools", "run", "--rm", "-T", "--entrypoint", "python",
|
||||
"ops", "-", "--probe"]}
|
||||
for user, cmd in runners.items():
|
||||
r = subprocess.run(cmd, input=script, capture_output=True, text=True, cwd=root, timeout=120)
|
||||
got = json.loads(r.stdout.strip().splitlines()[-1])
|
||||
results[user] = {"got": got, "expected": EXPECT[user], "pass": got == EXPECT[user]}
|
||||
ok &= got == EXPECT[user]
|
||||
print("%s %-6s %s" % ("PASS" if got == EXPECT[user] else "FAIL", user, got))
|
||||
users = subprocess.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_users"],
|
||||
capture_output=True, text=True, cwd=root).stdout.split()
|
||||
ports = subprocess.run(["docker", "compose", "port", "broker", "5672"], capture_output=True, text=True, cwd=root)
|
||||
results["guest_absent"] = "guest" not in users
|
||||
results["broker_port_published_to_host"] = bool(ports.stdout.strip())
|
||||
ok &= results["guest_absent"] and not results["broker_port_published_to_host"]
|
||||
print("guest absent:", results["guest_absent"], "| port 5672 on host:", results["broker_port_published_to_host"])
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(results, ensure_ascii=False, indent=1) + "\n")
|
||||
print("PASS" if ok else "FAIL")
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main() or 0)
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: ограниченная конкуренция/prefetch, очистка staging, память worker под всплеском.
|
||||
|
||||
python3 student-tests/burst.py --count 24 --output evidence/burst.json
|
||||
|
||||
N несжимаемых PNG 1500x1500 (~6.8 MB) загружаются 8 потоками. Во время обработки раз в
|
||||
секунду снимается память контейнеров worker (docker stats). По job_events считаются:
|
||||
максимальное число одновременно обрабатываемых заданий (claimed..ready), задержка очереди
|
||||
(enqueued -> claimed) и время до ready. Ожидание: одновременно <= WORKER_REPLICAS x
|
||||
WORKER_CONCURRENCY (prefetch=1 на потребителя), staging всех заданий удалён.
|
||||
Иллюстрация на одной машине, не статистика.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import json
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from lab5lib import Client, Log, check, compose, noise_png_fast, queues, sql, upload, wait_status
|
||||
|
||||
|
||||
def ts(text):
|
||||
return dt.datetime.fromisoformat(text.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
def mem_sampler(stop, samples):
|
||||
while not stop.is_set():
|
||||
ids = compose("ps", "-q", "worker").stdout.split()
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}} {{.CPUPerc}}"]
|
||||
+ ids, capture_output=True, text=True).stdout
|
||||
for line in out.splitlines():
|
||||
name, used, _slash, limit, cpu = line.split()[:5]
|
||||
samples.append({"name": name, "used": used, "limit": limit, "cpu": cpu})
|
||||
stop.wait(1)
|
||||
|
||||
|
||||
def mib(text):
|
||||
num = float("".join(ch for ch in text if ch.isdigit() or ch == "."))
|
||||
return num / 1024 if text.endswith("KiB") else num * 1024 if text.endswith("GiB") else num
|
||||
|
||||
|
||||
def pct(values, p):
|
||||
values = sorted(values)
|
||||
return round(values[min(len(values) - 1, int(round(p / 100 * (len(values) - 1))))], 3)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--count", type=int, default=24)
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("burst of uploads: bounded worker concurrency")
|
||||
c = Client(args.base_url, timeout=60)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
consumers = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "-p", "messenger", "list_consumers",
|
||||
"queue_name", "prefetch_count", "ack_required", "--formatter", "json").stdout
|
||||
consumers = json.loads(consumers)
|
||||
log.step("consumers", count=len(consumers), prefetch=sorted({x["prefetch_count"] for x in consumers}))
|
||||
images = [noise_png_fast(1500, 1500) for _ in range(4)]
|
||||
log.step("generated images", bytes=[len(x) for x in images])
|
||||
stop = threading.Event()
|
||||
samples = []
|
||||
sampler = threading.Thread(target=mem_sampler, args=(stop, samples), daemon=True)
|
||||
sampler.start()
|
||||
t0 = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(8) as pool:
|
||||
atts = list(pool.map(lambda i: upload(c, alice, chat, images[i % 4], "burst-%d.png" % i),
|
||||
range(args.count)))
|
||||
t_up = time.monotonic() - t0
|
||||
q = queues()["attachments.process.v1"]
|
||||
log.step("all uploads accepted (202)", count=len(atts), seconds=round(t_up, 2), queue_right_after=q)
|
||||
for a in atts:
|
||||
st = wait_status(c, bob, a["id"], {"ready", "failed"}, timeout=180, interval=1)
|
||||
check(st["status"] == "ready", "burst job failed")
|
||||
total = time.monotonic() - t0
|
||||
stop.set()
|
||||
sampler.join()
|
||||
ids = ",".join("'%s'" % a["id"] for a in atts)
|
||||
rows = sql("""SELECT j.attachment_id, e.event, to_char(e.at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')
|
||||
FROM job_events e JOIN jobs j ON j.id = e.job_id
|
||||
WHERE j.attachment_id IN (%s) AND e.event IN ('enqueued','claimed','ready') ORDER BY e.id""" % ids)
|
||||
per = {}
|
||||
for att_id, ev, at in rows:
|
||||
per.setdefault(att_id, {})[ev] = ts(at)
|
||||
intervals = [(v["claimed"], v["ready"]) for v in per.values()]
|
||||
points = sorted([(a, 1) for a, _ in intervals] + [(b, -1) for _, b in intervals], key=lambda x: (x[0], x[1]))
|
||||
cur = peak = 0
|
||||
for _, d in points:
|
||||
cur += d
|
||||
peak = max(peak, cur)
|
||||
lag = [(v["claimed"] - v["enqueued"]).total_seconds() for v in per.values()]
|
||||
to_ready = [(v["ready"] - v["enqueued"]).total_seconds() for v in per.values()]
|
||||
work = [(v["ready"] - v["claimed"]).total_seconds() for v in per.values()]
|
||||
staging_left = sql("SELECT count(*) FROM attachments WHERE id IN (%s) AND staging_key IS NOT NULL" % ids)[0][0]
|
||||
limit = len(consumers)
|
||||
by_name = {}
|
||||
for s in samples:
|
||||
by_name[s["name"]] = max(by_name.get(s["name"], 0), mib(s["used"]))
|
||||
result = {
|
||||
"count": args.count, "image_bytes": len(images[0]), "upload_seconds": round(t_up, 2),
|
||||
"total_seconds_to_all_ready": round(total, 2),
|
||||
"throughput_jobs_per_s": round(args.count / total, 2),
|
||||
"consumers": limit, "prefetch_per_consumer": sorted({x["prefetch_count"] for x in consumers}),
|
||||
"max_concurrent_processing": peak,
|
||||
"queue_lag_s": {"p50": pct(lag, 50), "p95": pct(lag, 95), "max": round(max(lag), 3)},
|
||||
"enqueued_to_ready_s": {"p50": pct(to_ready, 50), "p95": pct(to_ready, 95), "max": round(max(to_ready), 3)},
|
||||
"processing_s": {"p50": pct(work, 50), "max": round(max(work), 3), "mean": round(statistics.mean(work), 3)},
|
||||
"worker_peak_mem_mib": {k: round(v, 1) for k, v in by_name.items()},
|
||||
"worker_mem_limit": samples[0]["limit"] if samples else None,
|
||||
"staging_left": int(staging_left),
|
||||
}
|
||||
check(peak <= limit, "concurrency exceeded consumers x prefetch")
|
||||
check(result["staging_left"] == 0, "staging not cleaned")
|
||||
log.step("result", **result)
|
||||
log.save(args.output, result=result)
|
||||
print("PASS: %d jobs, max concurrent %d <= %d consumers" % (args.count, peak, limit))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказы между записью в S3 и PostgreSQL и очистка janitor (уровень 4).
|
||||
|
||||
Требует API с FAULT_INJECTION=1 (учебный хук, по умолчанию выключен):
|
||||
FAULT_INJECTION=1 docker compose --env-file .env up -d --no-deps --wait api
|
||||
python3 student-tests/consistency_faults.py --output evidence/consistency-faults.json
|
||||
docker compose --env-file .env up -d --no-deps --wait api # вернуть FAULT_INJECTION=0
|
||||
|
||||
Сценарии (каждый — реальный HTTP upload через LB):
|
||||
db-fail-after-s3-put PUT прошёл, «COMMIT» ready упал -> 503; компенсация удаляет объект
|
||||
и pending-строку -> ничего не остаётся;
|
||||
crash-after-s3-put процесс API умирает (os._exit) после PUT -> pending + объект;
|
||||
crash-after-pending процесс умирает до PUT -> pending без объекта;
|
||||
обрыв клиента Content-Length 5 MiB, отправлен 1 MiB, сокет закрыт -> ничего;
|
||||
orphan pending-строку удаляем вручную -> объект без строки;
|
||||
missing объект ready-вложения удаляем в S3 -> только отчёт, download = 503.
|
||||
Затем janitor: dry-run и боевой проход с grace 3600 (свежее не трогает), ожидание
|
||||
grace-seconds, dry-run -> боевой -> повторный (идемпотентность). Контрольное ready-вложение
|
||||
должно остаться доступным побайтно.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
log = []
|
||||
|
||||
|
||||
def sh(*cmd, timeout=120):
|
||||
r = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, timeout=timeout)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit("command failed: %s\n%s" % (" ".join(cmd[:4]), r.stderr[-500:]))
|
||||
return r.stdout
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return sh("docker", "compose", "exec", "-T", "db", "sh", "-c",
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tAc "$0"', sql).strip()
|
||||
|
||||
|
||||
def janitor(grace, dry_run):
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "janitor", "python", "/app/src/janitor.py",
|
||||
"--once", "--grace-seconds", str(grace)] + (["--dry-run"] if dry_run else [])
|
||||
out = sh(*cmd)
|
||||
report = json.loads([line for line in out.splitlines() if line.startswith("{")][-1])
|
||||
keep = ("dry_run", "grace_seconds", "rows_by_status", "objects_total", "abandoned_pending",
|
||||
"orphan_objects", "missing_objects", "deleted_objects", "deleted_rows", "errors", "duration_ms")
|
||||
return {k: report.get(k) for k in keep}
|
||||
|
||||
|
||||
def step(name, **data):
|
||||
entry = dict(step=name, t=round(time.time(), 1), **data)
|
||||
log.append(entry)
|
||||
print(json.dumps(entry, ensure_ascii=False), flush=True)
|
||||
return entry
|
||||
|
||||
|
||||
def wait_api_healthy():
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
states = sh("docker", "compose", "ps", "-a", "--format", "{{.Health}}", "api").split()
|
||||
if states and all(s == "healthy" for s in states):
|
||||
time.sleep(3) # HAProxy rise
|
||||
return
|
||||
time.sleep(1)
|
||||
raise SystemExit("api did not become healthy")
|
||||
|
||||
|
||||
def upload(c, actor, chat, fault=None, expected=201):
|
||||
h = {"Content-Type": "image/png"}
|
||||
if fault:
|
||||
h["X-Fault-Inject"] = fault
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=f.png" % chat["id"], expected,
|
||||
actor=actor, raw=PNG, headers=h, schema="Attachment" if expected == 201 else None)
|
||||
return r["status"], r["json"]
|
||||
except Exception as exc: # обрыв соединения при crash-* тоже допустимый исход
|
||||
return type(exc).__name__, str(exc)[:120]
|
||||
|
||||
|
||||
def interrupted_upload(base, token, chat_id):
|
||||
host, port = base.split("//")[1].split(":")
|
||||
s = socket.create_connection((host, int(port)), timeout=10)
|
||||
s.sendall(("POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: %d\r\n\r\n"
|
||||
% (chat_id, host, token, 5 * 1024 * 1024)).encode())
|
||||
s.sendall(PNG[:8] + b"\0" * (1024 * 1024 - 8))
|
||||
s.close() # клиент «пропал» на середине
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--grace-seconds", type=int, default=20)
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
env = sh("docker", "compose", "exec", "-T", "api", "printenv", "FAULT_INJECTION").strip()
|
||||
check(env == "1", "start api with FAULT_INJECTION=1 first (see docstring)")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
started = psql("SELECT now()")
|
||||
base = janitor(3600, True)
|
||||
step("baseline janitor dry-run", report=base)
|
||||
|
||||
_, control = upload(c, alice, chat)
|
||||
_, victim = upload(c, alice, chat)
|
||||
step("control + victim uploaded (ready)", control=control["id"], victim=victim["id"])
|
||||
|
||||
st, body = upload(c, alice, chat, "db-fail-after-s3-put", expected=503)
|
||||
after_comp = janitor(3600, True)
|
||||
step("db-fail-after-s3-put -> compensation", status=st, report=after_comp,
|
||||
leftover_pending=after_comp["rows_by_status"].get("pending", 0) - base["rows_by_status"].get("pending", 0),
|
||||
leftover_objects=after_comp["objects_total"] - base["objects_total"] - 2)
|
||||
|
||||
for fault in ("crash-after-s3-put", "crash-after-s3-put", "crash-after-pending"):
|
||||
st, body = upload(c, alice, chat, fault, expected=[502, 503])
|
||||
step(fault, client_saw=st)
|
||||
wait_api_healthy()
|
||||
|
||||
interrupted_upload(args.base_url, alice["token"], chat["id"])
|
||||
time.sleep(2)
|
||||
step("client aborted upload at 1 of 5 MiB", report=janitor(3600, True))
|
||||
|
||||
pending = psql("SELECT id || ' ' || (object_key IS NOT NULL) FROM attachments WHERE status='pending' "
|
||||
"AND created_at >= '%s' ORDER BY created_at" % started).splitlines()
|
||||
step("pending rows left by crashes", pending=len(pending))
|
||||
check(len(pending) == 3, "expected 3 pending rows from crashes")
|
||||
orphan_id = pending[0].split()[0]
|
||||
psql("DELETE FROM attachments WHERE id = '%s'" % orphan_id)
|
||||
step("orphan injected: pending row deleted, object kept", row=orphan_id)
|
||||
victim_key = psql("SELECT object_key FROM attachments WHERE id = '%s'" % victim["id"])
|
||||
sh("docker", "compose", "--profile", "tools", "run", "--rm", "--entrypoint", "python", "s3-check", "-c",
|
||||
"import sys; sys.argv=['x']; exec(open('/app/student-tests/s3_private_check.py').read().split('results = []')[0]);"
|
||||
"client('api').remove_object(BUCKET, %r)" % victim_key)
|
||||
dl = c.call("GET", "/api/v1/attachments/%s/content" % victim["id"], 503, actor=bob)
|
||||
step("missing injected: victim object deleted in S3", download_status=dl["status"])
|
||||
|
||||
fresh_dry = janitor(3600, True)
|
||||
fresh_run = janitor(3600, False)
|
||||
step("janitor grace=3600 (all fresh): dry-run", report=fresh_dry)
|
||||
step("janitor grace=3600 (all fresh): real run deletes nothing", report=fresh_run)
|
||||
check(fresh_run["deleted_objects"] == 0 and fresh_run["deleted_rows"] == 0, "fresh data deleted")
|
||||
|
||||
time.sleep(args.grace_seconds + 2)
|
||||
dry = janitor(args.grace_seconds, True)
|
||||
step("after grace: dry-run", report=dry)
|
||||
real = janitor(args.grace_seconds, False)
|
||||
step("after grace: real run", report=real)
|
||||
again = janitor(args.grace_seconds, False)
|
||||
step("after grace: repeated run (idempotent)", report=again)
|
||||
d = c.call("GET", "/api/v1/attachments/%s/content" % control["id"], actor=bob)
|
||||
control_ok = hashlib.sha256(d["bytes"]).hexdigest() == control["sha256"]
|
||||
still = psql("SELECT count(*) FROM attachments WHERE status='pending' AND created_at >= '%s'" % started)
|
||||
step("control attachment still intact", sha256_ok=control_ok, pending_left=int(still))
|
||||
|
||||
ok = (log[2]["leftover_pending"] == 0 and log[2]["leftover_objects"] == 0
|
||||
and dry["abandoned_pending"] >= 2 and dry["orphan_objects"] >= 1 and dry["missing_objects"] >= 1
|
||||
and dry["deleted_objects"] == 0
|
||||
and real["deleted_rows"] >= 2 and again["abandoned_pending"] == 0 and again["orphan_objects"] == 0
|
||||
and again["deleted_objects"] == 0 and again["missing_objects"] >= 1
|
||||
and control_ok and int(still) == 0)
|
||||
print(json.dumps({"pass": ok}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"pass": ok, "steps": log}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка диапазона дат cursor: некорректная дата должна давать 400, а не 500."""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, ca_file=args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
checks = 0
|
||||
for kind, scope, path in (
|
||||
("messages", chat["id"], "/api/v1/chats/" + chat["id"] + "/messages"),
|
||||
("chats", alice["id"], "/api/v1/chats"),
|
||||
):
|
||||
for timestamp, expected in ((-10**17, 400), (-62135596800000001, 400), (0, 200)):
|
||||
payload = {"k": kind, "s": scope, "t": timestamp, "i": str(uuid.uuid4())}
|
||||
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
client.call("GET", path + "?cursor=" + quote(cursor, safe=""), expected, actor=alice)
|
||||
checks += 1
|
||||
print("PASS: %d cursor date boundary checks; invalid dates return 400." % checks)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказ/замена API-реплики ПОД НАГРУЗКОЙ: RPS, ошибки, время обнаружения и восстановления (lab3, уровень 4).
|
||||
|
||||
Что делает:
|
||||
* CONCURRENCY потоков в closed-loop шлют смесь запросов через LB: POST сообщения
|
||||
(с Idempotency-Key) и GET истории (limit=20) в пропорции 1:1;
|
||||
* после неуспешного/неопределённого POST поток повторяет ТОТ ЖЕ ключ и тело (как
|
||||
требует контракт), поэтому подтверждённых дублей быть не должно;
|
||||
* на секунде --action-at запускается --action (например, docker stop/kill контейнера
|
||||
или scripts/rolling-update.sh), его stdout/stderr пишутся в отдельный лог;
|
||||
* параллельно каждые 200 мс опрашивается CSV статистики HAProxy: фиксируются моменты
|
||||
UP -> DOWN / DOWN -> UP серверов backend (время обнаружения отказа LB);
|
||||
* в конце читается вся история чата (тем же токеном) и проверяется: все подтверждённые
|
||||
сообщения на месте, дублей нет.
|
||||
|
||||
Метрики (все времена — от старта action):
|
||||
errors_total / error_rate — неуспешные попытки (HTTP != ожидаемого, timeout, разрыв);
|
||||
error_window_s — от первой до последней ошибки после старта action;
|
||||
recovery_s — конец окна ошибок (дальше все запросы успешны), 0 если ошибок нет;
|
||||
post_action_ok_rps/capacity_ratio — успешный RPS после действия и его доля от базового;
|
||||
lb_down_detected_s — когда HAProxy пометил сервер DOWN;
|
||||
target_last_seen_s — последний ответ от остановленной реплики.
|
||||
|
||||
Ограничения: closed-loop генератор (coordinated omission), клиент на том же хосте, что и
|
||||
стенд; цифры RPS сравнимы только между прогонами этого же скрипта на этом же ноутбуке.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
TIMEOUT = 2.0
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
s = sorted(values)
|
||||
return round(s[min(len(s) - 1, int(round(p / 100 * (len(s) - 1))))] * 1000, 1)
|
||||
|
||||
|
||||
class Bench:
|
||||
def __init__(self, a):
|
||||
self.a = a
|
||||
self.base = a.base_url.rstrip("/")
|
||||
self.lock = threading.Lock()
|
||||
self.t0 = None
|
||||
self.stop = threading.Event()
|
||||
self.per_sec = defaultdict(lambda: {"ok": 0, "err": 0, "inst": Counter(), "ver": Counter()})
|
||||
self.errors = [] # (t, kind)
|
||||
self.lat = [] # успешные задержки, с
|
||||
self.confirmed = {} # message id -> text
|
||||
self.retried_posts = 0
|
||||
self.lb_events = []
|
||||
self.inst_last_seen = {}
|
||||
|
||||
def now(self):
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def record(self, ok, dt, inst=None, ver=None, kind=None):
|
||||
t = self.now()
|
||||
with self.lock:
|
||||
b = self.per_sec[int(t)]
|
||||
if ok:
|
||||
b["ok"] += 1
|
||||
self.lat.append(dt)
|
||||
if inst:
|
||||
b["inst"][inst] += 1
|
||||
self.inst_last_seen[inst] = t
|
||||
if ver:
|
||||
b["ver"][ver] += 1
|
||||
else:
|
||||
b["err"] += 1
|
||||
self.errors.append((round(t, 3), kind))
|
||||
|
||||
def request(self, method, path, body=None, headers=None, expected=200):
|
||||
h = {"Authorization": "Bearer " + self.token}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(self.base + path, data=data, method=method, headers=h)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
payload = json.loads(r.read())
|
||||
ok = r.status == expected
|
||||
self.record(ok, time.monotonic() - start, r.headers.get("X-Instance-Id"),
|
||||
r.headers.get("X-App-Version"), None if ok else "http_%d" % r.status)
|
||||
return payload if ok else None
|
||||
except urllib.error.HTTPError as e:
|
||||
self.record(False, 0, kind="http_%d" % e.code)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.record(False, 0, kind=type(e).__name__)
|
||||
return None
|
||||
|
||||
def worker(self, n):
|
||||
chat_path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
key = text = None
|
||||
i = 0
|
||||
while not self.stop.is_set():
|
||||
i += 1
|
||||
if i % 2:
|
||||
if key is None: # новый логический запрос; после ошибки ключ НЕ меняется
|
||||
key = "bench-%d-%s" % (n, uuid.uuid4().hex)
|
||||
text = "Нагрузка " + key
|
||||
else:
|
||||
with self.lock:
|
||||
self.retried_posts += 1
|
||||
msg = self.request("POST", chat_path, {"text": text}, {"Idempotency-Key": key}, 201)
|
||||
if msg is not None:
|
||||
with self.lock:
|
||||
self.confirmed[msg["id"]] = msg["text"]
|
||||
key = None
|
||||
else:
|
||||
self.request("GET", chat_path + "?limit=20")
|
||||
|
||||
def poll_lb(self):
|
||||
prev = {}
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
with urllib.request.urlopen(self.a.stats_url, timeout=1) as r:
|
||||
rows = list(csv.reader(io.StringIO(r.read().decode().lstrip("# "))))
|
||||
head = rows[0]
|
||||
ix = {k: head.index(k) for k in ("pxname", "svname", "status", "addr")}
|
||||
for row in rows[1:]:
|
||||
if len(row) <= ix["addr"] or row[ix["pxname"]] != "be_api" or row[ix["svname"]] == "BACKEND":
|
||||
continue
|
||||
sv, st, addr = row[ix["svname"]], row[ix["status"]].split(" ")[0], row[ix["addr"]]
|
||||
if sv in prev and prev[sv] != (st, addr):
|
||||
self.lb_events.append({"t": round(self.now(), 2), "server": sv, "addr": addr,
|
||||
"from": prev[sv][0], "to": st})
|
||||
prev[sv] = (st, addr)
|
||||
except Exception: # noqa: BLE001 — статистика вспомогательная
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
def history(self):
|
||||
c, path, items = self.client, "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100", []
|
||||
while True:
|
||||
page = c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
if page["next_cursor"] is None:
|
||||
return items
|
||||
path = "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
def run(self):
|
||||
a = self.a
|
||||
self.client = Client(self.base, timeout=10)
|
||||
self.alice, _bob, _eve, self.chat = self.client.bootstrap()
|
||||
self.token = self.alice["token"]
|
||||
self.t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(a.concurrency)]
|
||||
threads.append(threading.Thread(target=self.poll_lb, daemon=True))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.action_at)
|
||||
action = {"command": a.action, "started_s": round(self.now(), 3)}
|
||||
log = open(a.action_log, "w", encoding="utf-8") if a.action_log else subprocess.DEVNULL
|
||||
proc = subprocess.Popen(shlex.split(a.action), stdout=log, stderr=subprocess.STDOUT)
|
||||
rc = proc.wait(timeout=a.duration)
|
||||
action.update(finished_s=round(self.now(), 3), exit_code=rc)
|
||||
remaining = a.duration - self.now()
|
||||
if remaining > 0:
|
||||
time.sleep(remaining)
|
||||
self.stop.set()
|
||||
for t in threads:
|
||||
t.join(timeout=TIMEOUT + 1)
|
||||
return self.summarize(action)
|
||||
|
||||
def summarize(self, action):
|
||||
a, t_act = self.a, action["started_s"]
|
||||
secs = sorted(self.per_sec)
|
||||
base = [self.per_sec[s]["ok"] for s in secs if 1 <= s < int(t_act)] # 1-я секунда — прогрев
|
||||
baseline = sum(base) / len(base) if base else 0
|
||||
after = [(round(t - t_act, 3), k) for t, k in self.errors if t >= t_act]
|
||||
# Восстановление = конец окна ошибок: после этого момента все запросы до конца
|
||||
# прогона успешны. Если ошибок не было — 0. Мощность после отказа меряем отдельно:
|
||||
# при меньшем числе реплик RPS законно ниже (лимиты CPU на реплику).
|
||||
recovery = after[-1][0] if after else 0.0
|
||||
tail_secs = [s for s in secs if int(action.get("finished_s", t_act)) + 2 <= s < a.duration - 1]
|
||||
post = [self.per_sec[s]["ok"] for s in tail_secs]
|
||||
post_rps = sum(post) / len(post) if post else 0
|
||||
writes_after = any(self.per_sec[s]["ok"] > 0 for s in tail_secs)
|
||||
target = a.target_instance
|
||||
hist = self.history()
|
||||
ids = [m["id"] for m in hist]
|
||||
texts = [m["text"] for m in hist]
|
||||
lost = [i for i in self.confirmed if i not in set(ids)]
|
||||
timeline = [{"t": s, "ok": self.per_sec[s]["ok"], "err": self.per_sec[s]["err"],
|
||||
"instances": dict(self.per_sec[s]["inst"]), "versions": dict(self.per_sec[s]["ver"])}
|
||||
for s in secs]
|
||||
total_ok = sum(b["ok"] for b in self.per_sec.values())
|
||||
total_err = len(self.errors)
|
||||
summary = {
|
||||
"label": a.label,
|
||||
"concurrency": a.concurrency, "duration_s": a.duration, "request_timeout_s": TIMEOUT,
|
||||
"action": action,
|
||||
"baseline_ok_rps": round(baseline, 1),
|
||||
"overall_ok_rps": round(total_ok / a.duration, 1),
|
||||
"requests_ok": total_ok, "errors_total": total_err,
|
||||
"error_rate": round(total_err / max(1, total_ok + total_err), 5),
|
||||
"errors_by_kind": dict(Counter(k for _, k in self.errors)),
|
||||
"error_window_s": [after[0][0], after[-1][0]] if after else None,
|
||||
"recovery_s": recovery,
|
||||
"post_action_ok_rps": round(post_rps, 1),
|
||||
"capacity_ratio": round(post_rps / baseline, 2) if baseline else None,
|
||||
"latency_ok_ms": {"p50": percentile(self.lat, 50), "p95": percentile(self.lat, 95),
|
||||
"p99": percentile(self.lat, 99)},
|
||||
"target_instance": target,
|
||||
"target_last_seen_s": (round(self.inst_last_seen[target] - t_act, 3)
|
||||
if target in self.inst_last_seen else None),
|
||||
"lb_events": [dict(e, t=round(e["t"] - t_act, 2)) for e in self.lb_events],
|
||||
"posts_retried_same_key": self.retried_posts,
|
||||
"confirmed_messages": len(self.confirmed),
|
||||
"history_messages": len(hist), "lost_confirmed": len(lost),
|
||||
"duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"timeline": timeline,
|
||||
}
|
||||
summary["pass"] = (summary["lost_confirmed"] == 0 and summary["duplicate_ids"] == 0
|
||||
and summary["duplicate_texts"] == 0 and action["exit_code"] == 0
|
||||
and writes_after and recovery <= 10)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Отказ/замена реплики под нагрузкой")
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--stats-url", default="http://127.0.0.1:8404/stats;csv")
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--duration", type=float, default=40)
|
||||
p.add_argument("--action-at", type=float, default=10)
|
||||
p.add_argument("--action", required=True, help="команда без shell, например 'docker stop -t 20 <id>'")
|
||||
p.add_argument("--action-log")
|
||||
p.add_argument("--target-instance", help="X-Instance-Id реплики, которую останавливает action")
|
||||
p.add_argument("--label", default="")
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
s = Bench(a).run()
|
||||
brief = {k: v for k, v in s.items() if k != "timeline"}
|
||||
print(json.dumps(brief, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(s, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if s["pass"] else "FAIL")
|
||||
return 0 if s["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4).
|
||||
|
||||
Сценарий на каждый раунд:
|
||||
A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело.
|
||||
Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик,
|
||||
в истории ровно одно сообщение с этим текстом.
|
||||
B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно
|
||||
тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет.
|
||||
|
||||
Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их
|
||||
по репликам. Токены только в памяти; синтетические пользователи создаются заново.
|
||||
|
||||
python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата)
|
||||
|
||||
|
||||
def post(base, token, chat_id, key, text, barrier, out, idx):
|
||||
data = json.dumps({"text": text}).encode()
|
||||
req = urllib.request.Request(
|
||||
base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json",
|
||||
"Idempotency-Key": key, "Connection": "close"})
|
||||
barrier.wait()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text)
|
||||
except urllib.error.HTTPError as e:
|
||||
out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text)
|
||||
except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку
|
||||
out[idx] = (0, repr(e), None, text)
|
||||
|
||||
|
||||
def burst(base, token, chat_id, key, texts):
|
||||
barrier = threading.Barrier(len(texts))
|
||||
out = [None] * len(texts)
|
||||
threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i))
|
||||
for i, t in enumerate(texts)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return out
|
||||
|
||||
|
||||
def history_texts(c, actor, chat):
|
||||
from urllib.parse import quote
|
||||
texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
while True:
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
if page["next_cursor"] is None:
|
||||
return texts
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--rounds", type=int, default=20)
|
||||
p.add_argument("--parallel", type=int, default=16)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
c = Client(base)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
token = alice["token"]
|
||||
problems, instances = [], Counter()
|
||||
stats = {"same_body": Counter(), "conflicting_body": Counter()}
|
||||
|
||||
for rnd in range(a.rounds):
|
||||
# A) одинаковое тело
|
||||
key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex
|
||||
res = burst(base, token, chat["id"], key, [text] * a.parallel)
|
||||
stats["same_body"].update(str(r[0]) for r in res)
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
seen = {r[2] for r in res if r[2]}
|
||||
instances.update(r[2] for r in res if r[2])
|
||||
if any(r[0] != 201 for r in res) or len(ids) != 1:
|
||||
problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids)))
|
||||
if len(seen) < 2:
|
||||
problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen)))
|
||||
|
||||
# B) тот же ключ, два разных тела вперемешку
|
||||
key = "mixed-" + uuid.uuid4().hex
|
||||
t1, t2 = "Тело A " + key, "Тело B " + key
|
||||
res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2))
|
||||
stats["conflicting_body"].update(str(r[0]) for r in res)
|
||||
winners = {r[3] for r in res if r[0] == 201}
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
bad = [r[0] for r in res if r[0] not in (201, 409)]
|
||||
losers_ok = all(r[0] == 409 for r in res if r[3] not in winners)
|
||||
if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok:
|
||||
problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad))
|
||||
|
||||
texts = history_texts(c, alice, chat)
|
||||
dupes = [t for t, n in Counter(texts).items() if n > 1]
|
||||
if dupes:
|
||||
problems.append("duplicated messages in history: %d" % len(dupes))
|
||||
summary = {
|
||||
"rounds": a.rounds, "parallel_per_burst": a.parallel,
|
||||
"requests_total": a.rounds * a.parallel * 2,
|
||||
"status_counts": {k: dict(v) for k, v in stats.items()},
|
||||
"replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()),
|
||||
"messages_in_history": len(texts), "expected_messages": a.rounds * 2,
|
||||
"duplicates": len(dupes), "problems": problems,
|
||||
}
|
||||
if len(texts) != a.rounds * 2:
|
||||
problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2))
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if not problems else "FAIL")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,175 @@
|
||||
"""Общие помощники проверок lab5 (запускаются на хосте, управляют стендом через docker compose).
|
||||
|
||||
Токены сессий живут только в памяти процесса и не печатаются. В evidence пишутся ID,
|
||||
статусы, времена и события заданий — без секретов и содержимого файлов.
|
||||
"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402,F401
|
||||
|
||||
SAMPLE_PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def now():
|
||||
return dt.datetime.now(dt.timezone.utc).strftime("%H:%M:%S.%f")[:-3]
|
||||
|
||||
|
||||
class Log:
|
||||
def __init__(self, name):
|
||||
self.name = name
|
||||
self.steps = []
|
||||
self.started = time.monotonic()
|
||||
|
||||
def step(self, text, **data):
|
||||
item = {"t": round(time.monotonic() - self.started, 2), "utc": now(), "step": text}
|
||||
item.update(data)
|
||||
self.steps.append(item)
|
||||
print("[%7.2fs] %s %s" % (item["t"], text, json.dumps(data, ensure_ascii=False) if data else ""), flush=True)
|
||||
|
||||
def save(self, path, **extra):
|
||||
if not path:
|
||||
return
|
||||
out = {"scenario": self.name, "date_utc": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"),
|
||||
"steps": self.steps}
|
||||
out.update(extra)
|
||||
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(path).write_text(json.dumps(out, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def compose(*args, env=None, timeout=300, ok=True):
|
||||
full_env = dict(os.environ)
|
||||
full_env.update(env or {})
|
||||
proc = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True,
|
||||
env=full_env, timeout=timeout)
|
||||
if ok and proc.returncode != 0:
|
||||
raise Failure("docker compose %s failed: %s" % (" ".join(args[:3]), proc.stderr.strip()[-400:]))
|
||||
return proc
|
||||
|
||||
|
||||
def recreate(service, env=None):
|
||||
"""Пересоздать сервис с переопределёнными переменными (shell env важнее .env)."""
|
||||
compose("up", "-d", "--no-deps", "--force-recreate", "--wait", service, env=env, timeout=400)
|
||||
|
||||
|
||||
def sql(query):
|
||||
proc = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "db", "sh", "-c",
|
||||
'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -tA -F "|" -v ON_ERROR_STOP=1'],
|
||||
cwd=ROOT, input=query, capture_output=True, text=True, timeout=60)
|
||||
if proc.returncode != 0:
|
||||
raise Failure("psql failed: " + proc.stderr.strip()[-300:])
|
||||
return [line.split("|") for line in proc.stdout.strip().splitlines() if line]
|
||||
|
||||
|
||||
def ops(*args, ok=True):
|
||||
proc = compose("--profile", "tools", "run", "--rm", "-T", "ops", *args, ok=False, timeout=120)
|
||||
if ok and proc.returncode not in (0, 3):
|
||||
raise Failure("ops %s failed: %s" % (args[0], proc.stderr.strip()[-400:]))
|
||||
try:
|
||||
return json.loads(proc.stdout)
|
||||
except ValueError:
|
||||
raise Failure("ops output is not JSON: " + proc.stdout[-300:] + proc.stderr[-300:])
|
||||
|
||||
|
||||
def queues():
|
||||
proc = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "-p", "messenger", "list_queues", "name",
|
||||
"messages", "messages_ready", "messages_unacknowledged", "consumers", "--formatter", "json")
|
||||
return {q["name"]: {k: q[k] for k in ("messages", "messages_ready", "messages_unacknowledged", "consumers")}
|
||||
for q in json.loads(proc.stdout)}
|
||||
|
||||
|
||||
def container_ids(service, running_only=True):
|
||||
args = ["ps", "-q"] + (["--status", "running"] if running_only else []) + [service]
|
||||
return [x for x in compose(*args).stdout.split() if x]
|
||||
|
||||
|
||||
def upload(c, actor, chat, data, filename="photo.png", ctype="image/png", expected=202):
|
||||
return c.call("POST", "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], filename), expected,
|
||||
actor=actor, raw=data, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 202 else None)["json"]
|
||||
|
||||
|
||||
def get_att(c, actor, att_id):
|
||||
return c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, statuses, timeout=90, interval=0.3):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
att = get_att(c, actor, att_id)
|
||||
if att["status"] in statuses:
|
||||
return att
|
||||
time.sleep(interval)
|
||||
raise Failure("attachment %s did not reach %s in %ss (last %s)" % (att_id, statuses, timeout, att["status"]))
|
||||
|
||||
|
||||
def wait_until(fn, timeout, interval=0.5, what="condition"):
|
||||
deadline = time.monotonic() + timeout
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
last = fn()
|
||||
if last:
|
||||
return last
|
||||
time.sleep(interval)
|
||||
raise Failure("timeout waiting for " + what)
|
||||
|
||||
|
||||
def events(info):
|
||||
return [e["event"] for e in info["events"]]
|
||||
|
||||
|
||||
def invariants(info):
|
||||
"""Ключ эффекта: ровно 3 варианта и 4 конечных объекта на (attachment, v1), staging убран."""
|
||||
names = sorted(v["name"] for v in info["variants"])
|
||||
finals = [o[0] for o in info["s3_final_objects"]]
|
||||
return {
|
||||
"variants": names,
|
||||
"variants_ok": names == ["crop", "optimized", "thumbnail"],
|
||||
"final_objects": len(finals),
|
||||
"final_objects_ok": len(finals) == 4,
|
||||
"staging_left": info["attachment"]["staging_key"] is not None,
|
||||
"job_status": info["jobs"][0]["status"],
|
||||
"attempt": info["jobs"][0]["attempt"],
|
||||
}
|
||||
|
||||
|
||||
def png(width, height, rgba=False, noise=False, color=(40, 120, 200), seed=1):
|
||||
"""PNG стандартной библиотекой: шум (несжимаемый) или заливка."""
|
||||
channels = 4 if rgba else 3
|
||||
rng = random.Random(seed)
|
||||
rows = []
|
||||
if noise:
|
||||
for _ in range(height):
|
||||
rows.append(b"\x00" + bytes(rng.getrandbits(8) for _ in range(width * channels)))
|
||||
else:
|
||||
px = bytes(color[:3]) + (b"\x80" if rgba else b"")
|
||||
row = b"\x00" + px * width
|
||||
rows = [row] * height
|
||||
raw = b"".join(rows)
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 6 if rgba else 2, 0, 0, 0)
|
||||
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 6))
|
||||
+ chunk(b"IEND", b""))
|
||||
|
||||
|
||||
def noise_png_fast(width, height, seed=1):
|
||||
"""Несжимаемый PNG через os.urandom (быстро для больших размеров)."""
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 1)) + chunk(b"IEND", b"")
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: зависший processing (lease) и fencing опоздавшего worker.
|
||||
|
||||
python3 student-tests/lease_takeover.py --output evidence/lease-takeover.json
|
||||
|
||||
Worker пересоздаются с WORKER_FAULT_INJECTION=1, JOB_LEASE_SECONDS=10, FAULT_SLOW_SECONDS=25.
|
||||
1. upload fault-slow.png: worker берёт задание и «долго работает» (продлевает аренду);
|
||||
2. пока аренда продлевается, второй worker задание не трогает (долгий != зависший);
|
||||
3. docker pause контейнера-владельца: процесс жив, но заморожен — аренду никто не продлевает;
|
||||
4. через ~lease reaper (relay) переводит задание в queued, второй worker берёт его -> ready;
|
||||
5. docker unpause: опоздавший worker обнаруживает потерю аренды и ничего не записывает
|
||||
(aborted_lease_lost / commit_rejected_lease_lost); вариантов по-прежнему 3, объектов 4.
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, container_ids, events, get_att, invariants, ops,
|
||||
recreate, upload, wait_status, wait_until)
|
||||
|
||||
ENV = {"WORKER_FAULT_INJECTION": "1", "JOB_LEASE_SECONDS": "10", "FAULT_SLOW_SECONDS": "25"}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("lease expiry of a frozen worker and fencing of its late result")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
recreate("worker", ENV)
|
||||
log.step("workers recreated", env=ENV, workers=[x[:12] for x in container_ids("worker")])
|
||||
paused = None
|
||||
try:
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "fault-slow.png")
|
||||
info = wait_until(lambda: (lambda i: i if i["jobs"][0]["status"] == "processing" else None)(
|
||||
ops("inspect", att["id"])), 30, 0.5, "processing")
|
||||
owner = info["jobs"][0]["lease_owner"]
|
||||
lease1 = info["jobs"][0]["lease_until"]
|
||||
log.step("claimed", attachment_id=att["id"], lease_owner=owner, lease_until=lease1)
|
||||
time.sleep(8)
|
||||
info = ops("inspect", att["id"])
|
||||
check(info["jobs"][0]["status"] == "processing" and info["jobs"][0]["lease_owner"] == owner, "long job stolen")
|
||||
log.step("long-running job keeps its lease (heartbeat)", lease_until=info["jobs"][0]["lease_until"],
|
||||
status=info["jobs"][0]["status"])
|
||||
host = owner.split(":")[0]
|
||||
paused = [cid for cid in container_ids("worker") if cid.startswith(host)][0]
|
||||
subprocess.run(["docker", "pause", paused], check=True, capture_output=True)
|
||||
t_pause = time.monotonic()
|
||||
log.step("owner container paused (frozen, no heartbeat)", container=paused[:12])
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=90)
|
||||
took = round(time.monotonic() - t_pause, 1)
|
||||
info = ops("inspect", att["id"])
|
||||
check(ready["status"] == "ready", "not ready after lease expiry")
|
||||
new_owner = [e["actor"] for e in info["events"] if e["event"] == "claimed"][-1]
|
||||
check(new_owner.split(":")[0] != host, "must be taken by the other worker")
|
||||
log.step("lease expired -> requeued -> other worker finished", seconds_after_pause=took,
|
||||
new_owner=new_owner, events=events(info))
|
||||
subprocess.run(["docker", "unpause", paused], check=True, capture_output=True)
|
||||
paused_id, paused = paused, None
|
||||
log.step("owner container unpaused")
|
||||
info = wait_until(lambda: (lambda i: i if {"aborted_lease_lost", "commit_rejected_lease_lost", "error_ignored_lease_lost"} & set(events(i))
|
||||
else None)(ops("inspect", att["id"])), 60, 1, "late worker fenced")
|
||||
inv = invariants(info)
|
||||
after = get_att(c, bob, att["id"])
|
||||
check(inv["variants_ok"] and inv["final_objects_ok"] and after["status"] == "ready", "invariants")
|
||||
check(after["variants"] == ready["variants"], "late worker changed published result")
|
||||
log.step("late worker fenced, result unchanged", events=events(info), invariants=inv)
|
||||
log.save(args.output, attachment_id=att["id"], paused_container=paused_id[:12], events=info["events"],
|
||||
invariants=inv)
|
||||
finally:
|
||||
if paused:
|
||||
subprocess.run(["docker", "unpause", paused], capture_output=True)
|
||||
recreate("worker")
|
||||
print("PASS: frozen worker loses lease, job recovered, late result fenced")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Шторм входов: много параллельных POST /auth/sessions с неверным паролем через LB.
|
||||
|
||||
Зачем: scrypt (N=2^15, r=8) берёт ~32 MiB на одну проверку пароля, лимит API-реплики
|
||||
256 MiB. Без ограничения параллельных проверок несколько одновременных входов
|
||||
приводят к OOM-kill реплики. Скрипт показывает, переживают ли реплики такой шторм.
|
||||
|
||||
Что измеряется:
|
||||
* статусы ответов шторма (ожидаем 401 и, при перегрузке, 503 с Retry-After) и
|
||||
ответы не в JSON-формате ошибки контракта (например HTML-страницы HAProxy);
|
||||
* «жертва»: параллельный поток раз в 50 мс читает /users/me действующим токеном —
|
||||
обычные пользователи не должны получать ошибки из-за шторма входов;
|
||||
* состояние API-контейнеров до/после: OOMKilled, RestartCount, StartedAt.
|
||||
|
||||
Пример: python3 student-tests/login_flood.py --parallel 24 --duration 20 --output evidence/login-flood.json
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
TIMEOUT = 10.0
|
||||
|
||||
|
||||
def http(base, method, path, headers=None, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = dict(headers or {})
|
||||
if data is not None:
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
return r.status, r.headers, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers, e.read()
|
||||
|
||||
|
||||
def is_contract_error(headers, raw):
|
||||
if not (headers.get("Content-Type") or "").startswith("application/json"):
|
||||
return False
|
||||
try:
|
||||
err = json.loads(raw)["error"]
|
||||
return bool(err["code"] and err["message"] and err["request_id"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def api_containers():
|
||||
ids = subprocess.run(["docker", "compose", "ps", "-a", "-q", "api"], capture_output=True,
|
||||
text=True, check=True).stdout.split()
|
||||
out = {}
|
||||
for cid in ids:
|
||||
info = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, text=True,
|
||||
check=True).stdout)[0]
|
||||
out[info["Name"].lstrip("/")] = {
|
||||
"status": info["State"]["Status"], "oom_killed": info["State"]["OOMKilled"],
|
||||
"restart_count": info["RestartCount"], "started_at": info["State"]["StartedAt"]}
|
||||
return out
|
||||
|
||||
|
||||
def oom_events(since):
|
||||
"""Имена контейнеров, получивших OOM с момента since (unix time): флаг OOMKilled
|
||||
сбрасывается после рестарта по restart-policy, поэтому смотрим события Docker."""
|
||||
out = subprocess.run(["docker", "events", "--since", str(int(since)), "--until", str(int(time.time()) + 1),
|
||||
"--filter", "type=container", "--filter", "event=oom",
|
||||
"--format", "{{.Actor.Attributes.name}}"], capture_output=True, text=True).stdout
|
||||
return sorted(Counter(out.split()).items())
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--parallel", type=int, default=24)
|
||||
p.add_argument("--duration", type=float, default=20)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
|
||||
username = "flood_" + uuid.uuid4().hex[:10]
|
||||
password = "correct-horse-" + uuid.uuid4().hex[:8]
|
||||
st, _, _ = http(base, "POST", "/api/v1/users",
|
||||
body={"username": username, "display_name": "Flood", "password": password})
|
||||
assert st == 201, st
|
||||
basic = base64.b64encode(("%s:%s" % (username, password)).encode()).decode()
|
||||
st, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
assert st == 201, st
|
||||
token = json.loads(raw)["token"]
|
||||
bad = base64.b64encode(("%s:wrong-password-123" % username).encode()).decode()
|
||||
|
||||
before = api_containers()
|
||||
wall0 = time.time()
|
||||
stop = threading.Event()
|
||||
lock = threading.Lock()
|
||||
flood, victim = Counter(), Counter()
|
||||
non_json_errors = Counter()
|
||||
retry_after_503 = [0, 0] # [503 всего, из них с Retry-After]
|
||||
|
||||
def record(counter, status, headers, raw):
|
||||
with lock:
|
||||
counter[str(status)] += 1
|
||||
if status >= 400 and not is_contract_error(headers, raw):
|
||||
non_json_errors[str(status)] += 1
|
||||
if status == 503 and counter is flood:
|
||||
retry_after_503[0] += 1
|
||||
retry_after_503[1] += bool(headers.get("Retry-After"))
|
||||
|
||||
def flooder():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(flood, *http(base, "POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + bad}))
|
||||
except Exception as exc: # обрыв соединения, timeout
|
||||
with lock:
|
||||
flood["exc:" + type(exc).__name__] += 1
|
||||
|
||||
def prober():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(victim, *http(base, "GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token}))
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
victim["exc:" + type(exc).__name__] += 1
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=flooder, daemon=True) for _ in range(a.parallel)]
|
||||
threads.append(threading.Thread(target=prober, daemon=True))
|
||||
t0 = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.duration)
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join(TIMEOUT + 1)
|
||||
elapsed = time.monotonic() - t0
|
||||
time.sleep(3) # дать restart-policy отработать, если реплика упала
|
||||
after = api_containers()
|
||||
|
||||
restarted = [n for n in after if n in before and (
|
||||
after[n]["restart_count"] != before[n]["restart_count"]
|
||||
or after[n]["started_at"] != before[n]["started_at"])]
|
||||
victim_ok = victim.get("200", 0)
|
||||
victim_total = sum(victim.values())
|
||||
summary = {
|
||||
"parallel": a.parallel, "duration_s": round(elapsed, 1),
|
||||
"flood_statuses": dict(flood), "flood_rps": round(sum(flood.values()) / elapsed, 1),
|
||||
"flood_503_with_retry_after": "%d/%d" % (retry_after_503[1], retry_after_503[0]),
|
||||
"victim_statuses": dict(victim),
|
||||
"victim_error_rate": round(1 - victim_ok / victim_total, 4) if victim_total else None,
|
||||
"non_contract_error_bodies": dict(non_json_errors),
|
||||
"containers_before": before, "containers_after": after,
|
||||
"oom_events": dict(oom_events(wall0)),
|
||||
"restarted": restarted,
|
||||
}
|
||||
summary["pass"] = (not summary["oom_events"] and not restarted and victim_total > 0
|
||||
and victim_ok == victim_total and not non_json_errors)
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
with open(a.output, "w", encoding="utf-8") as f:
|
||||
f.write(text + "\n")
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,142 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: разрыв PostgreSQL <-> broker закрыт transactional outbox. Окна отказа:
|
||||
|
||||
python3 student-tests/outbox_gap.py --output evidence/outbox-gap.json
|
||||
|
||||
A. relay остановлен: COMMIT есть, publish нет -> outbox не опубликован, очередь пуста;
|
||||
relay запущен -> задание доходит до ready без ручного создания нового задания;
|
||||
B. RELAY_FAULT=crash-before-publish: relay выбрал строки outbox и умер до publish
|
||||
(внедрённый crash между COMMIT и publish) -> рестарт контейнера -> ready;
|
||||
C. RELAY_FAULT=crash-after-publish: publish + confirm прошли, published_at не записан ->
|
||||
после рестарта сообщение опубликовано ещё раз -> worker гасит дубль, вариантов 3;
|
||||
D. API crash-after-commit (FAULT_INJECTION=1): клиент не получил 202, но задание принято
|
||||
и доходит до ready;
|
||||
E. API crash-after-staging: оригинал в staging, задания нет (202 не было) -> pending-строку
|
||||
и staging-объект убирает janitor после grace.
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from lab5lib import (Client, Failure, Log, SAMPLE_PNG, check, compose, events, get_att, invariants, ops,
|
||||
queues, recreate, sql, upload, wait_status, wait_until)
|
||||
|
||||
|
||||
def restart_count(service):
|
||||
ids = compose("ps", "-q", "-a", service).stdout.split()
|
||||
out = subprocess.run(["docker", "inspect", "-f", "{{.RestartCount}}"] + ids, capture_output=True, text=True)
|
||||
return [int(x) for x in out.stdout.split()]
|
||||
|
||||
|
||||
def find_by_filename(name):
|
||||
rows = sql("SELECT id, status, staging_key IS NOT NULL FROM attachments WHERE filename = '%s'" % name)
|
||||
return rows[0] if rows else None
|
||||
|
||||
|
||||
def raw_upload(c, actor, chat, name, fault):
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], name), [502, 503, 504],
|
||||
actor=actor, raw=SAMPLE_PNG, headers={"Content-Type": "image/png", "X-Fault-Inject": fault})
|
||||
return "http %d" % r["status"]
|
||||
except Failure as exc:
|
||||
return str(exc)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("outbox: COMMIT/publish gap and API crash windows")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
res = {}
|
||||
try:
|
||||
# A ---------------------------------------------------------------------------
|
||||
compose("stop", "relay")
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "gap-relay-stopped.png")
|
||||
time.sleep(3)
|
||||
info = ops("inspect", att["id"])
|
||||
q = queues()["attachments.process.v1"]
|
||||
check(info["outbox"][0]["published_at"] is None and get_att(c, bob, att["id"])["status"] == "queued",
|
||||
"A: must stay unpublished")
|
||||
log.step("A: relay stopped, upload 202", attachment_id=att["id"], outbox=info["outbox"], queue=q)
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "relay")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, 60)
|
||||
info = ops("inspect", att["id"])
|
||||
check(ready["status"] == "ready" and len(info["jobs"]) == 1, "A: not ready / extra job")
|
||||
res["A"] = {"attachment_id": att["id"], "events": events(info), "outbox": info["outbox"],
|
||||
"jobs": len(info["jobs"]), "invariants": invariants(info)}
|
||||
log.step("A: relay started -> ready, same single job", **res["A"])
|
||||
|
||||
# B ---------------------------------------------------------------------------
|
||||
recreate("relay", {"RELAY_FAULT": "crash-before-publish"})
|
||||
rc0 = restart_count("relay")
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "gap-crash-before-publish.png")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, 90)
|
||||
info = ops("inspect", att["id"])
|
||||
logs = compose("logs", "--no-log-prefix", "relay").stdout
|
||||
check(ready["status"] == "ready" and "FAULT INJECTION crash-before-publish" in logs, "B")
|
||||
res["B"] = {"attachment_id": att["id"], "relay_restart_count": [rc0, restart_count("relay")],
|
||||
"events": events(info), "outbox": info["outbox"], "invariants": invariants(info)}
|
||||
log.step("B: relay crashed between COMMIT and publish -> restarted -> ready", **res["B"])
|
||||
|
||||
# C ---------------------------------------------------------------------------
|
||||
recreate("relay", {"RELAY_FAULT": "crash-after-publish"})
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "gap-crash-after-publish.png")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, 90)
|
||||
info = wait_until(lambda: (lambda i: i if "duplicate_ignored" in events(i) or
|
||||
"busy_ignored" in events(i) else None)(ops("inspect", att["id"])),
|
||||
60, 1, "duplicate handled")
|
||||
inv = invariants(info)
|
||||
check(ready["status"] == "ready" and inv["variants_ok"] and inv["final_objects_ok"], "C")
|
||||
res["C"] = {"attachment_id": att["id"], "relay_restart_count": restart_count("relay"),
|
||||
"events": events(info), "outbox": info["outbox"], "invariants": inv}
|
||||
log.step("C: published twice (crash before marking) -> duplicate is a no-op", **res["C"])
|
||||
recreate("relay")
|
||||
|
||||
# D ---------------------------------------------------------------------------
|
||||
recreate("api", {"FAULT_INJECTION": "1"})
|
||||
name = "gap-api-crash-after-commit-%d.png" % time.time()
|
||||
outcome = raw_upload(c, alice, chat, name, "crash-after-commit")
|
||||
row = wait_until(lambda: find_by_filename(name), 20, what="attachment row")
|
||||
ready = wait_status(c, bob, row[0], {"ready", "failed"}, 90)
|
||||
info = ops("inspect", row[0])
|
||||
check(ready["status"] == "ready", "D")
|
||||
res["D"] = {"attachment_id": row[0], "client_saw": outcome, "events": events(info),
|
||||
"invariants": invariants(info)}
|
||||
log.step("D: API died after COMMIT before 202 -> work still completed", **res["D"])
|
||||
|
||||
# E ---------------------------------------------------------------------------
|
||||
name = "gap-api-crash-after-staging-%d.png" % time.time()
|
||||
outcome = raw_upload(c, alice, chat, name, "crash-after-staging")
|
||||
row = wait_until(lambda: find_by_filename(name), 20, what="pending row")
|
||||
jobs_n = sql("SELECT count(*) FROM jobs WHERE attachment_id = '%s'" % row[0])[0][0]
|
||||
check(row[1] == "pending" and jobs_n == "0", "E: expected pending row without job")
|
||||
c.call("GET", "/api/v1/attachments/" + row[0], 404, actor=bob)
|
||||
log.step("E: API died after staging before COMMIT", attachment_id=row[0], client_saw=outcome,
|
||||
status=row[1], jobs=int(jobs_n), api_get=404)
|
||||
time.sleep(3)
|
||||
dry = compose("exec", "-T", "janitor", "python", "/app/src/janitor.py", "--once", "--dry-run",
|
||||
"--grace-seconds", "2").stdout
|
||||
real = compose("exec", "-T", "janitor", "python", "/app/src/janitor.py", "--once",
|
||||
"--grace-seconds", "2").stdout
|
||||
import json as _j
|
||||
dry, real = _j.loads(dry.strip().splitlines()[-1]), _j.loads(real.strip().splitlines()[-1])
|
||||
gone = find_by_filename(name) is None
|
||||
check(row[0] in dry["abandoned_ids"] and gone, "E: janitor did not clean")
|
||||
res["E"] = {"attachment_id": row[0], "janitor_dry_run": {k: dry[k] for k in ("abandoned_pending", "orphan_objects",
|
||||
"deleted_objects", "deleted_rows")},
|
||||
"janitor": {k: real[k] for k in ("abandoned_pending", "orphan_objects", "deleted_objects",
|
||||
"deleted_rows", "missing_objects")}, "row_gone": gone}
|
||||
log.step("E: janitor removed pending row and staging object", **res["E"])
|
||||
finally:
|
||||
recreate("relay")
|
||||
recreate("api")
|
||||
log.step("relay and api restored to .env configuration")
|
||||
log.save(args.output, results=res)
|
||||
print("PASS: outbox closes COMMIT/publish gap; API crash windows handled")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/bin/sh
|
||||
# Полный прогон проверок lab5 на запущенном стенде с записью результатов в evidence/.
|
||||
# Каждый сценарий сам включает и выключает свои учебные инъекции отказов.
|
||||
# ./student-tests/run_all.sh
|
||||
set -u
|
||||
cd "$(dirname "$0")/.."
|
||||
E=evidence
|
||||
mkdir -p "$E"
|
||||
status=0
|
||||
run() { # run <name> <command...>
|
||||
name=$1; shift
|
||||
printf '=== %s\n' "$name"
|
||||
{ echo "# $(date -u +%FT%TZ) $*"; "$@" 2>&1; rc=$?; echo "exit=$rc"; } > "$E/$name.txt"
|
||||
tail -n 3 "$E/$name.txt"
|
||||
grep -q '^exit=0$' "$E/$name.txt" || status=1
|
||||
}
|
||||
states() { docker compose ps --format '{{.Name}} {{.State}}' | sort; \
|
||||
for c in $(docker compose ps -q); do docker inspect -f '{{.Name}} StartedAt={{.State.StartedAt}}' "$c"; done | sort; }
|
||||
|
||||
run check make check
|
||||
run smoke make test
|
||||
{ echo "# containers before persistence hook"; states; } > "$E/containers-before-restart.txt"
|
||||
run persistence make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
{ echo "# containers after persistence hook"; states; } > "$E/containers-after-restart.txt"
|
||||
run failover make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
./scripts/start-all.sh >/dev/null 2>&1
|
||||
run worker-outage python3 student-tests/worker_outage.py --output "$E/worker-outage.json"
|
||||
run variants-check docker compose --profile tools run --rm -T checks /app/student-tests/variants_check.py \
|
||||
--base-url http://lb:8080 --output /app/evidence/variants-check.json
|
||||
run transform-limits docker compose --profile tools run --rm -T checks /app/student-tests/transform_limits.py \
|
||||
--output /app/evidence/transform-limits.json
|
||||
run worker-faults python3 student-tests/worker_faults.py --output "$E/worker-faults.json"
|
||||
run outbox-gap python3 student-tests/outbox_gap.py --output "$E/outbox-gap.json"
|
||||
run lease-takeover python3 student-tests/lease_takeover.py --output "$E/lease-takeover.json"
|
||||
run burst python3 student-tests/burst.py --count 24 --output "$E/burst.json"
|
||||
run broker-permissions python3 student-tests/broker_permissions.py --output "$E/broker-permissions.json"
|
||||
run s3-private-check docker compose --profile tools run --rm -T checks /app/student-tests/s3_private_check.py
|
||||
run attachments-negative python3 student-tests/attachments_negative.py --output "$E/attachments-negative.json"
|
||||
run attachment-failover python3 student-tests/attachment_failover.py --output "$E/attachment-failover.json"
|
||||
./scripts/start-all.sh >/dev/null 2>&1
|
||||
run janitor-dry-run docker compose exec -T janitor python /app/src/janitor.py --once --dry-run
|
||||
run queues docker compose exec -T broker rabbitmqctl -q -p messenger list_queues name type durable messages consumers
|
||||
run failed-registry docker compose --profile tools run --rm -T ops failed --limit 10
|
||||
echo "overall=$status"
|
||||
exit $status
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Недоступность S3: stop (порт закрыт) и pause (S3 «завис», TCP не отвечает).
|
||||
|
||||
python3 student-tests/s3_outage.py [--output evidence/s3-outage.json]
|
||||
|
||||
Ожидания: upload и download — быстрый 503 unavailable c Retry-After (не 500 и не
|
||||
таймаут LB), текстовые сообщения и /health/ready продолжают работать (S3 не входит в
|
||||
readiness), после восстановления S3 загрузка снова 201 без перезапуска API.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
log = []
|
||||
|
||||
|
||||
def probe(c, alice, chat, att):
|
||||
out = {}
|
||||
for name, args in (
|
||||
("upload", ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"])),
|
||||
("download", ("GET", "/api/v1/attachments/%s/content" % att["id"])),
|
||||
("text_message", ("POST", "/api/v1/chats/%s/messages" % chat["id"])),
|
||||
("ready", ("GET", "/health/ready"))):
|
||||
kw = {}
|
||||
if name == "upload":
|
||||
kw = {"raw": PNG, "headers": {"Content-Type": "image/png"}}
|
||||
if name == "text_message":
|
||||
kw = {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}
|
||||
t = time.monotonic()
|
||||
r = c.call(*args, [200, 201, 503, 502, 504], actor=alice if name != "ready" else None, **kw)
|
||||
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
|
||||
"code": (r["json"] or {}).get("error", {}).get("code"),
|
||||
"retry_after": r["headers"].get("Retry-After")}
|
||||
return out
|
||||
|
||||
|
||||
def phase(name, c, alice, chat, att):
|
||||
entry = {"phase": name, "probe": probe(c, alice, chat, att)}
|
||||
log.append(entry)
|
||||
print(json.dumps(entry, ensure_ascii=False), flush=True)
|
||||
return entry
|
||||
|
||||
|
||||
def recover(c, alice, chat, started):
|
||||
while time.monotonic() - started < 120:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=r.png" % chat["id"], [201, 503], actor=alice,
|
||||
raw=PNG, headers={"Content-Type": "image/png"})
|
||||
if r["status"] == 201:
|
||||
return round(time.monotonic() - started, 1)
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 201, actor=alice, raw=PNG,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||
phase("baseline", c, alice, chat, att)
|
||||
for action, undo in ((["stop", "s3"], ["start", "s3"]), (["pause", "s3"], ["unpause", "s3"])):
|
||||
subprocess.run(["docker", "compose"] + action, cwd=ROOT, check=True, capture_output=True)
|
||||
time.sleep(1)
|
||||
phase("immediately after `%s` (S3Health not yet stale)" % " ".join(action), c, alice, chat, att)
|
||||
time.sleep(4)
|
||||
phase("S3 down for 5 s (`%s`)" % " ".join(action), c, alice, chat, att)
|
||||
subprocess.run(["docker", "compose"] + undo, cwd=ROOT, check=True, capture_output=True)
|
||||
t0 = time.monotonic()
|
||||
rec = recover(c, alice, chat, t0)
|
||||
log.append({"phase": "recovery after `%s`" % " ".join(undo), "upload_201_after_s": rec})
|
||||
print(json.dumps(log[-1]), flush=True)
|
||||
# Оставляем стенд рабочим: ждём, пока healthcheck S3 снова станет healthy (после pause
|
||||
# он несколько проверок подряд был unhealthy, а `docker compose up api` при нездоровой
|
||||
# зависимости не запускает реплики).
|
||||
cid = subprocess.run(["docker", "compose", "ps", "-q", "s3"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
|
||||
t0 = time.monotonic()
|
||||
while time.monotonic() - t0 < 120:
|
||||
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True, text=True).stdout.strip()
|
||||
if st == "healthy":
|
||||
break
|
||||
time.sleep(1)
|
||||
log.append({"phase": "s3 healthcheck healthy again", "after_s": round(time.monotonic() - t0, 1), "status": st})
|
||||
print(json.dumps(log[-1]), flush=True)
|
||||
down = [e for e in log if e.get("phase", "").startswith("S3 down")]
|
||||
ok = all(e["probe"]["upload"]["status"] == 503 and e["probe"]["download"]["status"] == 503
|
||||
and e["probe"]["text_message"]["status"] == 201 and e["probe"]["ready"]["status"] == 200
|
||||
for e in down) and all(e.get("upload_201_after_s") is not None for e in log if "upload_201_after_s" in e)
|
||||
no5xx = all(p["status"] in (200, 201, 503) for e in log if "probe" in e for p in e["probe"].values())
|
||||
ok = ok and st == "healthy"
|
||||
print(json.dumps({"pass": ok and no5xx, "only_200_201_503": no5xx}))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"pass": ok and no5xx, "phases": log}, ensure_ascii=False, indent=1))
|
||||
return 0 if ok and no5xx else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка приватности bucket и ограничений ключей ВНЕ API (внутри backend-сети).
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/s3_private_check.py
|
||||
|
||||
Проверяет напрямую на S3 (минуя API и его ACL):
|
||||
* анонимные GET объекта / ListBucket / PUT -> 403;
|
||||
* ключ api: Put/Get/Delete своего тестового объекта можно; ListBucket, CreateBucket,
|
||||
DeleteBucket, PutBucketPolicy — AccessDenied; другой bucket — AccessDenied;
|
||||
* ключ worker (lab5): Get/Put/Delete можно; ListBucket, CreateBucket — AccessDenied;
|
||||
* ключ janitor: List и Delete можно; GetObject (чтение содержимого) — AccessDenied;
|
||||
* служебные порты SeaweedFS (master 9333, volume 8080, filer 8888, IAM 8111,
|
||||
Iceberg 8181, Lance 9101) из backend-сети недоступны — открыт только S3 :8333.
|
||||
Выход 0 только если все ожидания выполнены. Ключи не печатаются.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
sys.path.insert(0, "/app/src")
|
||||
from minio import Minio # noqa: E402
|
||||
from minio.error import S3Error # noqa: E402
|
||||
|
||||
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:8333").rstrip("/")
|
||||
HOST = urlsplit(ENDPOINT).netloc
|
||||
|
||||
|
||||
def key(name):
|
||||
with open("/run/secrets/" + name) as f:
|
||||
return f.read().strip()
|
||||
|
||||
|
||||
def client(who):
|
||||
return Minio(HOST, access_key=key("s3_%s_access_key" % who), secret_key=key("s3_%s_secret_key" % who),
|
||||
secure=False, region=os.environ.get("S3_REGION", "us-east-1"))
|
||||
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
def expect(name, should_succeed, fn):
|
||||
try:
|
||||
fn()
|
||||
ok, got = should_succeed, "allowed"
|
||||
except S3Error as exc:
|
||||
ok, got = not should_succeed, exc.code
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok, got = False, type(exc).__name__
|
||||
results.append({"check": name, "expected": "allowed" if should_succeed else "denied", "got": got, "pass": ok})
|
||||
|
||||
|
||||
def http_status(method, url, data=None):
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=3) as resp:
|
||||
return resp.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def main():
|
||||
api, janitor, worker = client("api"), client("janitor"), client("worker")
|
||||
probe = "originals/s3check-" + uuid.uuid4().hex
|
||||
expect("api: PutObject в свой bucket", True, lambda: api.put_object(BUCKET, probe, io.BytesIO(b"x" * 16), 16))
|
||||
for name, method, url, data in (
|
||||
("anonymous GET object", "GET", "%s/%s/%s" % (ENDPOINT, BUCKET, probe), None),
|
||||
("anonymous ListBucket", "GET", "%s/%s?list-type=2" % (ENDPOINT, BUCKET), None),
|
||||
("anonymous ListAllMyBuckets", "GET", ENDPOINT + "/", None),
|
||||
("anonymous PUT object", "PUT", "%s/%s/anon-%s" % (ENDPOINT, BUCKET, uuid.uuid4().hex), b"z")):
|
||||
code = http_status(method, url, data)
|
||||
results.append({"check": name, "expected": "403", "got": code, "pass": code in (401, 403)})
|
||||
expect("api: GetObject", True, lambda: api.get_object(BUCKET, probe).read())
|
||||
expect("api: ListBucket", False, lambda: list(api.list_objects(BUCKET, recursive=True)))
|
||||
expect("api: CreateBucket", False, lambda: api.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteBucket", False, lambda: api.remove_bucket(BUCKET))
|
||||
expect("api: PutBucketPolicy (сделать публичным)", False, lambda: api.set_bucket_policy(BUCKET, json.dumps({
|
||||
"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": "*", "Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::%s/*" % BUCKET]}]})))
|
||||
expect("janitor: GetObject (чтение содержимого)", False, lambda: janitor.get_object(BUCKET, probe).read())
|
||||
expect("janitor: ListBucket", True, lambda: list(janitor.list_objects(BUCKET, prefix="originals/", recursive=True)))
|
||||
expect("janitor: CreateBucket", False, lambda: janitor.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("worker: GetObject (чтение staging)", True, lambda: worker.get_object(BUCKET, probe).read())
|
||||
expect("worker: PutObject (результат)", True, lambda: worker.put_object(BUCKET, probe + ".w", io.BytesIO(b"y"), 1))
|
||||
expect("worker: DeleteObject (очистка staging)", True, lambda: worker.remove_object(BUCKET, probe + ".w"))
|
||||
expect("worker: ListBucket", False, lambda: list(worker.list_objects(BUCKET, recursive=True)))
|
||||
expect("worker: CreateBucket", False, lambda: worker.make_bucket("evil-" + uuid.uuid4().hex[:8]))
|
||||
expect("api: DeleteObject (компенсация)", True, lambda: api.remove_object(BUCKET, probe))
|
||||
s3_host = HOST.split(":")[0]
|
||||
for port, role in ((9333, "master UI/API"), (8080, "volume"), (8888, "filer UI/API"), (8111, "IAM API"),
|
||||
(8181, "Iceberg"), (9101, "Lance"), (8333, "S3 API")):
|
||||
try:
|
||||
socket.create_connection((s3_host, port), timeout=2).close()
|
||||
got = "open"
|
||||
except OSError:
|
||||
got = "closed"
|
||||
want = "open" if port == 8333 else "closed"
|
||||
results.append({"check": "port %d (%s) из backend-сети" % (port, role), "expected": want, "got": got,
|
||||
"pass": got == want})
|
||||
for r in results:
|
||||
print(("PASS " if r["pass"] else "FAIL ") + "%-45s expected=%-8s got=%s" % (r["check"], r["expected"], r["got"]))
|
||||
failed = [r for r in results if not r["pass"]]
|
||||
print(json.dumps({"checks": len(results), "failed": len(failed)}))
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Учебная порча staging-объекта (контейнер checks, ключ api): подменяет байты на другие
|
||||
байты той же длины. Нужна worker_faults.py для проверки постоянной ошибки staging_corrupted.
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/s3_tamper.py staging/<hex>
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, "/app/src")
|
||||
os.environ.setdefault("S3_ACCESS_KEY_ID_FILE", "/run/secrets/s3_api_access_key")
|
||||
os.environ.setdefault("S3_SECRET_ACCESS_KEY_FILE", "/run/secrets/s3_api_secret_key")
|
||||
import objstore # noqa: E402
|
||||
|
||||
key = sys.argv[1]
|
||||
if not re.fullmatch(r"staging/[0-9a-f]{32}", key):
|
||||
sys.exit("refusing: not a staging key")
|
||||
store = objstore.ObjectStore(objstore.make_client(), os.environ.get("S3_BUCKET", "messenger-attachments"))
|
||||
resp = store.open(key)
|
||||
data = resp.read()
|
||||
resp.close()
|
||||
resp.release_conn()
|
||||
bad = bytes(b ^ 0x5A for b in data)
|
||||
store.put(key, io.BytesIO(bad), len(bad), "application/octet-stream")
|
||||
print("tampered", key, len(bad))
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Лимиты worker на «плохие» входы: пиксели, память, CPU-время, повреждённые данные.
|
||||
Запускает src/transform.py так же, как worker (подпроцесс), В КОНТЕЙНЕРЕ checks:
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/transform_limits.py \
|
||||
--output /app/evidence/transform-limits.json
|
||||
|
||||
API отсекает > 10 MiB и > 40 Мпикс ещё до очереди (lab4); здесь проверяется вторая линия
|
||||
обороны — сам worker, если в staging всё же оказался такой файл.
|
||||
"""
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
|
||||
TRANSFORM = "/app/src/transform.py"
|
||||
EXPECT = {0: "ok", 3: "invalid_image", 4: "image_too_large", 5: "resource_limit"}
|
||||
|
||||
|
||||
def run(data, ctype, env=None, max_pixels=40000000, timeout=60):
|
||||
"""Как worker: подпроцесс; timeout — wall-clock (у worker JOB_TIMEOUT_SECONDS)."""
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
src = os.path.join(d, "in")
|
||||
Path(src).write_bytes(data)
|
||||
out = os.path.join(d, "out")
|
||||
os.mkdir(out)
|
||||
e = dict(os.environ, **(env or {}))
|
||||
t = time.monotonic()
|
||||
try:
|
||||
p = subprocess.run([sys.executable, TRANSFORM, src, out, ctype, str(max_pixels)], capture_output=True,
|
||||
env=e, timeout=timeout)
|
||||
rc = p.returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
rc = "timeout"
|
||||
dur = round(time.monotonic() - t, 2)
|
||||
if rc == "timeout":
|
||||
return {"exit": rc, "class": "processing_timeout", "seconds": round(time.monotonic() - t, 2)}
|
||||
cls = EXPECT.get(rc, "killed_by_signal_%d" % -rc if isinstance(rc, int) and rc < 0 else str(rc))
|
||||
return {"exit": rc, "class": cls, "seconds": dur}
|
||||
|
||||
|
||||
def png(size, mode="RGB", color=(10, 20, 30)):
|
||||
buf = io.BytesIO()
|
||||
Image.new(mode, size, color).save(buf, "PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
ok = png((640, 480))
|
||||
big = png((6000, 6000)) # 36 Мпикс: допустимо, ~108 MiB в RGB
|
||||
# Несжимаемый RGBA-шум ~40 Мпикс: декодирование, alpha-композиция и resize — секунды CPU.
|
||||
buf = io.BytesIO()
|
||||
n = Image.effect_noise((6300, 6300), 80)
|
||||
Image.merge("RGBA", [n, n.transpose(Image.Transpose.ROTATE_90), n, n]).save(buf, "PNG", compress_level=1)
|
||||
heavy = buf.getvalue()
|
||||
cases = [
|
||||
("valid 640x480", ok, "image/png", {}, 40000000, "ok"),
|
||||
("49 Mpx PNG (> MAX_IMAGE_PIXELS)", png((7000, 7000)), "image/png", {}, 40000000, "image_too_large"),
|
||||
("36 Mpx PNG, normal limits", big, "image/png", {}, 40000000, "ok"),
|
||||
("36 Mpx PNG, memory limit 160 MiB", big, "image/png", {"TRANSFORM_MEMORY_LIMIT_MB": "160"}, 40000000,
|
||||
"resource_limit"),
|
||||
("40 Mpx RGBA noise PNG, CPU limit 1 s", heavy, "image/png", {"TRANSFORM_CPU_SECONDS": "1"}, 40000000,
|
||||
"killed_by_signal_24"),
|
||||
("40 Mpx RGBA noise PNG, wall timeout 0.5 s", heavy, "image/png", {}, 40000000, "processing_timeout"),
|
||||
("truncated PNG", ok[: len(ok) // 2], "image/png", {}, 40000000, "invalid_image"),
|
||||
("garbage declared as JPEG", b"\xff\xd8\xff" + os.urandom(5000), "image/jpeg", {}, 40000000, "invalid_image"),
|
||||
("PNG declared as JPEG", ok, "image/jpeg", {}, 40000000, "invalid_image"),
|
||||
]
|
||||
results = []
|
||||
failed = 0
|
||||
for name, data, ctype, env, mp, want in cases:
|
||||
r = run(data, ctype, env, mp, timeout=0.5 if want == "processing_timeout" else 60)
|
||||
r.update(case=name, expected=want, input_bytes=len(data), env=env)
|
||||
r["pass"] = r["class"] == want or (want.startswith("killed") and r["class"] in ("resource_limit", want))
|
||||
failed += not r["pass"]
|
||||
results.append(r)
|
||||
print("%s %-36s -> %s (%.2fs)" % ("PASS" if r["pass"] else "FAIL", name, r["class"], r["seconds"]), flush=True)
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"cases": results}, ensure_ascii=False, indent=1) + "\n")
|
||||
print("PASS" if not failed else "FAIL", "%d/%d" % (len(cases) - failed, len(cases)))
|
||||
sys.exit(1 if failed else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Пик памяти API при одновременных загрузках крупных файлов (уровень 4).
|
||||
|
||||
python3 student-tests/upload_memory.py --concurrency 12 --rounds 3 --output evidence/upload-memory-c12.json
|
||||
|
||||
Гипотеза: потоковый приём (буфер 64 KiB -> безымянный временный файл), multipart PUT
|
||||
частями по 5 MiB и draft-декодирование JPEG держат RAM реплики ограниченной и не
|
||||
зависящей линейно от числа одновременных загрузок; 10+ загрузок по ~10 MiB не
|
||||
приближают процесс к лимиту контейнера 256 MiB.
|
||||
|
||||
Методика: перед прогоном API-реплики перезапускаются (VmHWM считается с нуля). В каждой
|
||||
реплике фоново (docker exec ... while sleep 0.05) читаются VmRSS процесса (PID 1) и
|
||||
anon/file из cgroup memory.stat. Нагрузка — concurrency потоков, каждый грузит свой
|
||||
файл через LB; файлы: несжимаемый PNG ~9.99 MiB и (если на хосте есть Pillow) JPEG
|
||||
6000x6000 = 36 Мпикс. В конце — VmHWM (пиковый RSS процесса) и memory.peak cgroup.
|
||||
file-память cgroup — page cache временных файлов, она вытесняема и OOM не вызывает.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from client import Client # noqa: E402
|
||||
from attachments_negative import noise_png # noqa: E402
|
||||
|
||||
SAMPLER = ("while true; do r=$(grep VmRSS /proc/1/status | tr -s ' ' | cut -d' ' -f2); "
|
||||
"a=$(grep '^anon ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); "
|
||||
"f=$(grep '^file ' /sys/fs/cgroup/memory.stat | cut -d' ' -f2); echo \"$r $a $f\"; sleep 0.05; done")
|
||||
|
||||
|
||||
def sh(*cmd):
|
||||
return subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
def containers():
|
||||
return sh("docker", "compose", "ps", "-q", "api").split()
|
||||
|
||||
|
||||
def proc_status(cid, field):
|
||||
out = sh("docker", "exec", cid, "grep", field, "/proc/1/status")
|
||||
return int(out.split()[1]) // 1024 # kB -> MiB
|
||||
|
||||
|
||||
class Sampler:
|
||||
def __init__(self, cid):
|
||||
self.cid, self.samples = cid, []
|
||||
self.p = subprocess.Popen(["docker", "exec", cid, "sh", "-c", SAMPLER], stdout=subprocess.PIPE, text=True)
|
||||
threading.Thread(target=self._read, daemon=True).start()
|
||||
|
||||
def _read(self):
|
||||
for line in self.p.stdout:
|
||||
parts = line.split()
|
||||
if len(parts) == 3:
|
||||
self.samples.append((time.monotonic(), int(parts[0]) / 1024, int(parts[1]) / 2**20, int(parts[2]) / 2**20))
|
||||
|
||||
def stop(self):
|
||||
self.p.terminate()
|
||||
|
||||
|
||||
def make_jpeg():
|
||||
try:
|
||||
from PIL import Image
|
||||
except ImportError:
|
||||
return None
|
||||
im = Image.effect_noise((6000, 6000), 40).convert("RGB")
|
||||
for q in (60, 45, 30, 20):
|
||||
b = io.BytesIO()
|
||||
im.save(b, "JPEG", quality=q)
|
||||
if b.tell() <= 10 * 1024 * 1024:
|
||||
return b.getvalue()
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default="http://localhost:8080")
|
||||
ap.add_argument("--concurrency", type=int, default=12)
|
||||
ap.add_argument("--rounds", type=int, default=3)
|
||||
ap.add_argument("--no-restart", action="store_true")
|
||||
ap.add_argument("--output")
|
||||
args = ap.parse_args()
|
||||
files = [("image/png", noise_png(10 * 1024 * 1024))]
|
||||
jpeg = make_jpeg()
|
||||
if jpeg:
|
||||
files.append(("image/jpeg", jpeg))
|
||||
if not args.no_restart:
|
||||
sh("docker", "compose", "restart", "api")
|
||||
sh("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--wait", "api")
|
||||
time.sleep(4)
|
||||
c = Client(args.base_url, timeout=120)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
# прогрев: один upload каждого типа (импорт Pillow, пулы соединений)
|
||||
for ctype, data in files:
|
||||
c.call("POST", "/api/v1/chats/%s/attachments?filename=w" % chat["id"], 202, actor=alice, raw=data,
|
||||
headers={"Content-Type": ctype})
|
||||
cids = containers()
|
||||
idle = {cid[:12]: {"rss_mib": proc_status(cid, "VmRSS"), "hwm_mib_after_warmup": proc_status(cid, "VmHWM")}
|
||||
for cid in cids}
|
||||
s3_cid = sh("docker", "compose", "ps", "-q", "s3").split()[0]
|
||||
s3_before = {"rss_mib": proc_status(s3_cid, "VmRSS"), "oom_killed": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip()}
|
||||
samplers = [Sampler(cid) for cid in cids]
|
||||
s3_sampler = Sampler(s3_cid)
|
||||
time.sleep(1)
|
||||
results, lock = [], threading.Lock()
|
||||
|
||||
def worker(i):
|
||||
ctype, data = files[i % len(files)]
|
||||
t = time.monotonic()
|
||||
try:
|
||||
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=m%d" % (chat["id"], i), [202, 503], actor=alice,
|
||||
raw=data, headers={"Content-Type": ctype}, schema=None)
|
||||
st, inst = r["status"], r["headers"].get("X-Instance-Id")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
st, inst = type(exc).__name__, None
|
||||
with lock:
|
||||
results.append({"type": ctype, "status": st, "instance": inst, "s": round(time.monotonic() - t, 2)})
|
||||
|
||||
started = time.monotonic()
|
||||
for _ in range(args.rounds):
|
||||
threads = [threading.Thread(target=worker, args=(i,)) for i in range(args.concurrency)]
|
||||
for th in threads:
|
||||
th.start()
|
||||
for th in threads:
|
||||
th.join()
|
||||
wall = time.monotonic() - started
|
||||
time.sleep(1)
|
||||
for s in samplers + [s3_sampler]:
|
||||
s.stop()
|
||||
per = {}
|
||||
for cid, s in zip(cids, samplers):
|
||||
k = cid[:12]
|
||||
per[k] = dict(idle[k],
|
||||
samples=len(s.samples),
|
||||
peak_rss_mib_sampled=round(max(x[1] for x in s.samples), 1),
|
||||
peak_anon_mib=round(max(x[2] for x in s.samples), 1),
|
||||
peak_file_cache_mib=round(max(x[3] for x in s.samples), 1),
|
||||
vmhwm_mib=proc_status(cid, "VmHWM"),
|
||||
cgroup_memory_peak_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.peak")) / 2**20, 1),
|
||||
memory_limit_mib=round(int(sh("docker", "exec", cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20),
|
||||
uploads_served=sum(1 for r in results if r["instance"] == k))
|
||||
durations = sorted(r["s"] for r in results if r["status"] == 202)
|
||||
summary = {
|
||||
"concurrency": args.concurrency, "rounds": args.rounds,
|
||||
"files": [{"type": t, "bytes": len(d), "sha256": hashlib.sha256(d).hexdigest()[:16]} for t, d in files],
|
||||
"uploads": len(results), "status_counts": {str(k): sum(1 for r in results if r["status"] == k)
|
||||
for k in {r["status"] for r in results}},
|
||||
"megabytes_uploaded_ok": round(sum(len(files[i % len(files)][1]) for i, r in enumerate(results)
|
||||
if r["status"] == 202) / 2**20, 1),
|
||||
"wall_s": round(wall, 1),
|
||||
"latency_s_p50_max": [durations[len(durations) // 2], durations[-1]] if durations else None,
|
||||
"replicas": per,
|
||||
"s3": dict(s3_before,
|
||||
peak_rss_mib_sampled=round(max(x[1] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||||
peak_anon_mib=round(max(x[2] for x in s3_sampler.samples), 1) if s3_sampler.samples else None,
|
||||
restarts=int(sh("docker", "inspect", "-f", "{{.RestartCount}}", s3_cid)),
|
||||
oom_killed_after=sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", s3_cid).strip(),
|
||||
memory_limit_mib=round(int(sh("docker", "exec", s3_cid, "cat", "/sys/fs/cgroup/memory.max")) / 2**20)),
|
||||
"oom_kills": sh("docker", "inspect", "-f", "{{.State.OOMKilled}}", *cids).split(),
|
||||
}
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps(summary, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,128 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка вариантов по контракту (запускается В КОНТЕЙНЕРЕ checks, где есть Pillow):
|
||||
|
||||
docker compose --profile tools run --rm checks /app/student-tests/variants_check.py \
|
||||
--base-url http://lb:8080 --output /app/evidence/variants-check.json
|
||||
|
||||
Для каждого входа: ready, ровно 3 варианта, метаданные = фактическим байтам (размер, SHA-256,
|
||||
декодированные размеры, формат), оригинал неизменен. Thumbnail: JPEG, вписан в 256x256 без
|
||||
увеличения, округление вниз; EXIF orientation применена; alpha -> белый. Crop: JPEG 128x128.
|
||||
Optimized: WebP, вписан в 1280x1280 без увеличения. В вариантах нет EXIF/ICC.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, "/app/tests")
|
||||
from client import Client, check # noqa: E402
|
||||
from PIL import Image # noqa: E402
|
||||
|
||||
FIXTURE = Path("/app/tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def fit(w, h, box):
|
||||
if w <= box and h <= box:
|
||||
return w, h
|
||||
return (box, max(1, h * box // w)) if w >= h else (max(1, w * box // h), box)
|
||||
|
||||
|
||||
def encode(img, fmt, **kw):
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, fmt, **kw)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def cases():
|
||||
out = [("fixture 320x200 PNG", FIXTURE, "image/png", (320, 200), None)]
|
||||
# RGBA: левая половина прозрачная -> в JPEG должна стать белой.
|
||||
rgba = Image.new("RGBA", (300, 300), (200, 20, 20, 255))
|
||||
rgba.paste((0, 0, 0, 0), (0, 0, 150, 300))
|
||||
out.append(("RGBA 300x300 half transparent", encode(rgba, "PNG"), "image/png", (300, 300), "alpha"))
|
||||
# EXIF orientation 6 (поворот 90° по часовой): хранится 400x200, показывается 200x400.
|
||||
# Верхняя половина ХРАНИМОГО кадра красная -> после поворота красной становится правая половина.
|
||||
raw = Image.new("RGB", (400, 200), (0, 0, 255))
|
||||
raw.paste((255, 0, 0), (0, 0, 400, 100))
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = 6
|
||||
exif[0x010F] = "MTUSI test camera" # Make: проверяем, что EXIF не утёк в варианты
|
||||
out.append(("JPEG 400x200 EXIF orientation=6", encode(raw, "JPEG", quality=95, exif=exif.tobytes()),
|
||||
"image/jpeg", (200, 400), "orientation"))
|
||||
out.append(("tiny PNG 10x5 (no upscale)", encode(Image.new("RGB", (10, 5), (9, 200, 9)), "PNG"),
|
||||
"image/png", (10, 5), None))
|
||||
big = Image.radial_gradient("L").resize((3000, 2000)).convert("RGB")
|
||||
out.append(("JPEG 3000x2000", encode(big, "JPEG", quality=90), "image/jpeg", (3000, 2000), None))
|
||||
tall = Image.new("RGB", (100, 1000), (50, 60, 70))
|
||||
out.append(("tall PNG 100x1000", encode(tall, "PNG"), "image/png", (100, 1000), None))
|
||||
pal = Image.new("P", (64, 64), 1)
|
||||
pal.putpalette([255, 255, 255, 10, 200, 10] + [0] * 762)
|
||||
out.append(("palette PNG with transparency", encode(pal, "PNG", transparency=1), "image/png", (64, 64), "alpha"))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://lb:8080")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
results = []
|
||||
pending = []
|
||||
for name, data, ctype, (ow, oh), special in cases():
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=v.%s" % (chat["id"], ctype.split("/")[1]), 202,
|
||||
actor=alice, raw=data, headers={"Content-Type": ctype}, schema="Attachment")["json"]
|
||||
pending.append((name, data, ctype, ow, oh, special, att["id"]))
|
||||
for name, data, ctype, ow, oh, special, att_id in pending:
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
att = c.call("GET", "/api/v1/attachments/" + att_id, actor=bob, schema="Attachment")["json"]
|
||||
if att["status"] in ("ready", "failed") or time.monotonic() > deadline:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
check(att["status"] == "ready", "%s: status %s" % (name, att["status"]))
|
||||
r = {"case": name, "source_oriented": [ow, oh], "variants": {}}
|
||||
orig = c.call("GET", "/api/v1/attachments/%s/content" % att_id, actor=bob)
|
||||
check(orig["bytes"] == data and orig["headers"].get_content_type() == ctype, name + ": original changed")
|
||||
check(sorted(v["name"] for v in att["variants"]) == ["crop", "optimized", "thumbnail"], name + ": variants")
|
||||
expect = {"thumbnail": ("image/jpeg", "JPEG", fit(ow, oh, 256)),
|
||||
"crop": ("image/jpeg", "JPEG", (128, 128)),
|
||||
"optimized": ("image/webp", "WEBP", fit(ow, oh, 1280))}
|
||||
for v in att["variants"]:
|
||||
ct, fmt, size = expect[v["name"]]
|
||||
body = c.call("GET", "/api/v1/attachments/%s/content?variant=%s" % (att_id, v["name"]), actor=bob)
|
||||
b = body["bytes"]
|
||||
img = Image.open(io.BytesIO(b))
|
||||
img.load()
|
||||
check(v["content_type"] == ct and body["headers"].get_content_type() == ct, name + ": content type")
|
||||
check(img.format == fmt, name + ": real format " + str(img.format))
|
||||
check((v["width"], v["height"]) == size == img.size, "%s %s: size %s meta %s expected %s" % (
|
||||
name, v["name"], img.size, (v["width"], v["height"]), size))
|
||||
check(v["size_bytes"] == len(b) and v["sha256"] == hashlib.sha256(b).hexdigest(), name + ": checksum")
|
||||
no_meta = not img.getexif() and "icc_profile" not in img.info and "exif" not in img.info
|
||||
check(no_meta, name + ": metadata leaked into " + v["name"])
|
||||
item = {"size": list(img.size), "format": fmt, "bytes": len(b), "no_exif_icc": no_meta}
|
||||
if special == "alpha" and v["name"] in ("thumbnail", "crop"):
|
||||
px = img.convert("RGB").getpixel((1, img.size[1] // 2))
|
||||
check(min(px) >= 245, name + ": transparent area is not white: %s" % (px,))
|
||||
item["transparent_pixel_rgb"] = list(px)
|
||||
if special == "orientation" and v["name"] == "thumbnail":
|
||||
w, h = img.size
|
||||
left, right = img.getpixel((w // 4, h // 2)), img.getpixel((3 * w // 4, h // 2))
|
||||
check(right[0] > 200 and right[2] < 60 and left[2] > 200, name + ": orientation not applied")
|
||||
item["left_rgb"], item["right_rgb"] = list(left), list(right)
|
||||
r["variants"][v["name"]] = item
|
||||
results.append(r)
|
||||
print("PASS %-36s %s" % (name, {k: tuple(x["size"]) for k, x in r["variants"].items()}), flush=True)
|
||||
c.call("GET", "/api/v1/attachments/%s/content?variant=bogus" % pending[0][6], 400, actor=bob)
|
||||
if args.output:
|
||||
Path(args.output).write_text(json.dumps({"cases": results, "unknown_variant_status": 400},
|
||||
ensure_ascii=False, indent=1) + "\n")
|
||||
print("PASS: %d inputs, all variants match contract" % len(results))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 4: отказы worker, retry/backoff, failed + replay, DLQ.
|
||||
|
||||
python3 student-tests/worker_faults.py --output evidence/worker-faults.json
|
||||
|
||||
На время теста worker пересоздаются с WORKER_FAULT_INJECTION=1 и JOB_RETRY_BASE_SECONDS=1
|
||||
(короче ожидание backoff); в конце возвращаются к значениям из .env.
|
||||
Точка отказа задаётся именем файла fault-<point>.png (src/worker.py).
|
||||
|
||||
crash-after-claim процесс умер в processing до любых эффектов
|
||||
crash-after-s3-put все объекты записаны в S3, COMMIT ready не сделан, ack не отправлен
|
||||
crash-after-commit ready зафиксирован, ack не отправлен (и staging не удалён)
|
||||
transient-2 временная ошибка в попытках 1–2: backoff с jitter, ready с 3-й
|
||||
transient-always временная ошибка до replay: 5 попыток -> failed(retry_exhausted)
|
||||
-> content 409, прикрепление 409 -> ops replay -> ready; повторный replay отклонён
|
||||
staging tamper staging подменён до обработки -> failed(staging_corrupted) без повторов
|
||||
poison message невалидное сообщение -> reject -> DLQ -> ops dlq --purge-invalid
|
||||
Инварианты после каждого: 3 варианта, 4 конечных объекта, staging убран (с janitor).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
|
||||
from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, events, get_att, invariants, ops, png, queues,
|
||||
recreate, upload, wait_status, wait_until)
|
||||
|
||||
FAULT_ENV = {"WORKER_FAULT_INJECTION": "1", "JOB_RETRY_BASE_SECONDS": "1", "JOB_RETRY_MAX_SECONDS": "8"}
|
||||
|
||||
|
||||
def inspect_until(att_id, pred, timeout=60, what="state"):
|
||||
return wait_until(lambda: (lambda i: i if pred(i) else None)(ops("inspect", att_id)), timeout, 1, what)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("worker faults, retries, failed registry, replay, DLQ")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
recreate("worker", FAULT_ENV)
|
||||
log.step("workers recreated with fault injection", env=FAULT_ENV)
|
||||
report = {}
|
||||
try:
|
||||
# --- крахи процесса в разных окнах -------------------------------------------------
|
||||
for point in ("crash-after-claim", "crash-after-s3-put", "crash-after-commit"):
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "fault-%s.png" % point)
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=90)
|
||||
check(ready["status"] == "ready", point + ": not ready")
|
||||
if point == "crash-after-commit":
|
||||
# ready уже был зафиксирован; redelivery после рестарта -> no-op ack.
|
||||
inspect_until(att["id"], lambda i: "duplicate_ignored" in events(i), 60, "redelivery no-op")
|
||||
compose("exec", "-T", "janitor", "python", "/app/src/janitor.py", "--once")
|
||||
info = ops("inspect", att["id"])
|
||||
inv = invariants(info)
|
||||
check(inv["variants_ok"] and inv["final_objects_ok"] and not inv["staging_left"], point + ": invariants")
|
||||
report[point] = {"attachment_id": att["id"], "events": events(info), "invariants": inv}
|
||||
log.step(point, events=events(info), invariants=inv)
|
||||
ids = compose("ps", "-q", "worker").stdout.split()
|
||||
rc = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.RestartCount}} {{.State.Status}}"] + ids,
|
||||
capture_output=True, text=True).stdout.split("\n")
|
||||
log.step("worker containers after crashes (restart: unless-stopped)", containers=[x for x in rc if x])
|
||||
|
||||
# --- временные ошибки: backoff + jitter ---------------------------------------------
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "fault-transient-2.png")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=90)
|
||||
check(ready["status"] == "ready", "transient-2 not ready")
|
||||
info = ops("inspect", att["id"])
|
||||
delays = [e["detail"]["delay_seconds"] for e in info["events"] if e["event"] == "retry_scheduled"]
|
||||
claims = [e["at"] for e in info["events"] if e["event"] == "claimed"]
|
||||
bounds = [[0.5 * min(8, 2 ** (n - 1)), min(8, 2 ** (n - 1))] for n in (1, 2)]
|
||||
check(len(delays) == 2 and all(lo <= d <= hi for d, (lo, hi) in zip(delays, bounds)), "backoff bounds")
|
||||
inv = invariants(info)
|
||||
check(inv["attempt"] == 3 and inv["variants_ok"], "transient-2 attempts")
|
||||
report["transient-2"] = {"attachment_id": att["id"], "delays": delays, "bounds": bounds, "claims_at": claims,
|
||||
"invariants": inv}
|
||||
log.step("transient-2: retried with backoff", delays=delays, bounds=bounds, invariants=inv)
|
||||
|
||||
# --- исчерпание попыток -> failed -> replay ----------------------------------------
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "fault-transient-always.png")
|
||||
failed = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=120)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "expected retry_exhausted")
|
||||
r409 = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
|
||||
m409 = c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice,
|
||||
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "f-" + att["id"]})
|
||||
registry = ops("failed")
|
||||
in_registry = [r for r in registry["failed"] if r["attachment_id"] == att["id"]]
|
||||
check(in_registry and in_registry[0]["replayable"], "failed registry")
|
||||
info = ops("inspect", att["id"])
|
||||
log.step("transient-always: failed after max attempts", error_code=failed["error_code"],
|
||||
attempts=info["jobs"][0]["attempt"], content=r409["status"], attach=m409["status"],
|
||||
registry_entry=in_registry[0])
|
||||
dry = ops("replay", att["id"], "--dry-run")
|
||||
rep = ops("replay", att["id"], "--reason", "test: S3 restored")
|
||||
check(rep["replay"][0]["result"] == "replayed", "replay")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=60)
|
||||
check(ready["status"] == "ready", "not ready after replay")
|
||||
again = ops("replay", att["id"])
|
||||
check(again["replay"][0]["result"] == "refused_status_ready", "replay of ready must be refused")
|
||||
info = ops("inspect", att["id"])
|
||||
inv = invariants(info)
|
||||
check(inv["variants_ok"] and inv["final_objects_ok"], "replay invariants")
|
||||
report["transient-always+replay"] = {"attachment_id": att["id"], "dry_run": dry["replay"][0]["result"],
|
||||
"replay": rep["replay"][0]["result"],
|
||||
"second_replay": again["replay"][0]["result"],
|
||||
"replay_count": info["jobs"][0]["replay_count"],
|
||||
"events": events(info), "invariants": inv}
|
||||
log.step("replay -> ready; replay of ready refused", **report["transient-always+replay"])
|
||||
|
||||
# --- подмена staging: постоянная ошибка без повторов --------------------------------
|
||||
compose("stop", "worker")
|
||||
att = upload(c, alice, chat, png(50, 40), "tamper.png")
|
||||
info = ops("inspect", att["id"])
|
||||
key = info["attachment"]["staging_key"]
|
||||
compose("--profile", "tools", "run", "--rm", "-T", "checks", "/app/student-tests/s3_tamper.py", key)
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "worker", env=FAULT_ENV)
|
||||
failed = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=60)
|
||||
info = ops("inspect", att["id"])
|
||||
check(failed["error_code"] == "staging_corrupted" and info["jobs"][0]["attempt"] == 1, "tamper -> permanent")
|
||||
report["staging-tamper"] = {"attachment_id": att["id"], "error_code": failed["error_code"],
|
||||
"attempts": info["jobs"][0]["attempt"], "events": events(info)}
|
||||
log.step("tampered staging -> failed without retries", **report["staging-tamper"])
|
||||
|
||||
# --- poison message -> DLQ ----------------------------------------------------------
|
||||
before = queues()["attachments.dlq"]["messages"]
|
||||
ops("publish-raw", json.dumps({"schema_version": 1, "hello": "not a job"}))
|
||||
q = wait_until(lambda: (lambda x: x if x["messages"] > before else None)(queues()["attachments.dlq"]),
|
||||
30, what="message in DLQ")
|
||||
listed = ops("dlq")
|
||||
purged = ops("dlq", "--purge-invalid")
|
||||
# Счётчики quorum-очереди в rabbitmqctl обновляются с задержкой в секунды.
|
||||
after = wait_until(lambda: (lambda n: "0" if n == 0 else None)(queues()["attachments.dlq"]["messages"]),
|
||||
20, what="empty DLQ") and 0
|
||||
report["poison"] = {"dlq_before": before, "dlq_after_publish": q["messages"], "listed": listed["dlq_messages"],
|
||||
"purged": [m["action"] for m in purged["dlq_messages"]], "dlq_after_purge": after}
|
||||
log.step("poison message dead-lettered and purged", **report["poison"])
|
||||
check(after == 0, "DLQ not empty after purge")
|
||||
finally:
|
||||
recreate("worker")
|
||||
log.step("workers restored to .env configuration")
|
||||
log.save(args.output, results=report)
|
||||
print("PASS: worker crashes, backoff, retry_exhausted -> replay, staging tamper, DLQ")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Уровень 3, сценарий защиты: worker остановлен -> upload 202 -> сообщение с вложением ->
|
||||
рестарт API и брокера (volumes сохраняются) -> worker запущен -> ready -> повторная доставка.
|
||||
|
||||
python3 student-tests/worker_outage.py --output evidence/worker-outage.json
|
||||
|
||||
Проверяется:
|
||||
* 202 queued при остановленных worker; GET queued; content и thumbnail -> 409;
|
||||
* сообщение с queued-вложением и обычное сообщение -> 201 (остальной API работает);
|
||||
* задание лежит в durable quorum-очереди (messages_ready=1) и переживает рестарт брокера;
|
||||
* после рестарта API и брокера и запуска worker вложение ready, thumbnail 256x160,
|
||||
оригинал побайтно совпадает;
|
||||
* повторная доставка (тот же job_id ещё раз в очередь) -> no-op, вариантов по-прежнему 3.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
|
||||
from lab5lib import (SAMPLE_PNG, Client, Log, check, compose, events, get_att, invariants, ops, queues,
|
||||
upload, wait_status, wait_until)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("worker outage -> restart api+broker -> worker start -> ready -> redelivery")
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
compose("stop", "worker")
|
||||
log.step("worker stopped", running=compose("ps", "-q", "--status", "running", "worker").stdout.split())
|
||||
before = queues()["attachments.process.v1"]
|
||||
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "outage.png")
|
||||
check(att["status"] == "queued", "expected queued")
|
||||
log.step("upload while worker is down", http=202, attachment_id=att["id"], status=att["status"])
|
||||
meta = get_att(c, bob, att["id"])
|
||||
r1 = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
|
||||
r2 = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], 409, actor=bob)
|
||||
log.step("metadata and content while queued", status=meta["status"], content=r1["status"],
|
||||
thumbnail=r2["status"], error_code=r1["json"]["error"]["code"])
|
||||
m1 = c.message(alice, chat, "", attachments=[att["id"]])["json"]
|
||||
m2 = c.message(bob, chat, "другие сообщения работают")["json"]
|
||||
log.step("messages while worker is down", with_queued_attachment=m1["attachment_ids"] == [att["id"]],
|
||||
plain_message_id=m2["id"])
|
||||
|
||||
q = wait_until(lambda: (lambda x: x if x["messages_ready"] >= before["messages_ready"] + 1 else None)(
|
||||
queues()["attachments.process.v1"]), 15, what="job message in queue")
|
||||
info = ops("inspect", att["id"])
|
||||
log.step("job is durable in broker", queue=q, outbox_published=info["outbox"][0]["published_at"] is not None,
|
||||
job_id=info["jobs"][0]["id"], job_status=info["jobs"][0]["status"])
|
||||
job_id = info["jobs"][0]["id"]
|
||||
|
||||
compose("restart", "api")
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "api")
|
||||
log.step("api restarted", status=get_att(c, alice, att["id"])["status"])
|
||||
compose("restart", "broker")
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "broker")
|
||||
q2 = queues()["attachments.process.v1"]
|
||||
check(q2["messages_ready"] >= 1, "job message lost after broker restart")
|
||||
log.step("broker restarted with volume", queue=q2, status=get_att(c, alice, att["id"])["status"])
|
||||
|
||||
compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "worker")
|
||||
log.step("worker started")
|
||||
ready = wait_status(c, bob, att["id"], {"ready", "failed"}, timeout=60)
|
||||
check(ready["status"] == "ready" and ready["error_code"] is None, "attachment not ready")
|
||||
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
|
||||
content = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
|
||||
tb = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"]
|
||||
check(content == SAMPLE_PNG, "original changed")
|
||||
check(hashlib.sha256(tb).hexdigest() == thumb["sha256"], "thumbnail checksum")
|
||||
log.step("ready after worker start", variants=[(v["name"], v["width"], v["height"]) for v in ready["variants"]],
|
||||
original_sha256_ok=True, thumbnail_bytes=len(tb))
|
||||
|
||||
# Повторная доставка: то же сообщение (тот же job_id) ещё раз в очередь.
|
||||
payload = {"schema_version": 1, "job_id": job_id, "type": "attachment.process.v1", "attachment_id": att["id"],
|
||||
"pipeline_version": 1, "attempt": 1, "created_at": "2026-11-13T00:00:00Z"}
|
||||
ops("publish-raw", json.dumps(payload))
|
||||
info = wait_until(lambda: (lambda i: i if "duplicate_ignored" in events(i) else None)(ops("inspect", att["id"])),
|
||||
30, interval=1, what="duplicate_ignored event")
|
||||
inv = invariants(info)
|
||||
check(inv["variants_ok"] and inv["final_objects_ok"] and not inv["staging_left"], "invariants violated")
|
||||
log.step("redelivery of the same job is a no-op", events=events(info), invariants=inv)
|
||||
after = get_att(c, bob, att["id"])
|
||||
check(after == ready, "metadata changed after redelivery")
|
||||
log.save(args.output, attachment_id=att["id"], job_id=job_id, events=info["events"])
|
||||
print("PASS: worker outage, api+broker restart, ready, duplicate delivery no-op")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user