forked from mtusi2026/mtusi2026lab7
7 — Т2302 — ебедев — на 5
This commit is contained in:
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказы объектного хранилища и согласованность S3 ↔ PostgreSQL (уровень 4).
|
||||
|
||||
ВНИМАНИЕ: тест останавливает/запускает контейнер s3 и поднимает профиль fault (api-fault, :8445).
|
||||
Volumes не удаляются. Команды переопределяются STOP_S3/START_S3/FAULT_UP/FAULT_DOWN.
|
||||
"""
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import shlex
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from common import (BASE_URL, DC, ROOT, Client, Failure, Suite, check, login, make_png, new_user, s3_admin, sh, sql,
|
||||
upload, wait_until)
|
||||
|
||||
FAULT_URL = os.environ.get("FAULT_BASE_URL", "https://127.0.0.1:8445")
|
||||
CMD = {"stop_s3": os.environ.get("STOP_S3", DC + " stop s3"),
|
||||
"start_s3": os.environ.get("START_S3", DC + " start s3"),
|
||||
"fault_up": os.environ.get("FAULT_UP", DC + " --profile fault up -d --no-deps --force-recreate api-fault"),
|
||||
"fault_down": os.environ.get("FAULT_DOWN", DC + " --profile fault stop api-fault")}
|
||||
c = Client(BASE_URL, timeout=15)
|
||||
s = Suite("object storage failures (" + BASE_URL + ")")
|
||||
alice = new_user(c, "sa"); login(c, alice)
|
||||
bob = new_user(c, "sb"); login(c, bob)
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
|
||||
body={"title": "storage", "member_ids": [alice["id"], bob["id"]]})["json"]
|
||||
UP = "/api/v1/chats/" + chat["id"] + "/attachments"
|
||||
|
||||
|
||||
def n_objects():
|
||||
"""lab5: загрузка пишет в staging/ (оригинал публикует worker в originals/ после обработки)."""
|
||||
return len(s3_admin("ls", "staging/").splitlines())
|
||||
|
||||
|
||||
def n_intents():
|
||||
return int(sql("SELECT count(*) FROM upload_intents")[0])
|
||||
|
||||
|
||||
@s.case("bucket is private outside API: anonymous GET/LIST/PUT denied, API key limited")
|
||||
def _():
|
||||
att, _ = upload(c, alice, chat)
|
||||
c.wait_ready(alice, att) # оригинал опубликован в originals/
|
||||
key = sql("SELECT object_key FROM attachments WHERE id = '%s'" % att["id"])[0]
|
||||
status = s3_admin("anon-get", key)
|
||||
check(status in ("401", "403"), "anonymous GET of existing object returned " + status)
|
||||
out = subprocess.run(shlex.split(DC + " exec -T api python -m messenger s3-check"), cwd=ROOT,
|
||||
capture_output=True, text=True, timeout=60)
|
||||
lines = [ln for ln in out.stdout.splitlines() if ln.startswith(("PASS", "FAIL"))]
|
||||
check(out.returncode == 0 and lines and all(ln.startswith("PASS") for ln in lines), "s3-check failed: " + out.stdout[-400:])
|
||||
return "anon GET %s; s3-check %d/%d PASS" % (status, len(lines), len(lines))
|
||||
|
||||
|
||||
@s.case("S3 down: upload/download 503 fast, text messages and readiness keep working")
|
||||
def _():
|
||||
att, data = upload(c, alice, chat)
|
||||
c.wait_ready(alice, att)
|
||||
sh(CMD["stop_s3"])
|
||||
try:
|
||||
t = time.monotonic()
|
||||
c.call("POST", UP + "?filename=a.png", 503, actor=alice, raw=make_png(), headers={"Content-Type": "image/png"})
|
||||
took_up = time.monotonic() - t
|
||||
t = time.monotonic()
|
||||
c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 503, actor=bob)
|
||||
took_down = time.monotonic() - t
|
||||
c.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment") # метаданные — из БД
|
||||
c.message(alice, chat, "S3 лежит, текст работает")
|
||||
c.message(alice, chat, "", attachments=[att["id"]]) # ссылка на готовое вложение
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
check(took_up < 5 and took_down < 5, "503 too slow: %.2f / %.2f s" % (took_up, took_down))
|
||||
finally:
|
||||
sh(CMD["start_s3"])
|
||||
# После старта SeaweedFS чтение возвращается раньше записи (прогрев топологии ~15 с): ждём оба.
|
||||
slow = Client(BASE_URL, timeout=60)
|
||||
t0 = time.monotonic()
|
||||
wait_until(lambda: slow.call("GET", "/api/v1/attachments/" + att["id"] + "/content", [200, 503], actor=bob)["status"] == 200,
|
||||
timeout=90)
|
||||
read_back = time.monotonic() - t0
|
||||
wait_until(lambda: slow.call("POST", UP + "?filename=b.png", [202, 503], actor=alice, raw=make_png(),
|
||||
headers={"Content-Type": "image/png"})["status"] == 202, timeout=90)
|
||||
write_back = time.monotonic() - t0
|
||||
check(c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=bob)["bytes"] == data, "data changed")
|
||||
return "503 in %.2fs/%.2fs; after start: reads %.1fs, writes %.1fs" % (took_up, took_down, read_back, write_back)
|
||||
|
||||
|
||||
@s.case("interrupted upload: no object and no intent left behind")
|
||||
def _():
|
||||
objects, intents = n_objects(), n_intents()
|
||||
png = make_png(300, 300)
|
||||
u = urlsplit(BASE_URL)
|
||||
head = ("POST %s?filename=cut.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\nContent-Type: image/png\r\n"
|
||||
"Content-Length: %d\r\n\r\n" % (UP, u.netloc, alice["token"], len(png))).encode()
|
||||
for cut in (len(png) // 3, len(png) - 1):
|
||||
sock = socket.create_connection((u.hostname, u.port or 80), timeout=5)
|
||||
sock.sendall(head + png[:cut])
|
||||
time.sleep(0.3)
|
||||
sock.close() # клиент пропал посреди тела
|
||||
wait_until(lambda: n_intents() <= intents, timeout=30)
|
||||
check(n_objects() == objects, "objects changed: %d -> %d" % (objects, n_objects()))
|
||||
return "objects %d, intents %d — unchanged" % (objects, intents)
|
||||
|
||||
|
||||
@s.case("uploads rejected at the very end (truncated PNG) leave no staging object (race regression)")
|
||||
def _():
|
||||
# Ошибка обнаруживается только в finish(), после последнего байта. Раньше S3 мог зафиксировать
|
||||
# объект уже после компенсирующего DELETE (нашёл инвариант I7); теперь последний кусок
|
||||
# придерживается до проверки, и PUT обрывается раньше Content-Length.
|
||||
before = n_objects()
|
||||
png = make_png(20, 20)
|
||||
for i in range(30):
|
||||
c.call("POST", UP + "?filename=trunc%d.png" % i, 415, actor=alice, raw=png[:-12], headers={"Content-Type": "image/png"})
|
||||
time.sleep(3)
|
||||
after = n_objects()
|
||||
check(after == before, "staging objects %d -> %d" % (before, after))
|
||||
return "30 × 415 at finish(); staging objects %d → %d" % (before, after)
|
||||
|
||||
|
||||
@s.case("crash between staging PUT and DB COMMIT: intent recorded, janitor removes object after grace")
|
||||
def _():
|
||||
os.environ["API_FAULT_INJECT"] = "crash_after_s3_put" # точка отказа api-fault для этого сценария
|
||||
sh(CMD["fault_up"], timeout=120)
|
||||
try:
|
||||
fc = Client(FAULT_URL, timeout=10)
|
||||
wait_until(lambda: fc.call("GET", "/health/ready", [200, 503])["status"] == 200, timeout=90)
|
||||
objects = n_objects()
|
||||
try:
|
||||
upload(fc, alice, chat, make_png(50, 50))
|
||||
raise Failure("upload to crashing replica unexpectedly succeeded")
|
||||
except Failure as exc:
|
||||
if "unexpectedly" in str(exc):
|
||||
raise
|
||||
rows = sql("SELECT object_key FROM upload_intents WHERE created_at > clock_timestamp() - interval '1 minute'")
|
||||
check(rows, "no intent recorded before S3 PUT")
|
||||
key = rows[-1]
|
||||
check(s3_admin("sha", key) != "-", "object must exist after PUT (crash happened after it)")
|
||||
check(sql("SELECT count(*) FROM attachments WHERE staging_key = '%s'" % key) == ["0"], "metadata committed?!")
|
||||
t = time.monotonic()
|
||||
wait_until(lambda: s3_admin("sha", key) == "-" and
|
||||
sql("SELECT count(*) FROM upload_intents WHERE object_key = '%s'" % key) == ["0"], timeout=90, interval=2)
|
||||
check(n_objects() == objects, "untracked objects remain")
|
||||
return "orphan %s… removed %.1fs after crash (grace 10 s)" % (key[:20], time.monotonic() - t)
|
||||
finally:
|
||||
sh(CMD["fault_down"], timeout=120)
|
||||
os.environ.pop("API_FAULT_INJECT", None)
|
||||
|
||||
|
||||
s.run()
|
||||
Reference in New Issue
Block a user