feat: add 4 grade things

This commit is contained in:
TAskMAster339
2026-10-18 19:23:27 +03:00
parent e3cd2516ba
commit 4d91357932
23 changed files with 2015 additions and 140 deletions
+244 -44
View File
@@ -18,11 +18,22 @@ ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check, run
COMPOSE = ["docker", "compose", "--project-name", "highload-lab4", "--env-file", ".env", "-f", "compose.yml"]
COMPOSE = [
"docker",
"compose",
"--project-name",
"highload-lab4",
"--env-file",
".env",
"-f",
"compose.yml",
]
def command(args, **kwargs):
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
def ready(client):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
@@ -33,6 +44,7 @@ def ready(client):
time.sleep(1)
raise AssertionError("readiness did not recover")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
@@ -42,66 +54,169 @@ def main():
alice, bob, eve, chat = c.bootstrap()
png = (ROOT / "tests/fixtures/sample.png").read_bytes()
path = "/api/v1/chats/" + chat["id"] + "/attachments"
def upload(data=png, mime="image/png", filename="photo.png", status=201, actor=alice, target=path):
return c.call("POST", target + "?" + urllib.parse.urlencode({"filename": filename}), status,
actor=actor, raw=data, headers={"Content-Type": mime}, schema="Attachment" if status == 201 else None)
jpeg = base64.b64decode('/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAACAAMDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDj6KKKyPJP/9k=')
jpeg_result = upload(data=jpeg,mime="image/jpeg",filename="photo.jpg")["json"]
check(c.call("GET", "/api/v1/attachments/"+jpeg_result["id"]+"/content",actor=bob)["bytes"] == jpeg,"JPEG changed")
def upload(
data=png,
mime="image/png",
filename="photo.png",
status=201,
actor=alice,
target=path,
):
return c.call(
"POST",
target + "?" + urllib.parse.urlencode({"filename": filename}),
status,
actor=actor,
raw=data,
headers={"Content-Type": mime},
schema="Attachment" if status == 201 else None,
)
jpeg = base64.b64decode(
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAACAAMDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDj6KKKyPJP/9k="
)
jpeg_result = upload(data=jpeg, mime="image/jpeg", filename="photo.jpg")["json"]
check(
c.call(
"GET", "/api/v1/attachments/" + jpeg_result["id"] + "/content", actor=bob
)["bytes"]
== jpeg,
"JPEG changed",
)
first = upload()["json"]
second = upload(filename="Второе фото.png")["json"]
for a in (first, second):
content = c.call("GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob)
content = c.call(
"GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob
)
check(content["bytes"] == png, "download bytes changed")
check(a["sha256"] == hashlib.sha256(png).hexdigest(), "checksum differs")
for suffix in ("", "/content"):
c.call("GET", "/api/v1/attachments/" + first["id"] + suffix, 404, actor=eve)
c.call("GET", "/api/v1/attachments/" + first["id"] + suffix, 401)
c.call("GET", "/api/v1/attachments/" + first["id"] + "/content?variant=thumbnail", 404, actor=alice)
c.call(
"GET",
"/api/v1/attachments/" + first["id"] + "/content?variant=thumbnail",
404,
actor=alice,
)
upload(actor=eve, status=404)
upload(data=b"x" * (10485760 + 1), status=413)
upload(data=png[:40], status=415)
upload(mime="image/jpeg", status=415)
upload(mime="text/plain", status=415)
for filename in ("", " ", "../file.png", "a\\b.png", "a\x00.png", "a\n.png", "x" * 256):
for filename in (
"",
" ",
"../file.png",
"a\\b.png",
"a\x00.png",
"a\n.png",
"x" * 256,
):
upload(filename=filename, status=400)
huge = bytearray(png)
huge[16:24] = struct.pack(">II", 10001, 4000)
huge[29:33] = struct.pack(">I", zlib.crc32(huge[12:29]) & 0xffffffff)
huge[29:33] = struct.pack(">I", zlib.crc32(huge[12:29]) & 0xFFFFFFFF)
upload(data=bytes(huge), status=413)
# Unknown-length uploads must obey the same byte limit.
endpoint = urllib.parse.urlsplit(args.base_url)
conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port or 80, timeout=35)
conn.request("POST", path + "?filename=chunked.png", body=iter([png, b"x" * 10485760]),
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"}, encode_chunked=True)
conn = http.client.HTTPConnection(
endpoint.hostname, endpoint.port or 80, timeout=35
)
conn.request(
"POST",
path + "?filename=chunked.png",
body=iter([png, b"x" * 10485760]),
headers={
"Authorization": "Bearer " + alice["token"],
"Content-Type": "image/png",
},
encode_chunked=True,
)
response = conn.getresponse()
check(response.status == 413, "chunked body limit not enforced")
response.read(); conn.close()
response.read()
conn.close()
ids = [first["id"], second["id"]]
key = uuid.uuid4().hex
def send(_):
return c.message(alice, chat, "", key=key, attachments=ids)
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
responses = list(pool.map(send, range(24)))
check(len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2, "did not use two API replicas")
check(all(r["json"] == responses[0]["json"] for r in responses), "replay changed message")
check(
len({r["headers"]["X-Instance-Id"] for r in responses}) >= 2,
"did not use two API replicas",
)
check(
all(r["json"] == responses[0]["json"] for r in responses),
"replay changed message",
)
messages_path = "/api/v1/chats/" + chat["id"] + "/messages"
history = c.call("GET", messages_path, actor=bob, schema="MessagePage")["json"]["items"]
check(len(history) == 1 and history[0]["attachment_ids"] == ids, "duplicate or lost attachments")
for body, expected in (({"text": "", "attachment_ids": ids[::-1]}, 409),
({"text": "changed", "attachment_ids": ids}, 409)):
c.call("POST", messages_path, expected, actor=alice, body=body, headers={"Idempotency-Key": key})
for bad_ids, expected in (([first["id"], first["id"]], 400), ([str(uuid.uuid4())], 404), (["invalid"], 400), (None, 400), (ids * 6, 400)):
c.call("POST", messages_path, expected, actor=alice, body={"text": "x", "attachment_ids": bad_ids}, headers={"Idempotency-Key": uuid.uuid4().hex})
other_chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "Other", "member_ids": [alice["id"]]}, schema="Chat")["json"]
c.call("POST", "/api/v1/chats/" + other_chat["id"] + "/messages", 404, actor=alice,
body={"text": "", "attachment_ids": [first["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
history = c.call("GET", messages_path, actor=bob, schema="MessagePage")["json"][
"items"
]
check(
len(history) == 1 and history[0]["attachment_ids"] == ids,
"duplicate or lost attachments",
)
for body, expected in (
({"text": "", "attachment_ids": ids[::-1]}, 409),
({"text": "changed", "attachment_ids": ids}, 409),
):
c.call(
"POST",
messages_path,
expected,
actor=alice,
body=body,
headers={"Idempotency-Key": key},
)
for bad_ids, expected in (
([first["id"], first["id"]], 400),
([str(uuid.uuid4())], 404),
(["invalid"], 400),
(None, 400),
(ids * 6, 400),
):
c.call(
"POST",
messages_path,
expected,
actor=alice,
body={"text": "x", "attachment_ids": bad_ids},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
other_chat = c.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Other", "member_ids": [alice["id"]]},
schema="Chat",
)["json"]
c.call(
"POST",
"/api/v1/chats/" + other_chat["id"] + "/messages",
404,
actor=alice,
body={"text": "", "attachment_ids": [first["id"]]},
headers={"Idempotency-Key": uuid.uuid4().hex},
)
text_key = uuid.uuid4().hex
text = c.message(alice, chat, "text", key=text_key)["json"]
check(c.message(alice, chat, "text", key=text_key, attachments=[])["json"] == text, "omitted/empty array differ")
print("PASS: image limits, chunked upload, ACL, message attachments, concurrent replay across replicas")
check(
c.message(alice, chat, "text", key=text_key, attachments=[])["json"] == text,
"omitted/empty array differ",
)
print(
"PASS: image limits, chunked upload, ACL, message attachments, concurrent replay across replicas"
)
if args.failures:
records = []
@@ -109,51 +224,135 @@ def main():
result = upload()
target = result["headers"]["X-Instance-Id"]
a = result["json"]
check(not records or target != records[0]["upload_instance"], "repeat did not target the other replica")
check(
not records or target != records[0]["upload_instance"],
"repeat did not target the other replica",
)
try:
command([str(ROOT / "scripts/stop-one.sh")], env={**os.environ, "TARGET_INSTANCE_ID": target})
command(
[str(ROOT / "scripts/stop-one.sh")],
env={**os.environ, "TARGET_INSTANCE_ID": target},
)
time.sleep(3)
downloaded = c.call("GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob)
downloaded = c.call(
"GET", "/api/v1/attachments/" + a["id"] + "/content", actor=bob
)
check(downloaded["bytes"] == png, "original lost across failover")
served = downloaded["headers"]["X-Instance-Id"]
check(served != target, "download came from stopped instance")
records.append({"upload_instance": target, "download_instance": served, "sha256": a["sha256"]})
records.append(
{
"upload_instance": target,
"download_instance": served,
"sha256": a["sha256"],
}
)
if len(records) == 1:
# Upload the next fixture while only the second replica runs.
# Restore below, then select that same replica via LB uploads.
next_target = served
finally:
command(COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT)
command(
COMPOSE + ["up", "-d", "--no-build", "--wait"],
stderr=subprocess.STDOUT,
)
ready(c)
if len(records) == 1:
# Round-robin state may change after recovery; keep requesting until it
# chooses the other replica, then use that upload in the next pass.
original_upload = upload
def upload(*a, **kw):
for attempt in range(30):
candidate = original_upload(*a, **kw)
if candidate["headers"]["X-Instance-Id"] == next_target:
return candidate
raise AssertionError("could not reach second replica")
print("PASS: stop the uploading replica, download from the other (both replicas)")
print(
"PASS: stop the uploading replica, download from the other (both replicas)"
)
try:
command(COMPOSE + ["stop", "s3"], stderr=subprocess.STDOUT)
# Probe through an existing image on the data network; no API port exposure.
image = command(["docker", "inspect", "--format", "{{.Config.Image}}", command(COMPOSE + ["ps", "--all", "-q", "s3"])])
probe = ["docker", "run", "--rm", "--network", "highload-lab4_data", "--entrypoint", "curl", image, "-s", "-o", "/dev/null", "-w", "%{http_code}"]
image = command(
[
"docker",
"inspect",
"--format",
"{{.Config.Image}}",
command(COMPOSE + ["ps", "--all", "-q", "s3"]),
]
)
probe = [
"docker",
"run",
"--rm",
"--network",
"highload-lab4_data",
"--entrypoint",
"curl",
image,
"-s",
"-o",
"/dev/null",
"-w",
"%{http_code}",
]
for container in command(COMPOSE + ["ps", "-q", "api"]).splitlines():
# Container hostname aliases are not DNS names; use the data-network IP.
info = json.loads(command(["docker", "inspect", container]))[0]
ip = info["NetworkSettings"]["Networks"]["highload-lab4_data"]["IPAddress"]
check(command(probe + [f"http://{ip}:8080/health/live"]) == "200", "liveness depends on S3")
check(command(probe + [f"http://{ip}:8080/health/ready"]) == "503", "readiness ignores S3 failure")
ip = info["NetworkSettings"]["Networks"]["highload-lab4_data"][
"IPAddress"
]
check(
command(probe + [f"http://{ip}:8080/health/live"]) == "200",
"liveness depends on S3",
)
check(
command(probe + [f"http://{ip}:8080/health/ready"]) == "503",
"readiness ignores S3 failure",
)
records.append({"s3_failure": "live=200 ready=503 on both API replicas"})
finally:
command(COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT)
command(
COMPOSE + ["up", "-d", "--no-build", "--wait"], stderr=subprocess.STDOUT
)
ready(c)
check(c.call("GET", "/api/v1/attachments/" + first["id"] + "/content", actor=bob)["bytes"] == png, "S3 recovery lost bytes")
image = command(["docker", "inspect", "--format", "{{.Config.Image}}", command(COMPOSE + ["ps", "--all", "-q", "s3"])])
code = command(["docker", "run", "--rm", "--network", "highload-lab4_data", "--entrypoint", "curl", image, "-s", "-o", "/dev/null", "-w", "%{http_code}", "http://s3:9000/messenger-attachments/originals/" + first["id"]])
check(
c.call("GET", "/api/v1/attachments/" + first["id"] + "/content", actor=bob)[
"bytes"
]
== png,
"S3 recovery lost bytes",
)
image = command(
[
"docker",
"inspect",
"--format",
"{{.Config.Image}}",
command(COMPOSE + ["ps", "--all", "-q", "s3"]),
]
)
code = command(
[
"docker",
"run",
"--rm",
"--network",
"highload-lab4_data",
"--entrypoint",
"curl",
image,
"-s",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"http://s3:9000/messenger-attachments/originals/" + first["id"],
]
)
check(code == "403", "anonymous object access was permitted")
records.append({"anonymous_object_get": code})
directory = ROOT / ".memory/grade3"
@@ -161,5 +360,6 @@ def main():
(directory / "failures.json").write_text(json.dumps(records, indent=2) + "\n")
print("PASS: S3 unavailable/recovery, private bucket")
if __name__ == "__main__":
run(main)
+64
View File
@@ -0,0 +1,64 @@
import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
def command(args):
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
def main():
evidence = []
for service in ("s3", "api", "upload-cleanup"):
ids = command(["docker", "compose", "ps", "-q", service]).splitlines()
assert ids, "service is not running: " + service
for cid in ids:
info = json.loads(command(["docker", "inspect", cid]))[0]
sources = [
Path(mount["Source"]).name
for mount in info["Mounts"]
if mount["Type"] == "bind"
]
if service == "s3":
assert not info["HostConfig"]["PortBindings"], "S3 ports are published"
assert "MINIO_BROWSER=off" in info["Config"]["Env"], (
"MinIO console is enabled"
)
assert set(info["NetworkSettings"]["Networks"]) == {
"highload-lab4_data"
}
else:
assert (
"s3_access_key_id" not in sources
and "s3_secret_access_key" not in sources
), "root credentials mounted into " + service
assert (
"s3_api_access_key_id" in sources
and "s3_api_secret_access_key" in sources
)
if service == "api":
assert (
info["HostConfig"]["Tmpfs"]["/tmp/uploads"].find("size=16m") >= 0
), "upload tmpfs limit missing"
assert info["HostConfig"]["Memory"] == 512 * 1048576
evidence.append(
{
"service": service,
"container": info["Config"]["Hostname"],
"bind_filenames": sources,
"published_ports": info["HostConfig"]["PortBindings"],
"tmpfs": info["HostConfig"].get("Tmpfs", {}),
}
)
directory = ROOT / ".memory/s3-permissions"
directory.mkdir(parents=True, exist_ok=True)
(directory / "isolation.json").write_text(json.dumps(evidence, indent=2) + "\n")
print(
"PASS: private S3 network, disabled console, restricted API mounts, bounded tmpfs"
)
if __name__ == "__main__":
main()
+381
View File
@@ -0,0 +1,381 @@
import concurrent.futures
import datetime
import hashlib
import json
import struct
import subprocess
import sys
import threading
import time
import urllib.request
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client
LIMIT = 512 * 1024 * 1024
SIZE = 10485760
BASE_URL = "http://127.0.0.1:18080"
def command(args, **kwargs):
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
def png(width, height):
def chunk(kind, data):
return (
struct.pack(">I", len(data))
+ kind
+ data
+ struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
)
compressor = zlib.compressobj(6)
row = b"\0" + bytes((20, 100, 50)) * width
compressed = (
b"".join(compressor.compress(row) for _ in range(height)) + compressor.flush()
)
data = (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", compressed)
+ chunk(b"IEND", b"")
)
return data + b"\0" * (SIZE - len(data))
def inspect(ids):
data = json.loads(command(["docker", "inspect", *ids]))
return [
{
"id": item["Id"],
"started_at": item["State"]["StartedAt"],
"image": item["Image"],
"restarts": item["RestartCount"],
"oom_killed": item["State"]["OOMKilled"],
"memory_limit": item["HostConfig"]["Memory"],
"cpus": item["HostConfig"]["NanoCpus"],
}
for item in data
]
def cgroup(container):
text = command(
[
"docker",
"exec",
container,
"sh",
"-c",
"cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak /sys/fs/cgroup/memory.max /sys/fs/cgroup/memory.events",
]
)
lines = text.splitlines()
return {
"current": int(lines[0]),
"peak": int(lines[1]),
"limit": int(lines[2]),
"events": {line.split()[0]: int(line.split()[1]) for line in lines[3:]},
}
class Sampler:
def __init__(self, ids, path):
self.file = path.open("w")
self.lock = threading.Lock()
self.processes = []
self.threads = []
self.counts = {cid: 0 for cid in ids}
self.errors = []
script = 'while true; do read current < /sys/fs/cgroup/memory.current; read peak < /sys/fs/cgroup/memory.peak; printf \'%s %s\\n\' "$current" "$peak"; sleep 0.1; done'
for cid in ids:
process = subprocess.Popen(
["docker", "exec", cid, "sh", "-c", script],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
self.processes.append(process)
thread = threading.Thread(
target=self.read, args=(cid, process), daemon=True
)
thread.start()
self.threads.append(thread)
def read(self, cid, process):
try:
for line in process.stdout:
current, peak = map(int, line.split())
with self.lock:
self.counts[cid] += 1
self.file.write(
json.dumps(
{
"container": cid,
"monotonic_ns": time.monotonic_ns(),
"current": current,
"peak": peak,
}
)
+ "\n"
)
self.file.flush()
except Exception as error:
self.errors.append(str(error))
def close(self):
for process in self.processes:
process.terminate()
for process in self.processes:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
for thread in self.threads:
thread.join(timeout=5)
self.file.close()
def verify_content(actor, attachment, digest):
request = urllib.request.Request(
BASE_URL + "/api/v1/attachments/" + attachment["id"] + "/content",
headers={"Authorization": "Bearer " + actor["token"]},
)
checksum = hashlib.sha256()
size = 0
with urllib.request.urlopen(request, timeout=30) as response:
for chunk in iter(lambda: response.read(65536), b""):
checksum.update(chunk)
size += len(chunk)
if checksum.hexdigest() != digest or size != SIZE:
raise AssertionError("download differs from original")
def run_case(compose, profile, data, directory):
client = Client(BASE_URL, timeout=45)
alice, bob, _, chat = client.bootstrap()
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=memory.png"
digest = hashlib.sha256(data).hexdigest()
for _ in range(2):
client.call(
"POST",
path,
201,
actor=alice,
raw=data,
headers={"Content-Type": "image/png"},
schema="Attachment",
)
ids = command(compose + ["ps", "-q", "api"]).splitlines()
if len(ids) != 2:
raise AssertionError("expected two API containers")
before = inspect(ids)
baseline = {cid: cgroup(cid) for cid in ids}
(directory / "before.json").write_text(
json.dumps({"containers": before, "cgroups": baseline}, indent=2) + "\n"
)
sampler = Sampler(ids, directory / "samples.jsonl")
barrier = threading.Barrier(11)
results = []
def upload(index):
barrier.wait()
started = time.monotonic_ns()
try:
response = client.call(
"POST",
path,
201,
actor=alice,
raw=data,
headers={"Content-Type": "image/png"},
schema="Attachment",
)
return {
"client": index,
"started_ns": started,
"ended_ns": time.monotonic_ns(),
"ok": True,
"instance": response["headers"]["X-Instance-Id"],
"attachment": response["json"],
}
except Exception as error:
return {
"client": index,
"started_ns": started,
"ended_ns": time.monotonic_ns(),
"ok": False,
"error": str(error),
}
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:
futures = [pool.submit(upload, index) for index in range(10)]
barrier.wait()
results = [future.result() for future in futures]
finally:
sampler.close()
# Save responses before probing containers, including when an OOM stopped one.
(directory / "requests.json").write_text(json.dumps(results, indent=2) + "\n")
after = inspect(ids)
(directory / "after.json").write_text(json.dumps(after, indent=2) + "\n")
final = {cid: cgroup(cid) for cid in ids}
for result in results:
if result["ok"]:
try:
verify_content(bob, result["attachment"], digest)
result["original_verified"] = True
except Exception as error:
result["original_verified"] = False
result["verification_error"] = str(error)
passed = (
len(results) == 10
and all(r["ok"] and r.get("original_verified") for r in results)
and len({r.get("instance") for r in results}) == 2
and before == after
and all(not r["oom_killed"] for r in after)
and all(
final[cid]["peak"] < LIMIT
and final[cid]["limit"] == LIMIT
and final[cid]["events"].get("oom_kill", 0)
== baseline[cid]["events"].get("oom_kill", 0)
and final[cid]["events"].get("oom", 0)
== baseline[cid]["events"].get("oom", 0)
for cid in ids
)
and all(count > 0 for count in sampler.counts.values())
and not sampler.errors
)
summary = {
"profile": profile,
"passed": passed,
"before": before,
"after": after,
"baseline": baseline,
"final": final,
"sample_counts": sampler.counts,
"sampler_errors": sampler.errors,
"requests": results,
}
(directory / "results.json").write_text(json.dumps(summary, indent=2) + "\n")
return {
"profile": profile,
"passed": passed,
"peaks_mib": [round(final[cid]["peak"] / 1048576, 2) for cid in ids],
}
def main():
import fcntl
directory = (
ROOT
/ ".memory/upload-memory"
/ datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%dT%H%M%SZ")
)
directory.mkdir(parents=True)
lock = (ROOT / ".memory/upload-memory.lock").open("w")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
fixtures = {"moderate": png(320, 200), "pixels40m": png(8000, 5000)}
files = (
[
ROOT / "compose.yml",
ROOT / "infra/compose.upload-memory.yml",
ROOT / "infra/minio.Dockerfile",
ROOT / "infra/haproxy.cfg",
ROOT / "src/Dockerfile",
ROOT / "src/go.mod",
ROOT / "src/go.sum",
Path(__file__),
]
+ sorted((ROOT / "src/backend").rglob("*.go"))
+ sorted((ROOT / "src/backend").rglob("*.sql"))
)
hashes = {
str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
for path in files
}
protocol = {
"version": 1,
"hypothesis": "10 concurrent upload requests remain within 512 MiB per API with no OOM or restarts and all originals preserved",
"clients": 10,
"api_replicas": 2,
"cpu_per_api": 0.5,
"memory_limit_bytes": LIMIT,
"tmpfs_bytes": 16777216,
"active_uploads_per_replica": 1,
"sampling_interval_seconds": 0.1,
"repetitions": 3,
"warmup_uploads": 2,
"request_timeout_seconds": 45,
"model": "one simultaneous burst of 10 requests, no retries",
"order": [profile for _ in range(3) for profile in fixtures],
"fixtures": {
name: {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()}
for name, data in fixtures.items()
},
"isolation": "fresh Compose project and volumes per run; same code/resources; no parallel fault tests",
"criteria": "all 60 measured uploads and downloads succeed; both replicas used; cgroup peak strictly below limit; no OOM/restart",
"insufficient_data": "sampler failure or missing samples; retain run as inconclusive, never discard errors/OOM",
"stop_rules": "complete all six runs even on failed request or OOM; no favorable early stop",
"limitations": "one host; concurrent HTTP requests with at most two decoders; tmpfs counted in cgroup; sampler overhead",
"source_sha256": hashes,
}
serialized = json.dumps(protocol, indent=2).encode() + b"\n"
(directory / "protocol.json").write_bytes(serialized)
(directory / "protocol.sha256").write_text(
hashlib.sha256(serialized).hexdigest() + "\n"
)
print("Protocol fixed:", directory, flush=True)
summaries = []
stamp = directory.name.lower().replace("t", "").replace("z", "")
for index, profile in enumerate(protocol["order"], 1):
run = directory / f"{index:02d}-{profile}"
run.mkdir()
project = f"highload-lab4-upload-memory-{stamp}-{index}"
compose = [
"docker",
"compose",
"--project-name",
project,
"--env-file",
".env",
"-f",
"compose.yml",
"-f",
"infra/compose.upload-memory.yml",
]
(run / "project.txt").write_text(project + "\n")
try:
with (run / "startup.log").open("w") as log:
subprocess.run(
compose + ["up", "-d", "--build", "--wait"],
cwd=ROOT,
stdout=log,
stderr=subprocess.STDOUT,
check=True,
)
summary = run_case(compose, profile, fixtures[profile], run)
except Exception as error:
summary = {"profile": profile, "passed": False, "error": str(error)}
(run / "failure.json").write_text(json.dumps(summary, indent=2) + "\n")
finally:
with (run / "shutdown.log").open("w") as log:
subprocess.run(
compose + ["down"], cwd=ROOT, stdout=log, stderr=subprocess.STDOUT
)
summaries.append(summary)
print(json.dumps(summary), flush=True)
(directory / "summary.json").write_text(json.dumps(summaries, indent=2) + "\n")
if not all(case["passed"] for case in summaries):
raise SystemExit(1)
print("PASS: all six upload-memory runs", flush=True)
if __name__ == "__main__":
main()
+54 -14
View File
@@ -5,6 +5,7 @@ from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
def read_values(path):
values = {}
if path.exists():
@@ -15,23 +16,37 @@ def read_values(path):
values[key.strip()] = value.strip().strip("\"'")
return values
def main():
path = ROOT / ".env"
existing = read_values(path)
defaults = read_values(ROOT / ".env.example")
defaults.update(POSTGRES_DB="messenger", POSTGRES_USER="messenger",
POSTGRES_PASSWORD=secrets.token_hex(24))
defaults.update(
POSTGRES_DB="messenger",
POSTGRES_USER="messenger",
POSTGRES_PASSWORD=secrets.token_hex(24),
)
defaults.update(UPLOAD_CLEANUP_GRACE_SECONDS="600", UPLOAD_TMP_DIR="/tmp/uploads")
values = defaults | existing
for name, lower, upper in (("APP_PORT", 1, 65535), ("API_REPLICAS", 2, 32),
("SESSION_TTL_SECONDS", 1, 31536000),
("IDEMPOTENCY_TTL_SECONDS", 1, 31536000)):
for name, lower, upper in (
("APP_PORT", 1, 65535),
("API_REPLICAS", 2, 32),
("SESSION_TTL_SECONDS", 1, 31536000),
("IDEMPOTENCY_TTL_SECONDS", 1, 31536000),
):
try:
valid = lower <= int(values[name]) <= upper
except (ValueError, KeyError):
valid = False
if not valid:
raise SystemExit(f"{name} must be between {lower} and {upper}")
for name in ("POSTGRES_DB", "POSTGRES_USER", "POSTGRES_PASSWORD", "APP_HOST", "APP_ENV"):
for name in (
"POSTGRES_DB",
"POSTGRES_USER",
"POSTGRES_PASSWORD",
"APP_HOST",
"APP_ENV",
):
if not values[name]:
raise SystemExit(f"{name} must not be empty")
# Existing values, including credentials, are never replaced.
@@ -39,28 +54,53 @@ def main():
if missing:
prefix = "\n" if path.exists() and path.stat().st_size else ""
with path.open("a", encoding="utf-8") as file:
file.write(prefix + "".join(f"{key}={value}\n" for key, value in missing.items()))
file.write(
prefix + "".join(f"{key}={value}\n" for key, value in missing.items())
)
os.chmod(path, 0o600)
secret_dir = ROOT / "secrets"
secret_dir.mkdir(mode=0o700, exist_ok=True)
database_url = "postgres://{}:{}@db:5432/{}?sslmode=disable".format(
quote(values["POSTGRES_USER"], safe=""), quote(values["POSTGRES_PASSWORD"], safe=""),
quote(values["POSTGRES_DB"], safe=""))
for name, content in (("DATABASE_URL_FILE", database_url),
("CACHE_URL_FILE", "redis://redis:6379/0"),
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32))):
quote(values["POSTGRES_USER"], safe=""),
quote(values["POSTGRES_PASSWORD"], safe=""),
quote(values["POSTGRES_DB"], safe=""),
)
for name, content in (
("DATABASE_URL_FILE", database_url),
("CACHE_URL_FILE", "redis://redis:6379/0"),
("S3_ACCESS_KEY_ID_FILE", secrets.token_hex(12)),
("S3_SECRET_ACCESS_KEY_FILE", secrets.token_hex(32)),
):
container_path = Path(values[name])
if container_path.parent != Path("/run/secrets") or not container_path.name:
raise SystemExit(f"{name} must name a file directly inside /run/secrets")
target = secret_dir / {"DATABASE_URL_FILE":"database_url", "CACHE_URL_FILE":"cache_url", "S3_ACCESS_KEY_ID_FILE":"s3_access_key_id", "S3_SECRET_ACCESS_KEY_FILE":"s3_secret_access_key"}[name]
target = (
secret_dir
/ {
"DATABASE_URL_FILE": "database_url",
"CACHE_URL_FILE": "cache_url",
"S3_ACCESS_KEY_ID_FILE": "s3_access_key_id",
"S3_SECRET_ACCESS_KEY_FILE": "s3_secret_access_key",
}[name]
)
if not target.exists():
# Containers run as an unprivileged user; the private host directory
# protects the files, while read permission lets the API consume them.
with target.open("x", encoding="utf-8") as file:
file.write(content + "\n")
os.chmod(target, 0o644)
# Existing S3 files remain the root credentials; API gets a new, separate identity.
for filename, content in (
("s3_api_access_key_id", secrets.token_hex(12)),
("s3_api_secret_access_key", secrets.token_hex(32)),
):
target = secret_dir / filename
if not target.exists():
with target.open("x", encoding="utf-8") as file:
file.write(content + "\n")
os.chmod(target, 0o644)
print("Local .env and connection files ready; existing values and files preserved.")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -3,5 +3,5 @@ set -eu
cd "$(dirname "$0")/.."
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart db redis s3 >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait db redis s3 >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart api >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart api upload-cleanup >/dev/null
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait >/dev/null