95 lines
4.5 KiB
Python
95 lines
4.5 KiB
Python
"""Closed-loop: полный путь upload -> ready; ограничение генератора явно в отчёте."""
|
|
import argparse
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import random
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
import zlib
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, check
|
|
|
|
|
|
def png(width, height):
|
|
def chunk(name, data):
|
|
return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name + data))
|
|
rng = random.Random(2301)
|
|
data = b''.join(b'\0' + rng.randbytes(width * 3) for _ in range(height))
|
|
return (b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0))
|
|
+ chunk(b'IDAT', zlib.compress(data)) + chunk(b'IEND', b''))
|
|
|
|
|
|
def percentile(values, q):
|
|
return round(sorted(values)[min(len(values)-1, int((len(values)-1)*q))], 4) if values else None
|
|
|
|
|
|
def main(args):
|
|
client = Client(args.base_url)
|
|
alice, _, _, chat = client.bootstrap()
|
|
profiles = [('320x200', (ROOT / 'tests/fixtures/sample.png').read_bytes()), ('1024x768', png(1024, 768))]
|
|
rows = []
|
|
for profile, raw in profiles:
|
|
for repeat in range(args.repeats):
|
|
samples = []
|
|
failures = []
|
|
stats = []
|
|
stop = threading.Event()
|
|
def sample():
|
|
while not stop.is_set():
|
|
ids = subprocess.check_output(['docker', 'compose', '-p', args.project, 'ps', '-q'], text=True).split()
|
|
result = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{json .}}', *ids], text=True)
|
|
stats.append(dict(at_seconds=round(time.monotonic()-start, 3), containers=[json.loads(line) for line in result.splitlines()]))
|
|
stop.wait(2)
|
|
def one():
|
|
c = Client(args.base_url)
|
|
begin = time.monotonic()
|
|
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=load.png', 202,
|
|
raw=raw, actor=alice, headers={'Content-Type': 'image/png'})['json']
|
|
accepted = time.monotonic()
|
|
ready = c.wait_ready(alice, att)
|
|
check(len(ready['variants']) == 3 and ready['sha256'] == hashlib.sha256(raw).hexdigest(), 'bad load result')
|
|
return dict(upload_seconds=accepted-begin, ready_seconds=time.monotonic()-begin)
|
|
# Один завершённый прогрев на профиль/повтор, не входит в измерение.
|
|
one()
|
|
start = time.monotonic()
|
|
sampler = threading.Thread(target=sample)
|
|
sampler.start()
|
|
def loop(_):
|
|
while time.monotonic()-start < args.duration:
|
|
try:
|
|
samples.append(one())
|
|
except Exception as exc:
|
|
failures.append(type(exc).__name__ + ': ' + str(exc))
|
|
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
|
list(pool.map(loop, range(args.concurrency)))
|
|
elapsed = time.monotonic()-start
|
|
stop.set()
|
|
sampler.join()
|
|
times = [x['ready_seconds'] for x in samples]
|
|
row = dict(profile=profile, bytes_per_image=len(raw), repeat=repeat+1, concurrency=args.concurrency,
|
|
requested_duration=args.duration, elapsed_seconds=round(elapsed, 3), warmup_completed=1,
|
|
completed=len(samples), successful_rps=round(len(samples)/elapsed, 3), failures=failures,
|
|
error_fraction=len(failures)/max(1,len(samples)+len(failures)),
|
|
p50=percentile(times,.5), p95=percentile(times,.95), p99=percentile(times,.99),
|
|
upload_p95=percentile([x['upload_seconds'] for x in samples],.95), stats=stats)
|
|
rows.append(row)
|
|
(ROOT / 'evidence/load-pipeline.json').write_text(json.dumps(rows, indent=2), encoding='utf-8')
|
|
print(json.dumps({k:v for k,v in row.items() if k != 'stats'}), flush=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
p = argparse.ArgumentParser()
|
|
p.add_argument('--base-url', default='http://127.0.0.1:8085')
|
|
p.add_argument('--project', default='lyakhonov-lab5')
|
|
p.add_argument('--duration', type=int, default=20)
|
|
p.add_argument('--concurrency', type=int, default=2)
|
|
p.add_argument('--repeats', type=int, default=3)
|
|
main(p.parse_args())
|