79 lines
4.1 KiB
Python
79 lines
4.1 KiB
Python
"""Ten barrier-synchronized uploads + cgroup v2 memory/CPU sampling, lab4 only."""
|
|
import json
|
|
import math
|
|
import os
|
|
from pathlib import Path
|
|
import statistics
|
|
import subprocess
|
|
import sys
|
|
import threading
|
|
import time
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
from negative import png
|
|
from client import Client
|
|
|
|
|
|
def main():
|
|
c = Client(os.getenv('BASE_URL', 'http://localhost:8084'), timeout=45)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
# Random RGB is poorly compressible; ~7.3 MiB per original, no fixture in Git.
|
|
width = height = 1600
|
|
raw = b''.join(b'\0' + os.urandom(width * 3) for _ in range(height))
|
|
image = png(width, height, raw)
|
|
del raw
|
|
compose = ['docker', 'compose', '--env-file', '.env']
|
|
containers = subprocess.check_output(compose + ['ps', '-q', 'api'], text=True).split()
|
|
code = '''import json,time
|
|
from pathlib import Path
|
|
root=Path('/sys/fs/cgroup')
|
|
def cpu():
|
|
return int(dict(line.split() for line in (root/'cpu.stat').read_text().splitlines())['usage_usec'])
|
|
start=time.monotonic(); first=cpu(); values=[]
|
|
while time.monotonic()-start < 20:
|
|
values.append(int((root/'memory.current').read_text()))
|
|
time.sleep(.02)
|
|
print(json.dumps({'sample_count':len(values),'sampled_baseline_bytes':values[0],'sampled_peak_bytes':max(values),'cgroup_lifetime_peak_bytes':int((root/'memory.peak').read_text()),'elapsed_seconds':time.monotonic()-start,'cpu_usage_seconds':(cpu()-first)/1e6}))'''
|
|
samplers = [subprocess.Popen(['docker', 'exec', name, 'python', '-c', code], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for name in containers]
|
|
time.sleep(1)
|
|
barrier = threading.Barrier(10)
|
|
def worker(index):
|
|
local = Client(c.base, timeout=45)
|
|
barrier.wait()
|
|
started = time.monotonic()
|
|
try:
|
|
response = local.call('POST', '/api/v1/chats/'+chat['id']+'/attachments?filename=load-'+str(index)+'.png', 201, actor=alice, raw=image, headers={'Content-Type':'image/png'}, schema='Attachment')
|
|
return {'ok': True, 'seconds': time.monotonic()-started, 'instance': response['headers']['X-Instance-Id']}
|
|
except Exception as exc:
|
|
return {'ok': False, 'seconds': time.monotonic()-started, 'error': type(exc).__name__}
|
|
started = time.monotonic()
|
|
with ThreadPoolExecutor(max_workers=10) as pool:
|
|
results = list(pool.map(worker, range(10)))
|
|
elapsed = time.monotonic() - started
|
|
metrics = []
|
|
for name, proc in zip(containers, samplers):
|
|
out, err = proc.communicate(timeout=30)
|
|
if proc.returncode:
|
|
raise RuntimeError('cgroup sampler failed')
|
|
record = json.loads(out)
|
|
record['container'] = name[:12]
|
|
record['average_cpu_percent_one_core'] = 100 * record['cpu_usage_seconds'] / record['elapsed_seconds']
|
|
metrics.append(record)
|
|
latencies = sorted(x['seconds'] for x in results if x['ok'])
|
|
successes = len(latencies)
|
|
report = {'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), 'concurrency': 10, 'requests': 10,
|
|
'original_bytes': len(image), 'dimensions': [width,height], 'successful_requests': successes,
|
|
'failed_requests': 10-successes, 'elapsed_seconds': elapsed, 'successful_rps': successes/elapsed,
|
|
'latency_success_seconds': {p: latencies[max(0, math.ceil(q*len(latencies))-1)] if latencies else None for p,q in [('p50',.5),('p95',.95),('p99',.99)]},
|
|
'api_cgroups': metrics, 'requests_detail': results,
|
|
'limitations': 'One local closed-loop batch; client overhead; no capacity claim. cgroup memory.current sampled every 20ms includes decoder and tmpfs/page cache; may miss shorter peaks. memory.peak is lifetime, includes earlier work. CPU averaged over 20s sampling window includes idle time. Per-API peaks need not be simultaneous.',
|
|
'docker_host': subprocess.check_output(['docker','info','--format','{{.Architecture}} CPUs={{.NCPU}} RAM={{.MemTotal}}'],text=True).strip()}
|
|
text=json.dumps(report,indent=2)
|
|
Path('evidence/upload-load.json').write_text(text+'\n')
|
|
print(text)
|
|
if successes != 10:
|
|
raise SystemExit(1)
|
|
|
|
if __name__=='__main__':
|
|
main()
|