forked from mtusi2026/mtusi2026lab4
80 lines
4.6 KiB
Python
Executable File
80 lines
4.6 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Пик памяти реплик на худших допустимых файлах. Нужен Pillow: .venv/bin/pip install pillow.
|
||
|
||
Запускать на только что запущенных репликах, иначе пик включает более ранние нагрузки.
|
||
|
||
Критерий: нет OOM и перезапусков, анонимная память ниже лимита контейнера. memory.peak только
|
||
выводится: он включает вытесняемый дисковый кэш временных файлов, поэтому может дойти до лимита без
|
||
всякой опасности (ядро просто освобождает кэш). Счётчик max показывает, сколько раз это случилось.
|
||
"""
|
||
from concurrent.futures import ThreadPoolExecutor
|
||
import io
|
||
import subprocess
|
||
|
||
from PIL import Image
|
||
|
||
from common import Client, MAX_BYTES, arguments, check, run
|
||
from memory_concurrent import LIMIT, MIB, Sampler, container_read, memory_event, replicas
|
||
|
||
Image.MAX_IMAGE_PIXELS = None
|
||
|
||
|
||
def report(label, sampler):
|
||
values = []
|
||
for container in sampler.containers:
|
||
values.append('%s: anon %d, memory.peak %d МиБ, упоров в лимит %d, oom_kill=%d' % (
|
||
container[:12], sampler.peak[container] // MIB, int(container_read(container, '/sys/fs/cgroup/memory.peak')) // MIB,
|
||
memory_event(container, 'max'), memory_event(container, 'oom_kill')))
|
||
print(label, *values, sep='\n ', flush=True)
|
||
for container in sampler.containers:
|
||
check(sampler.peak[container] < LIMIT and memory_event(container, 'oom_kill') == 0, 'replica ran out of memory')
|
||
|
||
|
||
def main():
|
||
args = arguments('Peak memory on worst allowed uploads', None)
|
||
c = Client(args.base_url, args.ca_file, timeout=120)
|
||
alice, _, _, chat = c.bootstrap()
|
||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=x'
|
||
containers = replicas()
|
||
sampler = Sampler(containers)
|
||
sampler.start()
|
||
report('до загрузок', sampler)
|
||
|
||
def upload(data, content_type, client=c):
|
||
return client.call('POST', path, [201, 429], actor=alice, raw=data, headers={'Content-Type': content_type})
|
||
|
||
# Прогрессивный JPEG 4:4:4 — самый затратный вариант: декодер хранит коэффициенты всех компонентов.
|
||
picture = Image.effect_noise((400, 250), 60).convert('RGB').resize((8000, 5000))
|
||
buffer = io.BytesIO()
|
||
picture.save(buffer, 'JPEG', progressive=True, quality=40, subsampling=0)
|
||
check(len(buffer.getvalue()) <= MAX_BYTES, 'test file exceeds byte limit')
|
||
for _ in range(4):
|
||
response = upload(buffer.getvalue(), 'image/jpeg')
|
||
check(response['status'] == 201, 'worst-case JPEG rejected')
|
||
report('4 x JPEG 40 Мп, progressive 4:4:4', sampler)
|
||
|
||
# Худший случай целиком: тот же JPEG, дополненный до 10 МиБ нулями после конца изображения.
|
||
# Декодируется один файл за раз, остальные ждут своей очереди во временных файлах, а не в памяти.
|
||
big = buffer.getvalue() + b'\0' * (MAX_BYTES - len(buffer.getvalue()))
|
||
|
||
def parallel(_):
|
||
return upload(big, 'image/jpeg', Client(args.base_url, args.ca_file, timeout=120))['status']
|
||
with ThreadPoolExecutor(max_workers=24) as pool:
|
||
statuses = list(pool.map(parallel, range(24)))
|
||
print('24 одновременные загрузки JPEG 40 Мп по 10 МиБ: 201=%d, 429=%d (очередь на декодирование)' % (statuses.count(201), statuses.count(429)))
|
||
check(statuses.count(201) + statuses.count(429) == len(statuses), 'unexpected status')
|
||
report('после параллельных загрузок', sampler)
|
||
sampler.done.set()
|
||
sampler.join()
|
||
for container in containers:
|
||
state = subprocess.run(['docker', 'inspect', '--format', '{{.State.OOMKilled}} {{.RestartCount}}', container], check=True, capture_output=True, text=True).stdout.split()
|
||
check(state == ['false', '0'], 'replica was OOM-killed or restarted')
|
||
# Реплика после всего этого обслуживает запросы.
|
||
c.call('GET', '/health/ready', schema='Health')
|
||
print('OOMKilled=false, RestartCount=0 у всех реплик, readiness 200')
|
||
print('PASS: no OOM or restart, anonymous memory stays below the %d MiB container limit' % (LIMIT // MIB))
|
||
|
||
|
||
if __name__ == '__main__':
|
||
run(main)
|