Complete Lab 4 attachment service
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Upload ten decoded 3000x3000 PNGs concurrently and sample Docker API memory."""
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import zlib
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check
|
||||
|
||||
|
||||
def png_chunk(kind: bytes, payload: bytes) -> bytes:
|
||||
return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def large_decode_png(width=3000, height=3000) -> bytes:
|
||||
row = b"\x00" + (b"\x28\x80\xc0" * width)
|
||||
compressor = zlib.compressobj(level=6)
|
||||
compressed = bytearray()
|
||||
for _ in range(height):
|
||||
compressed.extend(compressor.compress(row))
|
||||
compressed.extend(compressor.flush())
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", bytes(compressed)) + png_chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def memory_mib(containers):
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{.ID}}|{{.MemUsage}}", *containers],
|
||||
check=True, capture_output=True, text=True, timeout=10,
|
||||
)
|
||||
samples = {}
|
||||
for line in result.stdout.splitlines():
|
||||
fields = line.split("|", 1)
|
||||
if len(fields) != 2:
|
||||
continue
|
||||
number = fields[1].split("/", 1)[0].strip().split()[0]
|
||||
match = re.fullmatch(r"([0-9.]+)(B|KiB|MiB|GiB)", number)
|
||||
if not match:
|
||||
continue
|
||||
value = float(match.group(1))
|
||||
value_mib = value * {"GiB": 1024, "MiB": 1, "KiB": 1 / 1024, "B": 1 / (1024 * 1024)}[match.group(2)]
|
||||
samples[fields[0]] = value_mib
|
||||
return samples
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default=None)
|
||||
parser.add_argument("--ca-file", default=None)
|
||||
parser.add_argument("--concurrency", type=int, default=10)
|
||||
parser.add_argument("--output", default="evidence/upload-memory.json")
|
||||
args = parser.parse_args()
|
||||
check(args.concurrency >= 10, "grade 4 memory run requires at least 10 concurrent clients")
|
||||
client = Client(args.base_url, args.ca_file, timeout=90)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
image = large_decode_png()
|
||||
containers = subprocess.check_output(
|
||||
["docker", "compose", "--env-file", ".env", "ps", "-q", "api"], text=True, timeout=10,
|
||||
).split()
|
||||
check(len(containers) >= 2, "start at least two API replicas behind the load balancer")
|
||||
before = memory_mib(containers)
|
||||
peak = dict(before)
|
||||
stop = threading.Event()
|
||||
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
for container, value in memory_mib(containers).items():
|
||||
peak[container] = max(peak.get(container, 0), value)
|
||||
except (subprocess.SubprocessError, OSError):
|
||||
pass
|
||||
stop.wait(0.25)
|
||||
|
||||
monitor = threading.Thread(target=sample, daemon=True)
|
||||
monitor.start()
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=memory-probe.png"
|
||||
|
||||
def upload(_index):
|
||||
request = urllib.request.Request(
|
||||
client.base + path,
|
||||
data=image,
|
||||
headers={"Authorization": "Bearer " + alice["token"], "Content-Type": "image/png"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with client.opener.open(request, timeout=90) as response:
|
||||
response.read(1024 * 1024)
|
||||
check(response.status == 201, "upload did not return 201")
|
||||
return response.headers.get("X-Instance-Id", "")
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise AssertionError(f"upload returned HTTP {exc.code}") from None
|
||||
|
||||
started = time.monotonic()
|
||||
successes = []
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
futures = [pool.submit(upload, i) for i in range(args.concurrency)]
|
||||
for future in as_completed(futures):
|
||||
successes.append(future.result())
|
||||
finally:
|
||||
stop.set()
|
||||
monitor.join(timeout=3)
|
||||
report = {
|
||||
"concurrent_clients": args.concurrency,
|
||||
"successful_uploads": len(successes),
|
||||
"decoded_dimensions": [3000, 3000],
|
||||
"input_bytes": len(image),
|
||||
"container_memory_mib_before": before,
|
||||
"container_memory_mib_peak": peak,
|
||||
"elapsed_seconds": round(time.monotonic() - started, 3),
|
||||
"observed_instances": sorted({item for item in successes if item}),
|
||||
}
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
|
||||
print(json.dumps(report, separators=(",", ":")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user