lab 4 na 4

This commit is contained in:
2026-11-05 13:52:11 +03:00
parent 14166003b8
commit f6292ac308
48 changed files with 2255 additions and 183 deletions
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
[ -f .env ] || { cp .env.example .env; echo ".env создан из .env.example"; }
mkdir -p secrets
[ -f secrets/postgres_password.txt ] || printf '%s' "$(grep '^POSTGRES_PASSWORD=' .env | cut -d= -f2-)" > secrets/postgres_password.txt
[ -f secrets/database_url.txt ] || printf '%s' "$(grep '^DATABASE_URL=' .env | cut -d= -f2-)" > secrets/database_url.txt
./scripts/gen-s3-secrets.sh
chmod 644 secrets/*
echo "секреты готовы"
+53
View File
@@ -0,0 +1,53 @@
import base64, hashlib, json, struct, subprocess, sys, time, urllib.request, uuid, zlib
BASE = "http://localhost:8080"; PWD = "correct-horse-battery-staple"
def call(method, path, body=None, headers=None):
req = urllib.request.Request(BASE + path, data=body, method=method, headers=headers or {})
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, r.headers, r.read() # r.headers нечувствителен к регистру
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
png = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 16, 16, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(b"".join(b"\x00" + bytes([i, 80, 200]) * 16 for i in range(16))))
+ chunk(b"IEND", b""))
j = {"Content-Type": "application/json"}
name = "af_" + uuid.uuid4().hex[:8]
_, _, raw = call("POST", "/api/v1/users", json.dumps({"username": name, "display_name": "a", "password": PWD}).encode(), j)
user = json.loads(raw)
_, _, raw = call("POST", "/api/v1/auth/sessions", None,
{"Authorization": "Basic " + base64.b64encode(f"{name}:{PWD}".encode()).decode()})
auth = {"Authorization": "Bearer " + json.loads(raw)["token"]}
_, _, raw = call("POST", "/api/v1/chats", json.dumps({"title": "x", "member_ids": [user["id"]]}).encode(), {**j, **auth})
chat = json.loads(raw)
_, hdr, raw = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=f.png", png,
{"Content-Type": "image/png", **auth})
att = json.loads(raw)
inst = hdr.get("X-Instance-Id")
print("uploaded via instance", inst, "sha256", att["sha256"])
ids = subprocess.run(["docker", "compose", "ps", "-q", "api"], capture_output=True, text=True).stdout.split()
target = next((i for i in ids if subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}}", i],
capture_output=True, text=True).stdout.strip() == inst), None)
if not target:
sys.exit(f"container for instance {inst} not found")
subprocess.run(["docker", "stop", "-t", "8", target], capture_output=True)
print("stopped", inst)
time.sleep(4)
seen = set()
for _ in range(10):
_, h, data = call("GET", f"/api/v1/attachments/{att['id']}/content", None, auth)
seen.add(h.get("X-Instance-Id"))
assert hashlib.sha256(data).hexdigest() == att["sha256"], "SHA-256 mismatch"
print("downloaded 10x via", sorted(seen), "- sha256 matches; stopped instance served:", inst in seen)
subprocess.run(["docker", "compose", "up", "-d", "--no-recreate", "api"], capture_output=True)
print("restored")
+131
View File
@@ -0,0 +1,131 @@
import base64, hashlib, json, os, random, struct, sys, urllib.error, urllib.request, uuid, zlib
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
PWD = "correct-horse-battery-staple"
LIMIT = 10 * 1024 * 1024
def call(method, path, body=None, headers=None, token=None, basic=None):
h = dict(headers or {})
if token: h["Authorization"] = "Bearer " + token
if basic: h["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
req = urllib.request.Request(BASE + path, data=body, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, r.headers, r.read()
except urllib.error.HTTPError as e:
return e.code, e.headers, e.read()
def jcall(method, path, obj, token=None, key=None):
h = {"Content-Type": "application/json"}
if key: h["Idempotency-Key"] = key
st, _, raw = call(method, path, json.dumps(obj).encode(), h, token)
return st, (json.loads(raw) if raw else None)
def chunk(t, d):
c = struct.pack(">I", len(d)) + t + d
return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
def png(width, height, idat=None):
raw = idat if idat is not None else b"".join(b"\x00" + b"\x10\x80\xf0" * width for _ in range(height))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw) if idat is None else raw) + chunk(b"IEND", b""))
def noise_png(target_bytes):
w = 1000
rows = max(1, target_bytes // (3 * w + 1))
raw = b"".join(b"\x00" + os.urandom(3 * w) for _ in range(rows))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, rows, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b""))
ok = True
def check(name, got, want):
global ok
good = got in want if isinstance(want, set) else got == want
ok &= good
print("PASS" if good else "FAIL", name, "->", got)
def register(prefix):
name = f"{prefix}_{uuid.uuid4().hex[:8]}"
_, u = jcall("POST", "/api/v1/users", {"username": name, "display_name": prefix, "password": PWD})
_, _, raw = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}")
return u, json.loads(raw)["token"]
alice, ta = register("alice")
bob, tb = register("bob")
carol, tc = register("carol")
_, chat1 = jcall("POST", "/api/v1/chats", {"title": "c1", "member_ids": [alice["id"], bob["id"]]}, ta)
_, chat2 = jcall("POST", "/api/v1/chats", {"title": "c2", "member_ids": [alice["id"]]}, ta)
up = lambda chat, data, ct="image/png", fn="a.png", tok=None: call(
"POST", f"/api/v1/chats/{chat}/attachments?filename={fn}", data, {"Content-Type": ct}, tok or ta)
msg = lambda chat, obj, tok=None, key=None: jcall(
"POST", f"/api/v1/chats/{chat}/messages", obj, tok or ta, key or uuid.uuid4().hex)
good_png = png(8, 8)
st, _, raw = up(chat1["id"], good_png)
check("валидный PNG", st, 201)
att = json.loads(raw)
check("sha256 в ответе", att["sha256"], hashlib.sha256(good_png).hexdigest())
check("status/variants/error_code", (att["status"], att["variants"], att["error_code"]), ("ready", [], None))
st, hdr, data = call("GET", f"/api/v1/attachments/{att['id']}/content", token=tb)
check("скачивание участником: статус", st, 200)
check("скачивание: байты совпадают", hashlib.sha256(data).hexdigest(), att["sha256"])
check("скачивание: Content-Type", hdr.get("Content-Type"), "image/png")
check("метаданные: посторонний", call("GET", f"/api/v1/attachments/{att['id']}", token=tc)[0], 404)
check("байты: посторонний", call("GET", f"/api/v1/attachments/{att['id']}/content", token=tc)[0], 404)
check("без токена", call("GET", f"/api/v1/attachments/{att['id']}/content")[0], 401)
check("неизвестный id", call("GET", f"/api/v1/attachments/{uuid.uuid4()}", token=ta)[0], 404)
check("id не UUID", call("GET", "/api/v1/attachments/not-a-uuid", token=ta)[0], 400)
check("variant=thumbnail", call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", token=ta)[0], {400, 404})
check("загрузка в чужой чат", up(chat1["id"], good_png, tok=tc)[0], 404)
check("слишком большой (Content-Length)", up(chat1["id"], good_png[:8] + b"\0" * (LIMIT + 1))[0], 413)
check("слишком много пикселей (8000x8000)", up(chat1["id"], png(8000, 8000, idat=b"\x00"))[0], 413)
check("повреждённый PNG", up(chat1["id"], good_png[:-20])[0], 415)
check("PNG под видом JPEG", up(chat1["id"], good_png, ct="image/jpeg")[0], 415)
check("текст под видом PNG", up(chat1["id"], b"hello, not an image")[0], 415)
check("пустое тело", up(chat1["id"], b"")[0], 415)
check("image/gif", up(chat1["id"], b"GIF89a....", ct="image/gif")[0], 415)
for label, fn in [("слэш", "a%2Fb.png"), ("обратный слэш", "a%5Cb.png"), ("NUL", "a%00b.png"),
("управляющий символ", "a%0Ab.png"), ("256 символов", "a" * 256), ("пустое", "")]:
check(f"filename: {label}", up(chat1["id"], good_png, fn=fn)[0], 400)
st, _, _ = call("POST", f"/api/v1/chats/{chat1['id']}/attachments", good_png, {"Content-Type": "image/png"}, ta)
check("filename отсутствует", st, 400)
check("валидный большой файл (~9 МиБ)", up(chat1["id"], noise_png(9 * 1024 * 1024))[0], 201)
# ---- сообщения с вложениями
st, m1 = msg(chat1["id"], {"text": "", "attachment_ids": [att["id"]]}, key="k-" + uuid.uuid4().hex)
check("пустой текст с вложением", st, 201)
check("в ответе attachment_ids", m1["attachment_ids"], [att["id"]])
check("пустой текст без вложений", msg(chat1["id"], {"text": ""})[0], 400)
check("вложение из другого чата (я участник обоих)", msg(chat2["id"], {"text": "x", "attachment_ids": [att["id"]]})[0], 404)
check("неизвестное вложение", msg(chat1["id"], {"text": "x", "attachment_ids": [str(uuid.uuid4())]})[0], 404)
check("attachment_ids не UUID", msg(chat1["id"], {"text": "x", "attachment_ids": ["zzz"]})[0], 400)
check("дубликаты в attachment_ids", msg(chat1["id"], {"text": "x", "attachment_ids": [att["id"], att["id"]]})[0], 400)
check("11 вложений", msg(chat1["id"], {"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]})[0], 400)
check("посторонний шлёт чужое вложение", msg(chat1["id"], {"text": "x", "attachment_ids": [att["id"]]}, tok=tc)[0], 404)
_, page = jcall("GET", f"/api/v1/chats/{chat1['id']}/messages", None, ta)
st, _, raw = call("GET", f"/api/v1/chats/{chat1['id']}/messages", token=bob and tb)
items = json.loads(raw)["items"]
check("история содержит attachment_ids", any(i["attachment_ids"] == [att["id"]] for i in items), True)
# ---- идемпотентность с вложениями
k = "idem-" + uuid.uuid4().hex
s1, a = msg(chat1["id"], {"text": "same", "attachment_ids": []}, key=k)
s2, b = msg(chat1["id"], {"text": "same"}, key=k)
check("attachment_ids отсутствует == []", (s1, s2, a["id"] == b["id"]), (201, 201, True))
k2 = "idem-" + uuid.uuid4().hex
msg(chat1["id"], {"text": "t", "attachment_ids": [att["id"]]}, key=k2)
check("тот же ключ, другой список вложений", msg(chat1["id"], {"text": "t"}, key=k2)[0], 409)
sys.exit(0 if ok else 1)
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
set -eu
run() {
who="$1"; shift
docker run --rm --network mtusi2026lab4_s3access -v "$PWD/secrets:/s:ro" -e AWS_DEFAULT_REGION=us-east-1 \
--entrypoint /bin/sh amazon/aws-cli:2.39.1 -c \
"AWS_ACCESS_KEY_ID=\$(cat /s/s3_${who}_access_key.txt) AWS_SECRET_ACCESS_KEY=\$(cat /s/s3_${who}_secret_key.txt) aws --endpoint-url http://s3-proxy:8333 $*" >/dev/null 2>&1
}
expect() {
want="$1"; desc="$2"; shift 2
if run "$@"; then got=ok; else got=deny; fi
[ "$got" = "$want" ] && echo "PASS $desc ($got)" || echo "FAIL $desc: ожидалось $want, получено $got"
}
expect ok "api: список объектов бакета" api "s3api list-objects-v2 --bucket attachments --max-keys 1"
expect ok "api: запись объекта" api "s3 cp /etc/hostname s3://attachments/attachments/probe/rights-check"
expect ok "api: удаление объекта" api "s3 rm s3://attachments/attachments/probe/rights-check"
expect deny "api: создание другого бакета" api "s3api create-bucket --bucket other-bucket"
expect deny "api: удаление бакета" api "s3api delete-bucket --bucket attachments"
expect ok "admin: создание бакета (bootstrap)" admin "s3api head-bucket --bucket attachments"
echo "--- без подписи (anonymous)"
for url in "http://s3-proxy:8333/attachments/" "http://s3-proxy:8333/attachments/attachments/x/y"; do
code=$(docker run --rm --network mtusi2026lab4_s3access curlimages/curl -s -o /dev/null -w '%{http_code}' "$url")
case "$code" in 401|403) echo "PASS anonymous $url -> $code";; *) echo "FAIL anonymous $url -> $code";; esac
done
echo "--- консоли управления из контейнера api (ожидается недоступность)"
for target in seaweedfs:9333 seaweedfs:8888 seaweedfs:8080 s3-proxy:9333 s3-proxy:8888; do
if docker compose exec -T api wget -q -O /dev/null -T 3 "http://$target/" >/dev/null 2>&1; then
echo "FAIL api -> $target доступен"
else
echo "PASS api -> $target недоступен"
fi
done
+18
View File
@@ -0,0 +1,18 @@
#!/bin/sh
set -eu
mkdir -p secrets
rnd() { openssl rand -hex "$1"; }
for f in s3_api_access_key s3_api_secret_key s3_admin_access_key s3_admin_secret_key; do
[ -f "secrets/$f.txt" ] || { [ "${f%access_key}" != "$f" ] && printf '%s' "AK$(rnd 8)" || printf '%s' "$(rnd 20)"; } > "secrets/$f.txt"
done
cat > secrets/s3_config.json <<EOF
{
"identities": [
{"name": "api", "credentials": [{"accessKey": "$(cat secrets/s3_api_access_key.txt)", "secretKey": "$(cat secrets/s3_api_secret_key.txt)"}],
"actions": ["Read:attachments", "Write:attachments", "List:attachments"]},
{"name": "admin", "credentials": [{"accessKey": "$(cat secrets/s3_admin_access_key.txt)", "secretKey": "$(cat secrets/s3_admin_secret_key.txt)"}],
"actions": ["Admin", "Read", "Write", "List"]}
]
}
EOF
chmod 600 secrets/*
+84
View File
@@ -0,0 +1,84 @@
import json, os, subprocess, struct, sys, threading, time, urllib.request, urllib.error, uuid, zlib, base64
BASE = "http://localhost:8080"; PWD = "correct-horse-battery-staple"
SIZE = int(sys.argv[1]) if len(sys.argv) > 1 else 9 * 1024 * 1024
WORKERS, DURATION = 12, 20
def chunk(t, d):
c = struct.pack(">I", len(d)) + t + d
return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
def noise_png(target):
w = 1000
rows = max(1, target // (3 * w + 1))
raw = b"".join(b"\x00" + os.urandom(3 * w) for _ in range(rows))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, rows, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw, 0)) + chunk(b"IEND", b""))
def call(method, path, body=None, headers=None):
req = urllib.request.Request(BASE + path, data=body, method=method, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=60) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
name = "mem_" + uuid.uuid4().hex[:8]
_, raw = call("POST", "/api/v1/users", json.dumps({"username": name, "display_name": "m", "password": PWD}).encode(),
{"Content-Type": "application/json"})
user = json.loads(raw)
_, raw = call("POST", "/api/v1/auth/sessions", None,
{"Authorization": "Basic " + base64.b64encode(f"{name}:{PWD}".encode()).decode()})
tok = json.loads(raw)["token"]
_, raw = call("POST", "/api/v1/chats", json.dumps({"title": "m", "member_ids": [user["id"]]}).encode(),
{"Content-Type": "application/json", "Authorization": "Bearer " + tok})
chat = json.loads(raw)
data = noise_png(SIZE)
print(f"payload: {len(data)} bytes, workers={WORKERS}, duration={DURATION}s")
statuses, lock, stop = {}, threading.Lock(), threading.Event()
def worker():
while not stop.is_set():
st, _ = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=m.png", data,
{"Content-Type": "image/png", "Authorization": "Bearer " + tok})
with lock:
statuses[st] = statuses.get(st, 0) + 1
def mib(s):
n, unit = float(s[:-3]) if s.endswith("iB") else 0, s[-3:]
return n * {"KiB": 1 / 1024, "MiB": 1, "GiB": 1024}.get(unit, 0)
peaks = {}
def sampler():
while not stop.is_set():
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
capture_output=True, text=True).stdout
for line in out.splitlines():
parts = line.split()
if len(parts) >= 2 and "-api-" in parts[0]:
peaks[parts[0]] = max(peaks.get(parts[0], 0), mib(parts[1]))
base = {}
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}} {{.MemUsage}}"],
capture_output=True, text=True).stdout
for line in out.splitlines():
p = line.split()
if len(p) >= 2 and "-api-" in p[0]:
base[p[0]] = mib(p[1])
ths = [threading.Thread(target=worker) for _ in range(WORKERS)] + [threading.Thread(target=sampler)]
t0 = time.time()
[t.start() for t in ths]
time.sleep(DURATION)
stop.set()
[t.join() for t in ths]
print(json.dumps({"payload_bytes": len(data), "statuses": statuses, "idle_mib": base,
"peak_mib": {k: round(v, 1) for k, v in peaks.items()}, "limit_mib": 256}, indent=2))
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p evidence
count() { ./scripts/s3-admin.sh s3 ls s3://attachments/ --recursive | wc -l | tr -d ' '; }
psql_() { docker compose exec -T postgres sh -c "psql -U \"\$POSTGRES_USER\" -d \"\$POSTGRES_DB\" -t -A -c \"$1\""; }
trap 'psql_ "ALTER TABLE attachments DROP CONSTRAINT IF EXISTS inject_fail;" >/dev/null 2>&1 || true' EXIT
ORPHAN=attachments/00000000-0000-4000-8000-000000000000/11111111-1111-4111-8111-111111111111
{
echo "== A: PUT прошёл, запись метаданных упала -> компенсация"
before=$(count); echo "objects before: $before"
psql_ "ALTER TABLE attachments ADD CONSTRAINT inject_fail CHECK (false) NOT VALID;"
python3 scripts/upload_tools.py ok
sleep 1
docker compose logs api --since 1m | grep "metadata insert failed" | tail -1 || true
docker compose logs api --since 1m | grep "compensation delete failed" || echo "(сбоев компенсации нет)"
psql_ "ALTER TABLE attachments DROP CONSTRAINT inject_fail;"
after=$(count); echo "objects after: $after"
[ "$before" = "$after" ] && echo "PASS: объект не остался" || echo "FAIL: число объектов изменилось"
} 2>&1 | tee evidence/orphans-A.txt
{
echo "== D: обрыв загрузки клиентом (заявлено 5 МБ, отправлено 300 КБ)"
before=$(count); echo "objects before: $before"
python3 scripts/upload_tools.py abort
sleep 3
after=$(count); echo "objects after: $after"
[ "$before" = "$after" ] && echo "PASS: в S3 ничего не записано" || echo "FAIL: число объектов изменилось"
for i in 1 2; do docker compose exec -T --index $i api sh -c "echo временных файлов в реплике $i: \$(ls /tmp | wc -l)"; done
} 2>&1 | tee evidence/orphans-D.txt
{
echo "== B: объект без записи в БД (имитация падения между PUT и INSERT)"
./scripts/s3-admin.sh s3api put-object --bucket attachments --key "$ORPHAN" >/dev/null
sleep 2
echo "-- grace=1h: свежий объект не трогается"
docker compose run --rm -T reconciler ./reconcile -dry-run -grace=1h 2>&1 | grep -E "orphan|reconcile:" || true
echo "-- grace=1s, dry-run: найден, но не удалён"
docker compose run --rm -T reconciler ./reconcile -dry-run -grace=1s 2>&1 | grep -E "orphan|reconcile:" || true
./scripts/s3-admin.sh s3 ls s3://attachments/ --recursive | grep -c 1111 || true
echo "-- grace=1s, реальный запуск: удалён"
docker compose run --rm -T reconciler ./reconcile -grace=1s 2>&1 | grep -E "orphan|reconcile:" || true
./scripts/s3-admin.sh s3 ls s3://attachments/ --recursive | grep 1111 || echo "PASS: сирота удалён"
} 2>&1 | tee evidence/orphans-B.txt
{
echo "== C: объект потерян, метаданные остались"
key=$(psql_ "SELECT object_key FROM attachments ORDER BY created_at LIMIT 1;")
echo "удаляем объект $key (тестовое вложение)"
./scripts/s3-admin.sh s3 rm "s3://attachments/$key" >/dev/null
docker compose run --rm -T reconciler ./reconcile -dry-run -grace=1s -check-missing 2>&1 | grep -E "MISSING|reconcile:" || true
} 2>&1 | tee evidence/orphans-C.txt
+8 -2
View File
@@ -1,4 +1,10 @@
#!/bin/sh
set -eu
docker compose restart postgres redis
docker compose restart api lb
cd "$(dirname "$0")/.."
healthy() {
[ "$(docker compose ps -q "$@" | xargs docker inspect -f '{{.State.Health.Status}}' | grep -c '^healthy$')" = "$#" ]
}
docker compose restart postgres redis seaweedfs
until healthy postgres redis seaweedfs; do sleep 1; done
docker compose restart s3-proxy
docker compose restart api lb
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
docker run --rm --network mtusi2026lab4_s3access -v "$PWD/secrets:/s:ro" -e AWS_DEFAULT_REGION=us-east-1 \
--entrypoint /bin/sh amazon/aws-cli:2.39.1 -c \
'AWS_ACCESS_KEY_ID=$(cat /s/s3_admin_access_key.txt) AWS_SECRET_ACCESS_KEY=$(cat /s/s3_admin_secret_key.txt) exec aws --endpoint-url http://s3-proxy:8333 "$@"' sh "$@"
+57
View File
@@ -0,0 +1,57 @@
import base64, hashlib, json, struct, subprocess, time, urllib.error, urllib.request, uuid, zlib
BASE = "http://localhost:8080"; PWD = "correct-horse-battery-staple"
def call(method, path, body=None, headers=None, token=None, basic=None, timeout=10):
h = dict(headers or {})
if token: h["Authorization"] = "Bearer " + token
if basic: h["Authorization"] = "Basic " + base64.b64encode(basic.encode()).decode()
req = urllib.request.Request(BASE + path, data=body, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def jcall(method, path, obj, token=None):
st, raw = call(method, path, json.dumps(obj).encode(), {"Content-Type": "application/json"}, token)
return st, json.loads(raw or b"null")
def tiny_png():
def chunk(t, d):
c = struct.pack(">I", len(d)) + t + d
return c + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
raw = b"".join(b"\x00" + b"\xff\x00\x00" * 8 for _ in range(8))
return (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
name = "pr_" + uuid.uuid4().hex[:8]
_, user = jcall("POST", "/api/v1/users", {"username": name, "display_name": "probe", "password": PWD})
st, raw = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}")
tok = json.loads(raw)["token"]
_, chat = jcall("POST", "/api/v1/chats", {"title": "probe", "member_ids": [user["id"]]}, tok)
png = tiny_png()
st, raw = call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=probe.png", png,
{"Content-Type": "image/png"}, tok)
att = json.loads(raw)
print("upload:", st, att.get("id"))
want = hashlib.sha256(png).hexdigest()
t0 = time.time()
subprocess.run(["docker", "compose", "restart", "seaweedfs"], capture_output=True)
print(f"restart seaweedfs returned after {time.time() - t0:.1f}s")
while time.time() - t0 < 90:
t1 = time.time()
try:
st, data = call("GET", f"/api/v1/attachments/{att['id']}/content", token=tok, timeout=5)
ok = st == 200 and hashlib.sha256(data).hexdigest() == want
print(f"t={time.time() - t0:5.1f}s status={st} bytes_ok={ok} took={time.time() - t1:.1f}s")
if ok:
break
except Exception as e:
print(f"t={time.time() - t0:5.1f}s {type(e).__name__} took={time.time() - t1:.1f}s")
time.sleep(1)
+55
View File
@@ -0,0 +1,55 @@
import base64, json, socket, struct, sys, urllib.request, uuid, zlib
BASE_HOST, BASE_PORT = "localhost", 8080
PWD = "correct-horse-battery-staple"
def api(method, path, body=None, headers=None):
req = urllib.request.Request(f"http://{BASE_HOST}:{BASE_PORT}{path}", data=body, method=method, headers=headers or {})
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, r.read()
except urllib.error.HTTPError as e:
return e.code, e.read()
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
PNG = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(b"".join(b"\x00" + b"\x10\x80\xf0" * 8 for _ in range(8)))) + chunk(b"IEND", b""))
name = "up_" + uuid.uuid4().hex[:8]
j = {"Content-Type": "application/json"}
_, raw = api("POST", "/api/v1/users", json.dumps({"username": name, "display_name": "u", "password": PWD}).encode(), j)
user = json.loads(raw)
_, raw = api("POST", "/api/v1/auth/sessions", None, {"Authorization": "Basic " + base64.b64encode(f"{name}:{PWD}".encode()).decode()})
token = json.loads(raw)["token"]
_, raw = api("POST", "/api/v1/chats", json.dumps({"title": "u", "member_ids": [user["id"]]}).encode(), {**j, "Authorization": "Bearer " + token})
chat = json.loads(raw)
mode = sys.argv[1] if len(sys.argv) > 1 else "ok"
if mode == "ok":
st, raw = api("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=u.png", PNG,
{"Content-Type": "image/png", "Authorization": "Bearer " + token})
print("upload status:", st)
elif mode == "abort":
# заявляем 5 МБ отправляем 300 КБ и закрываем соединение
s = socket.create_connection((BASE_HOST, BASE_PORT))
head = (f"POST /api/v1/chats/{chat['id']}/attachments?filename=a.png HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {token}\r\nContent-Type: image/png\r\nContent-Length: 5000000\r\n\r\n")
s.sendall(head.encode() + PNG + b"\0" * 300_000)
s.close()
print("aborted upload after 300 KB of 5000000")
elif mode == "roundtrip":
import hashlib
st, raw = api("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=r.png", PNG,
{"Content-Type": "image/png", "Authorization": "Bearer " + token})
if st != 201:
print("upload", st); sys.exit(1)
att = json.loads(raw)
st, data = api("GET", f"/api/v1/attachments/{att['id']}/content", None, {"Authorization": "Bearer " + token})
good = st == 200 and hashlib.sha256(data).hexdigest() == att["sha256"]
print("roundtrip", "ok" if good else f"fail {st}")
sys.exit(0 if good else 1)
+60
View File
@@ -0,0 +1,60 @@
#!/bin/sh
cd "$(dirname "$0")/.."
mkdir -p evidence/steps
RESULTS=""
step() {
name="$1"; shift
log="evidence/steps/$name.log"
echo ">>> $name"
"$@" > "$log" 2>&1
code=$?
if [ "$code" -ne 0 ] || grep -q '^FAIL' "$log"; then st=FAIL; else st=PASS; fi
echo " $st (exit=$code) -> $log"
RESULTS="$RESULTS\n$st $name"
}
settle() { docker compose up -d --no-recreate api >/dev/null 2>&1; ./scripts/wait_ready.sh 150 >/dev/null 2>&1; }
infra() {
docker compose ps -a
for c in $(docker compose ps -aq); do
docker inspect -f '{{.Name}} cpus={{.HostConfig.NanoCpus}} mem={{.HostConfig.Memory}}' "$c"
done
echo "container_name in compose: $(docker compose config | grep -c container_name || true)"
docker compose config --services
docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' "$(docker compose ps -q api | head -1)" | grep -i -E "DATABASE|PASSWORD|S3_" || true
docker inspect -f '{{.Name}}: {{range $k,$v := .NetworkSettings.Networks}}{{$k}} {{end}}' $(docker compose ps -q) 2>/dev/null
}
s3init_twice() { docker compose run --rm -T s3-init && docker compose run --rm -T s3-init; }
step 00-up sh -c 'docker compose --env-file .env up -d --build && ./scripts/wait_ready.sh 180'
step 01-go-tests sh -c 'go build ./... && go vet ./... && go test ./...'
step 02-make-check make check
step 03-make-test make test
step 04-lb python3 scripts/check_lb.py
step 05-edge python3 scripts/check_edge.py
step 06-attachments python3 scripts/check_attachments.py
step 07-s3-rights ./scripts/check_s3.sh
step 08-s3-init-twice s3init_twice
step 09-orphans ./scripts/orphan_scenarios.sh
step 10-memory-1mb python3 scripts/memory_experiment.py 1000000
step 11-memory-9mb python3 scripts/memory_experiment.py 9437184
step 12-att-failover-1 python3 scripts/check_attachment_failover.py
settle
step 13-att-failover-2 python3 scripts/check_attachment_failover.py
settle
step 14-persistence make test-persistence ACTION_SCRIPT=scripts/restart.sh
settle
step 15-failover-1 make test-failover ACTION_SCRIPT=scripts/stop-one.sh
settle
step 16-failover-2 make test-failover ACTION_SCRIPT=scripts/stop-one.sh
settle
step 17-infra infra
if [ "${ROLLING:-0}" = 1 ]; then
step 18-rolling ./scripts/rolling-under-load.sh
settle
fi
echo
echo "=========== ИТОГ ==========="
printf '%b\n' "$RESULTS" | tee evidence/SUMMARY.txt
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
cd "$(dirname "$0")/.."
limit="${1:-120}"
end=$(( $(date +%s) + limit ))
while [ "$(date +%s)" -lt "$end" ]; do
if [ "$(curl -s -o /dev/null -w '%{http_code}' localhost:8080/health/ready)" = 200 ] \
&& python3 scripts/upload_tools.py roundtrip >/dev/null 2>&1; then
echo "ready"; exit 0
fi
sleep 2
done
echo "NOT READY after ${limit}s"; exit 1