Files
mtusi2026lab3/student-tests/scaling.py
T

81 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""1/2/4 replicas, fixed and growing resources, raw cgroups and pool diagnostics."""
import json,os,platform,statistics,subprocess,sys,time,threading
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'))
from client import Client,check
BASE='http://localhost:8083'
ENV=dict(os.environ,POOL_DIAGNOSTICS='1')
def dc(*a,env=None):return subprocess.check_output(['docker','compose',*a],cwd=ROOT,env=env or ENV,text=True,stderr=subprocess.DEVNULL).strip()
def snapshot():
result={}
for service in ['api','postgres','lb']:
for id in dc('ps','-q',service).splitlines():
raw=subprocess.check_output(['docker','exec',id,'sh','-c','cat /sys/fs/cgroup/cpu.stat; cat /sys/fs/cgroup/memory.current /sys/fs/cgroup/memory.peak'],text=True).splitlines()
values={};numbers=[]
for line in raw:
items=line.split()
if len(items)==2:values[items[0]]=int(items[1])
else:numbers.append(int(line))
result[id[:12]]={'service':service,'usage_usec':values['usage_usec'],'nr_throttled':values['nr_throttled'],'throttled_usec':values['throttled_usec'],'memory_current':numbers[0],'memory_peak':numbers[1]}
return result
def main():
binary=ROOT/'bin/bench';binary.parent.mkdir(exist_ok=True)
subprocess.run(['go','build','-o',str(binary),'./cmd/bench'],cwd=ROOT,env=dict(os.environ,GOCACHE='/private/tmp/highload-go-cache'),check=True)
redo=set(filter(None,os.environ.get('SCALING_REDO','').split(',')))
report={'host':{'platform':platform.platform(),'machine':platform.machine(),'logical_cpus':os.cpu_count(),'docker':subprocess.check_output(['docker','info','--format','{{.Architecture}} CPUs={{.NCPU}} Memory={{.MemTotal}}'],text=True).strip()},'method':{'warmup_seconds':2,'duration_seconds':6,'repetitions':2,'chats':16,'profile':'one immutable ~128-character POST per worker, uniform round-robin among 16 chats; fresh unique key; no retry; successful percentiles; closed loop'},'runs':[]}
if redo:report=json.loads((ROOT/'evidence/scaling.json').read_text())
def configure(n,cpu,memory,pool=10):
env=dict(ENV,API_REPLICAS=str(n),API_CPUS=str(cpu),API_MEMORY=str(memory)+'m',DB_POOL_MAX=str(pool))
dc('up','-d','--no-deps','--scale','api='+str(n),'--force-recreate','--wait','api',env=env)
time.sleep(3)
return env
def bench(fixture,concurrency,duration):
waits=[];stop=threading.Event()
def observe():
while not stop.is_set():
try:waits.append(dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc',"SELECT coalesce(wait_event_type,'CPU')||':'||coalesce(wait_event,'running')||':'||count(*) FROM pg_stat_activity WHERE datname='messenger' AND pid<>pg_backend_pid() AND state<>'idle' GROUP BY wait_event_type,wait_event"))
except subprocess.CalledProcessError:pass
stop.wait(.5)
monitor=threading.Thread(target=observe);monitor.start()
try:output=subprocess.check_output([str(binary),'-base',BASE,'-concurrency',str(concurrency),'-duration',str(duration)+'s'],input=json.dumps(fixture),text=True)
finally:stop.set();monitor.join()
result=json.loads(output);result['pg_wait_samples']=waits;return result
try:
for series in ['fixed','growing']:
for n in [1,2,4]:
if redo and series+':'+str(n) not in redo:continue
if redo:report['runs']=[r for r in report['runs'] if not (r['series']==series and r['replicas']==n)]
cpu=2/n if series=='fixed' else 1;memory=1024//n if series=='fixed' else 512
configure(n,cpu,memory)
c=Client(BASE);a=c.user('scaling');chats=[]
for i in range(16):chats.append(c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Scaling','member_ids':[a['id']]},schema='Chat')['json']['id'])
fixture={'token':a['token'],'chats':chats}
for clients in [4,16,64]:
bench(fixture,clients,2)
for repeat in range(2):
before=snapshot();started=time.time();result=bench(fixture,clients,6);after=snapshot()
result.update(started_unix=started,series=series,replicas=n,cpu_per_api=cpu,memory_mib_per_api=memory,pool_per_api=10,repeat=repeat+1,cgroup_before=before,cgroup_after=after)
for id,stat in after.items():
stat['cpu_percent']=100*(stat['usage_usec']-before[id]['usage_usec'])/1e6/(time.time()-started)
result['messages_in_database_after']=int(dc('exec','-T','postgres','psql','-U','messenger','-d','messenger','-Atqc','SELECT count(*) FROM messages'))
report['runs'].append(result);(ROOT/'evidence/scaling.json').write_text(json.dumps(report,indent=2)+'\n')
print(series,n,clients,repeat+1,round(result['successful_rps']),flush=True)
# Deliberate pool starvation baseline and one measured improvement.
for pool in [1,10]:
if redo and 'pool' not in redo:continue
if redo:report['runs']=[r for r in report['runs'] if not (r['series']=='pool_improvement' and r['pool_per_api']==pool)]
configure(2,1,512,pool)
c=Client(BASE);a=c.user('pool');chats=[c.call('POST','/api/v1/chats',201,actor=a,body={'title':'Pool','member_ids':[a['id']]},schema='Chat')['json']['id'] for _ in range(16)]
fixture={'token':a['token'],'chats':chats};bench(fixture,32,2)
for rep in range(3):
result=bench(fixture,32,6);result.update(series='pool_improvement',replicas=2,pool_per_api=pool,repeat=rep+1)
report['runs'].append(result)
report.setdefault('pool_diagnostics',{})[str(pool)]=[json.loads(line) for line in dc('logs','--no-log-prefix','--tail','10000','api').splitlines() if line.startswith('{') and '"msg":"pool"' in line]
(ROOT/'evidence/scaling.json').write_text(json.dumps(report,indent=2)+'\n')
finally:dc('up','-d','--no-deps','--scale','api=2','--force-recreate','--wait','api',env=dict(os.environ,API_REPLICAS='2',API_CPUS='1',API_MEMORY='256m',DB_POOL_MAX='10'))
print('DONE',flush=True)
if __name__=='__main__':main()