Implement lab4 S3 attachments and reliability checks
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
import secrets
|
||||
import struct
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from uuid import uuid4
|
||||
import zlib
|
||||
|
||||
|
||||
BASE = "http://127.0.0.1:18082/api/v1"
|
||||
token = None
|
||||
passed = 0
|
||||
|
||||
|
||||
def check(label, status, headers, body, expected):
|
||||
global passed
|
||||
|
||||
if status != expected:
|
||||
raise SystemExit(
|
||||
f"FAIL {label}: expected={expected}, actual={status}\n"
|
||||
+ body[:1000].decode("utf-8", errors="replace")
|
||||
)
|
||||
|
||||
assert headers.get("X-Request-Id"), "Missing X-Request-Id"
|
||||
assert headers.get("X-Instance-Id"), "Missing X-Instance-Id"
|
||||
result = json.loads(body)
|
||||
|
||||
if expected >= 400:
|
||||
codes = {
|
||||
400: "invalid_request",
|
||||
404: "not_found",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
}
|
||||
assert result["error"]["code"] == codes[expected]
|
||||
assert (
|
||||
result["error"]["request_id"]
|
||||
== headers["X-Request-Id"]
|
||||
)
|
||||
|
||||
passed += 1
|
||||
print(f"OK {status}: {label}", flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def call(label, method, path, expected, *,
|
||||
payload=None, data=None, headers=None):
|
||||
headers = dict(headers or {})
|
||||
|
||||
if token and "Authorization" not in headers:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
request = urllib.request.Request(
|
||||
BASE + path, data=data, headers=headers, method=method
|
||||
)
|
||||
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
|
||||
with response:
|
||||
body = response.read()
|
||||
return check(
|
||||
label, response.code, response.headers, body, expected
|
||||
)
|
||||
|
||||
|
||||
def chunk(kind, content):
|
||||
return (
|
||||
struct.pack(">I", len(content))
|
||||
+ kind + content
|
||||
+ struct.pack(">I", zlib.crc32(kind + content) & 0xffffffff)
|
||||
)
|
||||
|
||||
|
||||
def png(width, 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(b"\x00\x12\x34\x56"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
username = "negative_" + secrets.token_hex(6)
|
||||
password = "Lab4-" + secrets.token_hex(16)
|
||||
|
||||
user = call(
|
||||
"create user", "POST", "/users", 201,
|
||||
payload={
|
||||
"username": username,
|
||||
"display_name": "Lab4 negative tests",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
|
||||
basic = base64.b64encode(
|
||||
f"{username}:{password}".encode()
|
||||
).decode()
|
||||
|
||||
session = call(
|
||||
"login", "POST", "/auth/sessions", 201,
|
||||
headers={"Authorization": "Basic " + basic},
|
||||
)
|
||||
token = session["token"]
|
||||
|
||||
chat_ids = []
|
||||
for number in (1, 2):
|
||||
chat = call(
|
||||
f"create chat {number}", "POST", "/chats", 201,
|
||||
payload={
|
||||
"title": f"Negative check {number}",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
chat_ids.append(chat["id"])
|
||||
|
||||
upload = f"/chats/{chat_ids[0]}/attachments"
|
||||
image = png(1, 1)
|
||||
|
||||
attachment = call(
|
||||
"valid upload", "POST", upload + "?filename=valid.png", 201,
|
||||
data=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
for filename in (
|
||||
"../bad.png",
|
||||
"bad\\name.png",
|
||||
"bad\x00.png",
|
||||
"bad\n.png",
|
||||
" ",
|
||||
"a" * 256,
|
||||
):
|
||||
call(
|
||||
"unsafe filename " + repr(filename[:30]),
|
||||
"POST",
|
||||
upload + "?filename=" + urllib.parse.quote(filename, safe=""),
|
||||
400,
|
||||
data=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
for label, data, mime in (
|
||||
("PNG declared as JPEG", image, "image/jpeg"),
|
||||
("non-image", b"this is not an image", "image/png"),
|
||||
("truncated PNG", image[:-12], "image/png"),
|
||||
("unsupported MIME", image, "application/octet-stream"),
|
||||
("empty image", b"", "image/png"),
|
||||
):
|
||||
call(
|
||||
label, "POST", upload + "?filename=bad.png", 415,
|
||||
data=data,
|
||||
headers={"Content-Type": mime},
|
||||
)
|
||||
|
||||
call(
|
||||
"over 40 million pixels",
|
||||
"POST", upload + "?filename=huge.png", 413,
|
||||
data=png(8001, 5000),
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
|
||||
connection = http.client.HTTPConnection(
|
||||
"127.0.0.1", 18082, timeout=15
|
||||
)
|
||||
try:
|
||||
connection.putrequest(
|
||||
"POST", "/api/v1" + upload + "?filename=oversize.png"
|
||||
)
|
||||
connection.putheader("Authorization", "Bearer " + token)
|
||||
connection.putheader("Content-Type", "image/png")
|
||||
connection.putheader("Content-Length", str(10 * 1024 * 1024 + 1))
|
||||
connection.putheader("Connection", "close")
|
||||
connection.endheaders()
|
||||
|
||||
response = connection.getresponse()
|
||||
check(
|
||||
"oversized Content-Length rejected before body",
|
||||
response.status,
|
||||
response.headers,
|
||||
response.read(),
|
||||
413,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
for label, chat_id, ids, expected in (
|
||||
(
|
||||
"attachment from another chat",
|
||||
chat_ids[1], [attachment["id"]], 404,
|
||||
),
|
||||
(
|
||||
"unknown attachment",
|
||||
chat_ids[0], [str(uuid4())], 404,
|
||||
),
|
||||
(
|
||||
"duplicate attachment",
|
||||
chat_ids[0], [attachment["id"], attachment["id"]], 400,
|
||||
),
|
||||
(
|
||||
"more than 10 attachments",
|
||||
chat_ids[0], [str(uuid4()) for _ in range(11)], 400,
|
||||
),
|
||||
):
|
||||
call(
|
||||
label, "POST", f"/chats/{chat_id}/messages", expected,
|
||||
payload={"text": "", "attachment_ids": ids},
|
||||
headers={"Idempotency-Key": secrets.token_hex(16)},
|
||||
)
|
||||
|
||||
print(f"\nPASS: {passed} checks including setup")
|
||||
@@ -0,0 +1,190 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from botocore.exceptions import ClientError
|
||||
import psycopg
|
||||
|
||||
import app.cleanup_orphans as cleanup
|
||||
from app.object_locks import object_lock_id
|
||||
from app.storage import bucket_name, get_client, get_object
|
||||
|
||||
|
||||
client = get_client()
|
||||
bucket = bucket_name()
|
||||
|
||||
with cleanup.database_connection() as conn:
|
||||
original = conn.execute(
|
||||
"""
|
||||
SELECT object_key, chat_id, owner_id, sha256
|
||||
FROM attachments
|
||||
ORDER BY created_at, id
|
||||
LIMIT 1
|
||||
"""
|
||||
).fetchone()
|
||||
|
||||
if original is None:
|
||||
raise SystemExit("Нужно существующее корректное вложение")
|
||||
|
||||
orphan_id = uuid4()
|
||||
orphan_key = f"originals/{orphan_id}"
|
||||
busy_key = f"originals/{uuid4()}"
|
||||
fresh_key = f"originals/{uuid4()}"
|
||||
|
||||
test_keys = {orphan_key, busy_key, fresh_key}
|
||||
scope = test_keys | {original["object_key"]}
|
||||
body = b"controlled-orphan-test"
|
||||
|
||||
|
||||
class ScopedPages:
|
||||
def paginate(self, **kwargs):
|
||||
paginator = client.get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(**kwargs):
|
||||
yield {
|
||||
**page,
|
||||
"Contents": [
|
||||
item for item in page.get("Contents", [])
|
||||
if item["Key"] in scope
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
class ScopedClient:
|
||||
def get_paginator(self, name):
|
||||
assert name == "list_objects_v2"
|
||||
return ScopedPages()
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(client, name)
|
||||
|
||||
|
||||
cleanup.get_client = lambda: ScopedClient()
|
||||
|
||||
|
||||
def sweep(apply):
|
||||
result = cleanup.sweep(apply=apply, grace_seconds=60)
|
||||
print(result, flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def exists(key):
|
||||
try:
|
||||
client.head_object(Bucket=bucket, Key=key)
|
||||
return True
|
||||
except ClientError as exc:
|
||||
status = exc.response.get(
|
||||
"ResponseMetadata", {}
|
||||
).get("HTTPStatusCode")
|
||||
if status == 404:
|
||||
return False
|
||||
raise
|
||||
|
||||
|
||||
try:
|
||||
client.put_object(
|
||||
Bucket=bucket, Key=orphan_key, Body=body,
|
||||
ContentType="application/octet-stream",
|
||||
)
|
||||
|
||||
with cleanup.database_connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, sha256, object_key
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""",
|
||||
(
|
||||
orphan_id,
|
||||
original["chat_id"],
|
||||
original["owner_id"],
|
||||
"rollback-test.png",
|
||||
"image/png",
|
||||
len(body),
|
||||
hashlib.sha256(body).hexdigest(),
|
||||
orphan_key,
|
||||
),
|
||||
)
|
||||
raise psycopg.Rollback()
|
||||
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM attachments WHERE object_key = %s",
|
||||
(orphan_key,),
|
||||
).fetchone()
|
||||
assert row is None
|
||||
|
||||
assert exists(orphan_key)
|
||||
print("OK: S3 PUT сохранён, метаданные откатились", flush=True)
|
||||
|
||||
client.put_object(
|
||||
Bucket=bucket, Key=busy_key, Body=body,
|
||||
)
|
||||
|
||||
result = sweep(False)
|
||||
assert result["candidates"] == 0
|
||||
assert result["deleted"] == 0
|
||||
assert result["fresh"] >= 2
|
||||
print("OK: свежие orphan-объекты сохранены", flush=True)
|
||||
|
||||
print("Ждём 65 секунд для тестового grace period...", flush=True)
|
||||
time.sleep(65)
|
||||
|
||||
client.put_object(
|
||||
Bucket=bucket, Key=fresh_key, Body=body,
|
||||
)
|
||||
|
||||
with cleanup.database_connection() as lock_conn:
|
||||
with lock_conn.transaction():
|
||||
lock_conn.execute(
|
||||
"SET LOCAL "
|
||||
"idle_in_transaction_session_timeout = '180s'"
|
||||
)
|
||||
lock_conn.execute(
|
||||
"SELECT pg_advisory_xact_lock(%s)",
|
||||
(object_lock_id(bucket, busy_key),),
|
||||
)
|
||||
|
||||
result = sweep(False)
|
||||
assert result["candidates"] == 1
|
||||
assert result["deleted"] == 0
|
||||
assert result["busy"] == 1
|
||||
assert result["fresh"] == 1
|
||||
assert result["kept"] == 1
|
||||
assert exists(orphan_key)
|
||||
print("OK: dry-run ничего не удалил", flush=True)
|
||||
|
||||
result = sweep(True)
|
||||
assert result["deleted"] == 1
|
||||
assert result["busy"] == 1
|
||||
assert result["fresh"] == 1
|
||||
assert result["kept"] == 1
|
||||
assert not exists(orphan_key)
|
||||
assert exists(busy_key)
|
||||
assert exists(fresh_key)
|
||||
print("OK: удалён только старый незанятый orphan", flush=True)
|
||||
|
||||
result = sweep(True)
|
||||
assert result["deleted"] == 0
|
||||
assert result["candidates"] == 0
|
||||
print("OK: повторный запуск безопасен", flush=True)
|
||||
|
||||
result = sweep(True)
|
||||
assert result["deleted"] == 1
|
||||
assert not exists(busy_key)
|
||||
assert exists(fresh_key)
|
||||
print("OK: после освобождения блокировки orphan очищен", flush=True)
|
||||
|
||||
downloaded = asyncio.run(get_object(original["object_key"]))
|
||||
assert hashlib.sha256(downloaded).hexdigest() == original["sha256"]
|
||||
print("OK: существующее вложение не повреждено", flush=True)
|
||||
|
||||
print("PASS: orphan cleanup safety and rollback recovery", flush=True)
|
||||
finally:
|
||||
for key in test_keys:
|
||||
client.delete_object(Bucket=bucket, Key=key)
|
||||
print("Только собственные тестовые объекты убраны", flush=True)
|
||||
@@ -0,0 +1,154 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
COMPOSE = [
|
||||
"docker", "compose",
|
||||
"-f", "compose.yaml",
|
||||
"-f", "compose.s3.yaml",
|
||||
"--env-file", ".env",
|
||||
]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
COMPOSE + list(args),
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
state = runpy.run_path(str(ROOT / "tests/attachments_negative.py"))
|
||||
|
||||
containers = subprocess.check_output(
|
||||
COMPOSE + ["ps", "-q", "api"],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
).split()
|
||||
|
||||
if not containers:
|
||||
raise SystemExit("No running API container")
|
||||
|
||||
payload = {
|
||||
"token": state["token"],
|
||||
"chat_id": state["chat_ids"][0],
|
||||
"attachment_id": state["attachment"]["id"],
|
||||
"image": base64.b64encode(state["image"]).decode(),
|
||||
}
|
||||
|
||||
probe = r'''
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
state = json.load(sys.stdin)
|
||||
base = "http://127.0.0.1:8080/api/v1"
|
||||
attachment = state["attachment_id"]
|
||||
|
||||
cases = [
|
||||
(
|
||||
"metadata remains readable",
|
||||
"GET",
|
||||
f"/attachments/{attachment}",
|
||||
None,
|
||||
200,
|
||||
),
|
||||
(
|
||||
"download fails safely",
|
||||
"GET",
|
||||
f"/attachments/{attachment}/content",
|
||||
None,
|
||||
503,
|
||||
),
|
||||
(
|
||||
"upload fails safely",
|
||||
"POST",
|
||||
f"/chats/{state['chat_id']}/attachments?filename=outage.png",
|
||||
base64.b64decode(state["image"]),
|
||||
503,
|
||||
),
|
||||
]
|
||||
|
||||
for label, method, path, data, expected in cases:
|
||||
headers = {"Authorization": "Bearer " + state["token"]}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "image/png"
|
||||
|
||||
request = urllib.request.Request(
|
||||
base + path, method=method, headers=headers, data=data
|
||||
)
|
||||
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=40)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
|
||||
with response:
|
||||
status = response.code
|
||||
headers = response.headers
|
||||
body = json.loads(response.read())
|
||||
|
||||
assert status == expected, (label, status, body)
|
||||
assert headers.get("X-Request-Id")
|
||||
assert headers.get("X-Instance-Id")
|
||||
|
||||
if expected == 503:
|
||||
assert body["error"]["code"] == "unavailable"
|
||||
assert (
|
||||
body["error"]["request_id"]
|
||||
== headers["X-Request-Id"]
|
||||
)
|
||||
else:
|
||||
assert body["id"] == attachment
|
||||
|
||||
print(f"OK {status}: {label}", flush=True)
|
||||
'''
|
||||
|
||||
try:
|
||||
compose("stop", "--timeout", "10", "s3")
|
||||
subprocess.run(
|
||||
["docker", "exec", "-i", containers[0], "python", "-c", probe],
|
||||
input=json.dumps(payload),
|
||||
text=True,
|
||||
check=True,
|
||||
timeout=150,
|
||||
)
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
"http://127.0.0.1:18082/health/ready",
|
||||
timeout=5,
|
||||
) as response:
|
||||
assert response.status == 200
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise SystemExit("Readiness did not recover")
|
||||
time.sleep(2)
|
||||
|
||||
request = urllib.request.Request(
|
||||
state["BASE"]
|
||||
+ f"/attachments/{state['attachment']['id']}/content",
|
||||
headers={"Authorization": "Bearer " + state["token"]},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
downloaded = response.read()
|
||||
|
||||
assert downloaded == state["image"]
|
||||
print("OK: original remains intact after S3 restart")
|
||||
print("PASS: S3 outage operations and recovery")
|
||||
@@ -0,0 +1,158 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import secrets
|
||||
import struct
|
||||
import time
|
||||
import urllib.request
|
||||
import zlib
|
||||
|
||||
from app.cleanup_orphans import database_connection
|
||||
from app.storage import bucket_name, get_client
|
||||
|
||||
|
||||
BASE = "http://lb:8080/api/v1"
|
||||
token = None
|
||||
|
||||
|
||||
def api(method, path, *, payload=None, data=None, headers=None):
|
||||
headers = dict(headers or {})
|
||||
if token and "Authorization" not in headers:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
|
||||
request = urllib.request.Request(
|
||||
BASE + path, method=method, headers=headers, data=data
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
assert response.code == 201
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def chunk(kind, content):
|
||||
return (
|
||||
struct.pack(">I", len(content))
|
||||
+ kind + content
|
||||
+ struct.pack(">I", zlib.crc32(kind + content) & 0xffffffff)
|
||||
)
|
||||
|
||||
|
||||
image = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", zlib.compress(b"\x00\x12\x34\x56"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
username = "abort_" + secrets.token_hex(6)
|
||||
password = "Lab4-" + secrets.token_hex(16)
|
||||
|
||||
user = api(
|
||||
"POST", "/users",
|
||||
payload={
|
||||
"username": username,
|
||||
"display_name": "Upload abort check",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
basic = base64.b64encode(
|
||||
f"{username}:{password}".encode()
|
||||
).decode()
|
||||
|
||||
session = api(
|
||||
"POST", "/auth/sessions",
|
||||
headers={"Authorization": "Basic " + basic},
|
||||
)
|
||||
token = session["token"]
|
||||
|
||||
chat = api(
|
||||
"POST", "/chats",
|
||||
payload={
|
||||
"title": "Upload abort check",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
chat_id = chat["id"]
|
||||
|
||||
client = get_client()
|
||||
bucket = bucket_name()
|
||||
|
||||
|
||||
def object_keys():
|
||||
return {
|
||||
item["Key"]
|
||||
for page in client.get_paginator("list_objects_v2").paginate(
|
||||
Bucket=bucket, Prefix="originals/"
|
||||
)
|
||||
for item in page.get("Contents", [])
|
||||
}
|
||||
|
||||
|
||||
before = object_keys()
|
||||
|
||||
for number in range(1, 4):
|
||||
connection = http.client.HTTPConnection("api", 8080, timeout=10)
|
||||
try:
|
||||
connection.request("GET", "/health/live")
|
||||
response = connection.getresponse()
|
||||
response.read()
|
||||
assert response.status == 200
|
||||
instance = response.getheader("X-Instance-Id")
|
||||
|
||||
connection.putrequest(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat_id}/attachments"
|
||||
f"?filename=aborted-{number}.png",
|
||||
)
|
||||
connection.putheader("Authorization", "Bearer " + token)
|
||||
connection.putheader("Content-Type", "image/png")
|
||||
connection.putheader("Content-Length", str(len(image)))
|
||||
connection.endheaders()
|
||||
connection.send(image[:len(image) // 2])
|
||||
time.sleep(0.3)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
print(
|
||||
f"Соединение {number} оборвано после половины тела; "
|
||||
f"instance={instance}",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
with database_connection() as conn:
|
||||
count = conn.execute(
|
||||
"SELECT count(*) AS n FROM attachments WHERE chat_id = %s",
|
||||
(chat_id,),
|
||||
).fetchone()["n"]
|
||||
|
||||
assert count == 0, f"Появились метаданные: {count}"
|
||||
print("OK: метаданные незавершённых загрузок не созданы", flush=True)
|
||||
|
||||
new_keys = object_keys() - before
|
||||
assert not new_keys, f"Появились новые S3-ключи: {new_keys}"
|
||||
print("OK: новые S3-объекты не появились", flush=True)
|
||||
|
||||
attachment = api(
|
||||
"POST",
|
||||
f"/chats/{chat_id}/attachments?filename=complete.png",
|
||||
data=image,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
assert attachment["sha256"] == hashlib.sha256(image).hexdigest()
|
||||
|
||||
request = urllib.request.Request(
|
||||
BASE + f"/attachments/{attachment['id']}/content",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
assert response.read() == image
|
||||
|
||||
print("OK: последующая загрузка и скачивание успешны", flush=True)
|
||||
print("PASS: interrupted uploads leave no metadata or objects", flush=True)
|
||||
@@ -0,0 +1,336 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import secrets
|
||||
import struct
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zlib
|
||||
|
||||
|
||||
BASE = "http://127.0.0.1:18082/api/v1"
|
||||
COMPOSE = [
|
||||
"docker", "compose",
|
||||
"-f", "compose.yaml",
|
||||
"-f", "compose.s3.yaml",
|
||||
"--env-file", ".env",
|
||||
]
|
||||
token = None
|
||||
|
||||
|
||||
def api(method, path, *, payload=None, headers=None):
|
||||
headers = dict(headers or {})
|
||||
if token and "Authorization" not in headers:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
data = None
|
||||
if payload is not None:
|
||||
data = json.dumps(payload).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
request = urllib.request.Request(
|
||||
BASE + path, method=method, headers=headers, data=data
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def chunk(kind, data):
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ kind + data
|
||||
+ struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
|
||||
)
|
||||
|
||||
|
||||
print("Generating PNG 6000x6000...", flush=True)
|
||||
rng = random.Random(44)
|
||||
compressor = zlib.compressobj(level=1)
|
||||
compressed = bytearray()
|
||||
|
||||
for row in range(6000):
|
||||
pixels = rng.randbytes(18000) if row < 450 else bytes(18000)
|
||||
compressed.extend(compressor.compress(b"\x00" + pixels))
|
||||
compressed.extend(compressor.flush())
|
||||
|
||||
image = (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", struct.pack(">IIBBBBB", 6000, 6000, 8, 2, 0, 0, 0))
|
||||
+ chunk(b"IDAT", bytes(compressed))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
del compressed
|
||||
assert len(image) <= 10485760
|
||||
digest = hashlib.sha256(image).hexdigest()
|
||||
print(f"Fixture: {len(image)} bytes, 36000000 pixels", flush=True)
|
||||
|
||||
username = "memory_" + secrets.token_hex(6)
|
||||
password = "Lab4-" + secrets.token_hex(16)
|
||||
user = api(
|
||||
"POST", "/users",
|
||||
payload={
|
||||
"username": username,
|
||||
"display_name": "Upload memory experiment",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
session = api(
|
||||
"POST", "/auth/sessions",
|
||||
headers={"Authorization": "Basic " + basic},
|
||||
)
|
||||
token = session["token"]
|
||||
chat = api(
|
||||
"POST", "/chats",
|
||||
payload={
|
||||
"title": "Upload memory experiment",
|
||||
"member_ids": [user["id"]],
|
||||
},
|
||||
)
|
||||
|
||||
containers = subprocess.check_output(
|
||||
COMPOSE + ["ps", "-q", "api"], text=True
|
||||
).split()
|
||||
assert len(containers) >= 2, "Need two running API replicas"
|
||||
|
||||
|
||||
def container_states():
|
||||
result = {}
|
||||
for container in containers:
|
||||
text = subprocess.check_output(
|
||||
[
|
||||
"docker", "inspect", "--format",
|
||||
"{{json .State}}|{{.RestartCount}}", container,
|
||||
],
|
||||
text=True,
|
||||
)
|
||||
raw, restart_count = text.strip().rsplit("|", 1)
|
||||
state = json.loads(raw)
|
||||
result[container[:12]] = {
|
||||
"started_at": state["StartedAt"],
|
||||
"oom_killed": state["OOMKilled"],
|
||||
"status": state["Status"],
|
||||
"restart_count": int(restart_count),
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
SAMPLER = r'''
|
||||
import json
|
||||
from pathlib import Path
|
||||
import select
|
||||
import sys
|
||||
|
||||
while True:
|
||||
row = {}
|
||||
for line in Path("/proc/1/status").read_text().splitlines():
|
||||
name, _, value = line.partition(":")
|
||||
if name in ("VmRSS", "VmHWM", "VmSwap"):
|
||||
row[name + "_kib"] = int(value.split()[0])
|
||||
|
||||
root = Path("/sys/fs/cgroup")
|
||||
for name in ("memory.current", "memory.peak", "memory.max"):
|
||||
row[name] = int((root / name).read_text().strip())
|
||||
|
||||
for line in (root / "memory.events").read_text().splitlines():
|
||||
name, value = line.split()
|
||||
row["events." + name] = int(value)
|
||||
|
||||
print(json.dumps(row), flush=True)
|
||||
ready, _, _ = select.select([sys.stdin], [], [], 0.1)
|
||||
if ready and not sys.stdin.readline():
|
||||
break
|
||||
'''
|
||||
|
||||
samples = []
|
||||
monitor_errors = []
|
||||
monitors = []
|
||||
readers = []
|
||||
phase = {"name": "baseline"}
|
||||
origin = time.monotonic()
|
||||
before = container_states()
|
||||
|
||||
|
||||
def read_samples(process, container):
|
||||
try:
|
||||
for line in process.stdout:
|
||||
row = json.loads(line)
|
||||
row["container"] = container[:12]
|
||||
row["time_s"] = round(time.monotonic() - origin, 4)
|
||||
row["phase"] = phase["name"]
|
||||
samples.append(row)
|
||||
except Exception as error:
|
||||
monitor_errors.append(type(error).__name__)
|
||||
|
||||
|
||||
for container in containers:
|
||||
process = subprocess.Popen(
|
||||
["docker", "exec", "-i", container, "python", "-u", "-c", SAMPLER],
|
||||
stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
text=True,
|
||||
)
|
||||
monitors.append(process)
|
||||
reader = threading.Thread(
|
||||
target=read_samples, args=(process, container), daemon=True
|
||||
)
|
||||
reader.start()
|
||||
readers.append(reader)
|
||||
|
||||
rounds = []
|
||||
|
||||
|
||||
def run_round(label, concurrency):
|
||||
barrier = threading.Barrier(concurrency + 1)
|
||||
lock = threading.Lock()
|
||||
activity = {"current": 0, "peak": 0}
|
||||
|
||||
def worker(number):
|
||||
barrier.wait()
|
||||
with lock:
|
||||
activity["current"] += 1
|
||||
activity["peak"] = max(
|
||||
activity["peak"], activity["current"]
|
||||
)
|
||||
started = time.monotonic()
|
||||
result = {"number": number}
|
||||
try:
|
||||
request = urllib.request.Request(
|
||||
BASE + f"/chats/{chat['id']}/attachments"
|
||||
+ f"?filename={label}-{number}.png",
|
||||
method="POST",
|
||||
data=image,
|
||||
headers={
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "image/png",
|
||||
},
|
||||
)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=60)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
|
||||
with response:
|
||||
body = response.read()
|
||||
result["status"] = response.code
|
||||
result["instance"] = response.headers.get("X-Instance-Id")
|
||||
if response.code == 201:
|
||||
metadata = json.loads(body)
|
||||
result["valid_metadata"] = (
|
||||
metadata["sha256"] == digest
|
||||
and metadata["size_bytes"] == len(image)
|
||||
and metadata["status"] == "ready"
|
||||
)
|
||||
except Exception as error:
|
||||
result["status"] = "transport_error"
|
||||
result["error_type"] = type(error).__name__
|
||||
finally:
|
||||
result["seconds"] = round(time.monotonic() - started, 4)
|
||||
with lock:
|
||||
activity["current"] -= 1
|
||||
return result
|
||||
|
||||
phase["name"] = label
|
||||
with ThreadPoolExecutor(max_workers=concurrency) as executor:
|
||||
futures = [executor.submit(worker, n) for n in range(concurrency)]
|
||||
started = time.monotonic()
|
||||
barrier.wait()
|
||||
results = [future.result() for future in futures]
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
summary = {
|
||||
"label": label,
|
||||
"clients": concurrency,
|
||||
"peak_client_in_flight": activity["peak"],
|
||||
"elapsed_seconds": round(elapsed, 4),
|
||||
"statuses": dict(Counter(str(row["status"]) for row in results)),
|
||||
"requests": results,
|
||||
}
|
||||
rounds.append(summary)
|
||||
print(json.dumps({
|
||||
key: value for key, value in summary.items()
|
||||
if key != "requests"
|
||||
}), flush=True)
|
||||
|
||||
phase["name"] = label + "_cooldown"
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
try:
|
||||
time.sleep(1)
|
||||
run_round("single", 1)
|
||||
run_round("concurrent_1", 10)
|
||||
run_round("concurrent_2", 10)
|
||||
finally:
|
||||
phase["name"] = "final"
|
||||
time.sleep(1)
|
||||
for process in monitors:
|
||||
process.stdin.close()
|
||||
for process in monitors:
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.terminate()
|
||||
monitor_errors.append("sampler_stop_timeout")
|
||||
if process.returncode != 0:
|
||||
monitor_errors.append("sampler_nonzero_exit")
|
||||
for reader in readers:
|
||||
reader.join(timeout=5)
|
||||
|
||||
after = container_states()
|
||||
report = {
|
||||
"fixture_bytes": len(image),
|
||||
"width": 6000,
|
||||
"height": 6000,
|
||||
"fixture_sha256": digest,
|
||||
"before": before,
|
||||
"after": after,
|
||||
"rounds": rounds,
|
||||
"monitor_errors": monitor_errors,
|
||||
"memory_summary": {},
|
||||
}
|
||||
|
||||
for container in containers:
|
||||
key = container[:12]
|
||||
rows = [row for row in samples if row["container"] == key]
|
||||
assert rows, f"No memory samples for {key}"
|
||||
report["memory_summary"][key] = {
|
||||
"samples": len(rows),
|
||||
"initial_cgroup_peak_bytes": rows[0]["memory.peak"],
|
||||
"final_cgroup_peak_bytes": rows[-1]["memory.peak"],
|
||||
"sampled_max_cgroup_bytes": max(r["memory.current"] for r in rows),
|
||||
"sampled_max_rss_kib": max(r["VmRSS_kib"] for r in rows),
|
||||
"initial_hwm_kib": rows[0]["VmHWM_kib"],
|
||||
"final_hwm_kib": rows[-1]["VmHWM_kib"],
|
||||
"oom_delta": rows[-1]["events.oom"] - rows[0]["events.oom"],
|
||||
"oom_kill_delta": (
|
||||
rows[-1]["events.oom_kill"] - rows[0]["events.oom_kill"]
|
||||
),
|
||||
}
|
||||
|
||||
directory = Path("evidence")
|
||||
directory.mkdir(exist_ok=True)
|
||||
(directory / "upload_memory.json").write_text(
|
||||
json.dumps(report, indent=2) + "\n"
|
||||
)
|
||||
fields = sorted({key for row in samples for key in row})
|
||||
with (directory / "upload_memory.csv").open("w", newline="") as stream:
|
||||
writer = csv.DictWriter(stream, fieldnames=fields, lineterminator="\n")
|
||||
writer.writeheader()
|
||||
writer.writerows(samples)
|
||||
|
||||
print("\nMEMORY SUMMARY", flush=True)
|
||||
print(json.dumps(report["memory_summary"], indent=2), flush=True)
|
||||
print("Container states unchanged:", before == after, flush=True)
|
||||
print("Monitor errors:", monitor_errors, flush=True)
|
||||
print("Saved: evidence/upload_memory.json and evidence/upload_memory.csv")
|
||||
print("EXPERIMENT COMPLETE: inspect statuses and memory before conclusions")
|
||||
Reference in New Issue
Block a user