JPEG проверяется через djpeg -strict: обрезанный поток с дописанным EOI теперь даёт 415. Память nginx больше не зависит от тел файлов: загрузка идёт потоком до API, скачивание без временных файлов, воркеров 2. API не закрывает соединение при недочитанном теле, что давало HTML 502; nginx сам отклоняет тела больше лимитов API. Лимит памяти API поднят до 512 MiB под проверку CMYK-JPEG на 40 Мпикс. Добавлен стресс-тест через LB.
211 lines
9.6 KiB
Python
211 lines
9.6 KiB
Python
#!/usr/bin/env python3
|
|
"""LB under upload pressure: no OOM/restart of any container, no HTML 502, every rejection is API-shaped JSON.
|
|
python3 student-tests/test_lb_stress.py --concurrency 10 --rounds 3 --oversize 200"""
|
|
import argparse
|
|
import base64
|
|
import collections
|
|
import http.client
|
|
import json
|
|
import os
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import uuid
|
|
import zlib
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
HOST, PORT = "localhost", 8080
|
|
LIMIT = 10485760
|
|
|
|
|
|
def noise_png(side):
|
|
raw = b"".join(b"\0" + os.urandom(side * 3) for _ in range(side))
|
|
|
|
def chunk(kind, body):
|
|
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
|
|
|
|
ihdr = struct.pack(">IIBBBBB", side, side, 8, 2, 0, 0, 0)
|
|
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 1)) + chunk(b"IEND", b"")
|
|
|
|
|
|
def request(method, path, body=None, headers=None, timeout=90):
|
|
"""Returns (status, content_type, payload) or ('EXC:<name>', '', b'')."""
|
|
conn = http.client.HTTPConnection(HOST, PORT, timeout=timeout)
|
|
try:
|
|
conn.request(method, path, body=body, headers=headers or {})
|
|
response = conn.getresponse()
|
|
return response.status, response.getheader("Content-Type", ""), response.read()
|
|
except Exception as exc:
|
|
return "EXC:" + type(exc).__name__, "", b""
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def actor(label):
|
|
username = "st_%s_%s" % (label, uuid.uuid4().hex[:10])
|
|
password = "T3st-" + uuid.uuid4().hex
|
|
body = {"username": username, "display_name": label, "password": password}
|
|
status, _, _ = request("POST", "/api/v1/users", json.dumps(body), {"Content-Type": "application/json"})
|
|
assert status == 201, status
|
|
basic = base64.b64encode((username + ":" + password).encode()).decode()
|
|
status, _, data = request("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
|
assert status == 201, status
|
|
session = json.loads(data)
|
|
return session["user"]["id"], {"Authorization": "Bearer " + session["token"]}
|
|
|
|
|
|
def container_ids():
|
|
out = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
|
|
names = {}
|
|
for cid in out:
|
|
name = subprocess.run(["docker", "inspect", "--format", "{{.Name}}", cid], capture_output=True, text=True).stdout
|
|
names[cid] = name.strip().lstrip("/")
|
|
return names
|
|
|
|
|
|
def peak_mib(name):
|
|
out = subprocess.run(["docker", "exec", name, "cat", "/sys/fs/cgroup/memory.peak"], capture_output=True, text=True)
|
|
return round(int(out.stdout) / 1048576, 1) if out.stdout.strip().isdigit() else None
|
|
|
|
|
|
class Events(threading.Thread):
|
|
def __init__(self):
|
|
super().__init__(daemon=True)
|
|
self.lines = []
|
|
self.proc = subprocess.Popen(
|
|
["docker", "events", "--filter", "type=container", "--filter", "event=oom", "--filter", "event=die",
|
|
"--filter", "event=restart", "--format", "{{.Action}} {{.Actor.Attributes.name}} exit={{.Actor.Attributes.exitCode}}"],
|
|
stdout=subprocess.PIPE, text=True,
|
|
)
|
|
|
|
def run(self):
|
|
for line in self.proc.stdout:
|
|
self.lines.append(line.strip())
|
|
|
|
def stop(self):
|
|
self.proc.terminate()
|
|
|
|
|
|
def is_json_error(result, code):
|
|
status, ctype, data = result
|
|
if status != code or not ctype.startswith("application/json"):
|
|
return False
|
|
return json.loads(data)["error"]["code"]
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument("--concurrency", type=int, default=10)
|
|
parser.add_argument("--rounds", type=int, default=3)
|
|
parser.add_argument("--oversize", type=int, default=200)
|
|
args = parser.parse_args()
|
|
# memory.peak is cumulative since container start, so read it after a fresh recreate.
|
|
|
|
failures = []
|
|
events = Events()
|
|
events.start()
|
|
uid, auth = actor("a")
|
|
_, outsider = actor("b")
|
|
status, _, data = request("POST", "/api/v1/chats", json.dumps({"title": "stress", "member_ids": [uid]}),
|
|
{**auth, "Content-Type": "application/json"})
|
|
assert status == 201, status
|
|
chat = json.loads(data)["id"]
|
|
upload = "/api/v1/chats/%s/attachments?filename=s.png" % chat
|
|
png_headers = {**auth, "Content-Type": "image/png"}
|
|
|
|
body = noise_png(1700)
|
|
print("== %d parallel uploads of %d bytes, %d rounds ==" % (args.concurrency, len(body), args.rounds))
|
|
ids, tally = [], collections.Counter()
|
|
for _ in range(args.rounds):
|
|
with ThreadPoolExecutor(args.concurrency) as pool:
|
|
results = list(pool.map(lambda _: request("POST", upload, body, png_headers), range(args.concurrency)))
|
|
for status, _, data in results:
|
|
tally[status] += 1
|
|
if status == 201:
|
|
ids.append(json.loads(data)["id"])
|
|
print("upload statuses:", dict(tally))
|
|
if set(tally) != {201}:
|
|
failures.append("parallel uploads: %s" % dict(tally))
|
|
|
|
print("== %d parallel downloads ==" % args.concurrency)
|
|
with ThreadPoolExecutor(args.concurrency) as pool:
|
|
results = list(pool.map(lambda i: request("GET", "/api/v1/attachments/%s/content" % i, headers=auth),
|
|
ids[:args.concurrency * 2]))
|
|
tally = collections.Counter(r[0] for r in results)
|
|
print("download statuses:", dict(tally))
|
|
if set(tally) != {200} or any(r[2] != body for r in results):
|
|
failures.append("parallel downloads: %s" % dict(tally))
|
|
|
|
print("== %d parallel valid 40 Mpx progressive CMYK JPEGs (worst case for the checker), %d rounds ==" % (args.concurrency, args.rounds))
|
|
jpeg = subprocess.run(
|
|
["docker", "run", "--rm", "--entrypoint", "python", "mtusi-messenger:lab4", "-c",
|
|
"import io,sys;from PIL import Image;b=io.BytesIO();"
|
|
"Image.new('CMYK',(8000,5000),(120,30,200,5)).save(b,'JPEG',quality=90,progressive=True);"
|
|
"sys.stdout.buffer.write(b.getvalue())"], capture_output=True, check=True).stdout
|
|
tally = collections.Counter()
|
|
for _ in range(args.rounds):
|
|
with ThreadPoolExecutor(args.concurrency) as pool:
|
|
results = list(pool.map(lambda _: request("POST", upload, jpeg, {**auth, "Content-Type": "image/jpeg"}),
|
|
range(args.concurrency)))
|
|
tally.update(r[0] for r in results)
|
|
print("upload statuses:", dict(tally))
|
|
if set(tally) != {201}:
|
|
failures.append("parallel progressive JPEG: %s" % dict(tally))
|
|
|
|
cases = [
|
|
("10 MiB + 1 byte, Content-Length", upload, b"\x89PNG\r\n\x1a\n" + b"\0" * (LIMIT - 7), png_headers, 413, "payload_too_large"),
|
|
("10 MiB + 1 byte, chunked", upload, iter([b"\x89PNG\r\n\x1a\n" + b"\0" * (LIMIT - 7)]), png_headers, 413, "payload_too_large"),
|
|
("10 MiB + 1 byte, chunked in 64 KiB pieces", upload,
|
|
[b"\x89PNG\r\n\x1a\n"] + [b"\0" * 65536] * 160, png_headers, 413, "payload_too_large"),
|
|
("8 MiB to a foreign chat", upload, b"\x89PNG\r\n\x1a\n" + b"\0" * (8 << 20), {**outsider, "Content-Type": "image/png"}, 404, "not_found"),
|
|
("8 MiB without session", upload, b"\x89PNG\r\n\x1a\n" + b"\0" * (8 << 20), {"Content-Type": "image/png"}, 401, "unauthorized"),
|
|
("8 MiB with wrong magic", upload, b"X" * (8 << 20), png_headers, 415, "unsupported_media_type"),
|
|
("8 MiB with wrong Content-Type", upload, b"X" * (8 << 20), {**auth, "Content-Type": "image/gif"}, 415, "unsupported_media_type"),
|
|
("70 KiB JSON message", "/api/v1/chats/%s/messages" % chat, b'{"text":"' + b"x" * (70 << 10) + b'"}',
|
|
{**auth, "Content-Type": "application/json", "Idempotency-Key": "k"}, 413, "payload_too_large"),
|
|
]
|
|
for name, path, payload, headers, code, error in cases:
|
|
print("== %s: %d requests, %d at a time ==" % (name, args.oversize, args.concurrency))
|
|
materialized = list(payload) if not isinstance(payload, bytes) else None
|
|
|
|
def one(_):
|
|
data = payload if materialized is None else iter(materialized)
|
|
extra = {} if materialized is None else {"Transfer-Encoding": "chunked"}
|
|
conn_headers = {**headers, **extra}
|
|
conn = http.client.HTTPConnection(HOST, PORT, timeout=90)
|
|
try:
|
|
conn.request("POST", path, body=data, headers=conn_headers, encode_chunked=materialized is not None)
|
|
response = conn.getresponse()
|
|
return response.status, response.getheader("Content-Type", ""), response.read()
|
|
except Exception as exc:
|
|
return "EXC:" + type(exc).__name__, "", b""
|
|
finally:
|
|
conn.close()
|
|
|
|
with ThreadPoolExecutor(args.concurrency) as pool:
|
|
results = list(pool.map(one, range(args.oversize)))
|
|
tally = collections.Counter((r[0], r[1].split(";")[0]) for r in results)
|
|
print(" ", {"%s %s" % k: v for k, v in tally.items()})
|
|
if not all(is_json_error(r, code) == error for r in results):
|
|
failures.append("%s: %s" % (name, dict(tally)))
|
|
|
|
status, _, _ = request("GET", "/health/ready")
|
|
if status != 200:
|
|
failures.append("not ready after the run: %s" % status)
|
|
events.stop()
|
|
bad = [line for line in events.lines if " mtusi-lab4-" in line]
|
|
print("container events during the run:", bad or "none")
|
|
if bad:
|
|
failures.append("container events: %s" % bad)
|
|
print("cgroup memory.peak, MiB:", {n: peak_mib(n) for n in container_ids().values() if "api-" in n or "nginx" in n})
|
|
for failure in failures:
|
|
print("FAIL:", failure)
|
|
print("PASS: LB stress" if not failures else "FAILED: %d" % len(failures))
|
|
sys.exit(1 if failures else 0)
|
|
|
|
|
|
main()
|