Проверять содержимое изображений: байты фильтра PNG и настоящее декодирование JPEG

This commit is contained in:
2026-10-31 04:06:58 +03:00
parent d812d8f8d8
commit d34d0bec79
26 changed files with 1024 additions and 427 deletions
+28 -5
View File
@@ -1,9 +1,12 @@
#!/usr/bin/env python3
"""Пик памяти реплик API при одновременных загрузках файлов около 10 MiB.
"""Пик памяти реплик API при одновременных загрузках файлов около 10 MiB и самых тяжёлых JPEG.
Перед замером реплики перезапускаются, чтобы обнулить VmHWM (пик памяти процесса). Уровни идут по
возрастанию, поэтому VmHWM после каждого уровня показывает пик этого уровня. memory.peak контейнера
больше: в него входит кэш страниц временных файлов, который система может освободить.
Последний уровень — прогрессивный CMYK JPEG на 40 млн пикселей: декодер держит коэффициенты всего
изображения, это худший случай для памяти. Загрузки идут параллельно, декодирование по одному на реплику.
"""
import argparse
import json
@@ -20,6 +23,13 @@ from api import call, new_chat, new_user
from samples import noisy_png
LEVELS = (1, 10, 30)
HEAVY_UPLOADS = 10
MAKE_HEAVY_JPEG = """
import sys
from PIL import Image
image = Image.effect_noise((7300 // 16, 5470 // 16), 40).resize((7300, 5470)).convert("CMYK")
image.save(sys.stdout.buffer, "JPEG", quality=50, progressive=True)
"""
def compose(*args):
@@ -53,6 +63,12 @@ def wait_ready():
time.sleep(0.2)
def heavy_jpeg():
# в отдельном контейнере: создание такого файла требует много памяти, реплику это не должно затрагивать
command = ["docker", "run", "--rm", "-i", "--memory=2g", "--entrypoint", "python", "mtusi-messenger:lab4", "-"]
return subprocess.run(command, input=MAKE_HEAVY_JPEG.encode(), check=True, capture_output=True).stdout
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--output")
@@ -64,20 +80,23 @@ def main():
chat = new_chat(user)
path = "/api/v1/chats/%s/attachments?filename=peak.png" % urllib.parse.quote(chat["id"])
levels = [{"parallel_uploads": 0, "memory": memory()}]
for level in LEVELS:
def run_level(level, content, content_type, label):
started = time.monotonic()
def post(_):
sent = time.monotonic()
status = call("POST", path, raw=data, user=user, headers={"Content-Type": "image/png"}, timeout=60)[0]
headers = {"Content-Type": content_type}
status = call("POST", path, raw=content, user=user, headers=headers, timeout=60)[0]
return status, time.monotonic() - sent
with ThreadPoolExecutor(max_workers=level) as pool:
results = list(pool.map(post, range(level)))
statuses = [status for status, _ in results]
entry = {
"file": label,
"parallel_uploads": level,
"file_bytes": len(data),
"file_bytes": len(content),
"seconds": round(time.monotonic() - started, 2),
"slowest_upload_s": round(max(took for _, took in results), 2),
"statuses": {str(s): statuses.count(s) for s in sorted(set(statuses))},
@@ -85,7 +104,11 @@ def main():
}
print(json.dumps(entry, ensure_ascii=False))
levels.append(entry)
report = {"limit_per_replica_mib": 256, "replicas": 2, "levels": levels}
for level in LEVELS:
run_level(level, data, "image/png", "PNG 10 MiB")
run_level(HEAVY_UPLOADS, heavy_jpeg(), "image/jpeg", "прогрессивный CMYK JPEG, 40 млн пикселей")
report = {"limit_per_replica_mib": 512, "replicas": 2, "levels": levels}
if args.output:
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
if any(set(level.get("statuses", {"201": 1})) != {"201"} for level in levels):