Add four-hour JMeter energy workloads with Gaussian user pacing

This commit is contained in:
Steffen committed 2026-10-07 18:23:20 +02:00
1 parent 23a824dd81
commit 45a040f3a2
14 files changed
+3562

No files matched your search

+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Preflight and run JMeter; record actual timing for external power measurements."""
import argparse, csv, datetime as dt, hashlib, json, os, platform, subprocess, time, ssl, urllib.request
from pathlib import Path
HERE=Path(__file__).resolve().parent
p=argparse.ArgumentParser()
p.add_argument('scenario',choices=['recording','review','correction','professional','mixed','idle'])
p.add_argument('--host',required=True);p.add_argument('--port',type=int,default=5443)
p.add_argument('--ca',required=True);p.add_argument('--users-file');p.add_argument('--users',type=int,default=50)
p.add_argument('--warmup',type=int,default=1800);p.add_argument('--duration',type=int,default=14400);p.add_argument('--ramp',type=int,default=120)
p.add_argument('--think-mean-ms',type=int,default=4000);p.add_argument('--think-stddev-ms',type=int,default=2000)
p.add_argument('--session-pause-ms',type=int,default=120000)
p.add_argument('--session-stddev-ms',type=int,default=30000);p.add_argument('--seed',type=int,default=42)
p.add_argument('--output',required=True);p.add_argument('--jmeter',default=str(Path.home()/'.local/bin/jmeter'))
p.add_argument('--allow-shared-read-account',action='store_true')
a=p.parse_args()
if a.users<1 or a.duration<1 or a.warmup<0 or a.ramp<0 or min(a.think_mean_ms,a.think_stddev_ms,a.session_pause_ms,a.session_stddev_ms)<0: p.error('Invalid timing/concurrency')
if a.scenario!='idle' and not a.users_file: p.error('--users-file is required')
rows=[]
if a.users_file:
with open(a.users_file,newline='') as f:
reader=csv.DictReader(f)
if reader.fieldnames!=['account_id','password','patient_id']: p.error('CSV columns must be account_id,password,patient_id')
rows=list(reader)
if not rows or any(not all(r.values()) or any(c in v for v in r.values() for c in ',\n\r"') for r in rows): p.error('CSV contains empty or unsupported values')
if len({r['account_id'] for r in rows})!=len(rows): p.error('CSV must contain distinct accounts')
if len(rows)<a.users:
if not a.allow_shared_read_account or a.scenario not in ['review','professional']: p.error('Provide at least one distinct account per user. Shared accounts are allowed only for explicitly labelled read-only runs.')
rows=(rows*((a.users+len(rows)-1)//len(rows)))[:a.users]
context=ssl.create_default_context(cafile=a.ca)
with urllib.request.urlopen(f'https://{a.host}:{a.port}/api/measurement-guidance',context=context,timeout=15) as r:
if r.status!=200: p.error('Gateway preflight failed')
# Fail before a long run if accounts, profiles, baseline data or assignments are missing.
def get(path,token=None,body=None):
headers={'Content-Type':'application/json'}
if token: headers['Authorization']='Bearer '+token
req=urllib.request.Request(f'https://{a.host}:{a.port}'+path,headers=headers,data=json.dumps(body).encode() if body else None)
with urllib.request.urlopen(req,context=context,timeout=60) as r: return json.load(r)
now=dt.datetime.now(dt.timezone.utc)
period_from=(now-dt.timedelta(days=31)).replace(hour=0,minute=0,second=0,microsecond=0).isoformat().replace('+00:00','Z')
period_to=(now+dt.timedelta(seconds=a.warmup+a.duration+3600)).isoformat().replace('+00:00','Z')
for row in {r['account_id']:r for r in rows}.values():
login=get('/api/authentication/login',body={'accountId':row['account_id'],'password':row['password']});token=login['accessToken']
if a.scenario=='professional':
if login['role']!='HealthcareProfessional' or not any(x['patientId']==row['patient_id'] for x in get('/api/professionals/me/patients',token)): p.error('Professional account lacks the required assignment')
elif get('/api/patients/me',token)['patientId']!=row['patient_id']: p.error('CSV patient does not belong to its account')
overview=get('/api/patients/'+row['patient_id']+'/overview?from='+period_from+'&to='+period_to,token)
if overview['insight'] is None or overview['latestObservation'] is None: p.error('Seed patient history before running')
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
metadata={'scenario':a.scenario,'users':a.users,'measurement_duration_seconds':a.duration,'warmup_seconds':a.warmup,'ramp_seconds':a.ramp,'think_mean_ms':a.think_mean_ms,'think_stddev_ms':a.think_stddev_ms,'session_pause_ms':a.session_pause_ms,'session_stddev_ms':a.session_stddev_ms,'random_seed':a.seed,'host':a.host,'port':a.port,'period_from':period_from,'period_to':period_to,'load_generator':platform.platform(),'distinct_accounts':len({r['account_id'] for r in rows}),'login':'initial login and renewal before expiry included','energy':'External power meter required; JMeter does not measure energy'}
if a.scenario!='idle':
runtime_csv=out/'runtime-users.csv'
with runtime_csv.open('x') as f:
os.chmod(f.name,0o600); w=csv.DictWriter(f,fieldnames=['account_id','password','patient_id']);w.writeheader();w.writerows(rows)
plan=HERE/'plans'/(a.scenario+'.jmx');metadata['plan_sha256']=hashlib.sha256(plan.read_bytes()).hexdigest()
cmd=[a.jmeter,'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jhost='+a.host,'-Jport='+str(a.port),'-Jusers_file='+str(runtime_csv),'-Jusers='+str(a.users),'-Jduration_seconds='+str(a.duration),'-Jwarmup_seconds='+str(a.warmup),'-Jtotal_duration_seconds='+str(a.warmup+a.duration+5),'-Jtimeline_file='+str(out/'timeline.json'),'-Jramp_seconds='+str(a.ramp),'-Jthink_mean_ms='+str(a.think_mean_ms),'-Jthink_stddev_ms='+str(a.think_stddev_ms),'-Jsession_pause_ms='+str(a.session_pause_ms),'-Jsession_stddev_ms='+str(a.session_stddev_ms),'-Jrandom_seed='+str(a.seed),'-Jperiod_from='+period_from,'-Jperiod_to='+period_to,'-Jjmeter.save.saveservice.output_format=csv','-Jjmeter.save.saveservice.print_field_names=true','-Jjmeter.save.saveservice.response_data=false','-Jjmeter.save.saveservice.samplerData=false','-Jjmeter.save.saveservice.requestHeaders=false','-Jjmeter.save.saveservice.responseHeaders=false']
metadata['jmeter_version']=subprocess.check_output([a.jmeter,'--version'],text=True).strip()
metadata['started_utc']=dt.datetime.now(dt.timezone.utc).isoformat(); started=time.monotonic()
(out/'run.json').write_text(json.dumps(metadata,indent=2))
print('Measurement workload starts:',metadata['started_utc'],flush=True)
code=0
try:
if a.scenario=='idle':
start_ms=time.time_ns()//1000000
(out/'timeline.json').write_text(json.dumps({'warmup_start_ms':start_ms,'measurement_start_ms':start_ms+a.warmup*1000,'measurement_end_ms':start_ms+(a.warmup+a.duration)*1000}))
time.sleep(a.warmup+a.duration)
else: code=subprocess.call(cmd)
except KeyboardInterrupt: code=130
finally:
metadata['finished_utc']=dt.datetime.now(dt.timezone.utc).isoformat();metadata['actual_elapsed_seconds']=time.monotonic()-started;metadata['exit_code']=code
(out/'run.json').write_text(json.dumps(metadata,indent=2))
if a.scenario!='idle': runtime_csv.unlink(missing_ok=True)
if (out/'timeline.json').exists():
timeline=json.loads((out/'timeline.json').read_text());metadata.update(timeline)
for name in ['warmup_start','measurement_start','measurement_end']:
metadata[name+'_utc']=dt.datetime.fromtimestamp(timeline[name+'_ms']/1000,dt.timezone.utc).isoformat()
if a.scenario!='idle' and (out/'samples.csv').exists():
with (out/'samples.csv').open() as f: all_samples=list(csv.DictReader(f))
samples=[r for r in all_samples if r['label'].startswith('HTTP ')]
all_failed=sum(r['success'].lower()!='true' for r in all_samples)
failed=sum(r['success'].lower()!='true' for r in samples)
measured=[r for r in samples if metadata.get('measurement_start_ms',float('inf')) <= int(r['timeStamp']) and int(r['timeStamp'])+int(r['elapsed']) <= metadata.get('measurement_end_ms',0)]
if measured:
with (out/'measured.csv').open('w') as f:
w=csv.DictWriter(f,fieldnames=list(measured[0]));w.writeheader();w.writerows(measured)
latencies=sorted(int(r['elapsed']) for r in measured)
metadata.update(failed_samples_including_scripts=all_failed,http_samples=len(samples),failed_http_samples=failed,measured_http_samples=len(measured),measured_failed_http_samples=sum(r['success'].lower()!='true' for r in measured),measured_http_requests_per_second=len(measured)/a.duration,p95_latency_ms=latencies[min(len(latencies)-1,int(len(latencies)*.95))] if latencies else None)
print(f'HTTP samples: {len(samples)}; failures: {failed}; measured samples: {len(measured)}')
if all_failed or not measured: code=1
if metadata['actual_elapsed_seconds']+2<a.warmup+a.duration: print('Run stopped early; measurement is incomplete');code=1
metadata['exit_code']=code
(out/'run.json').write_text(json.dumps(metadata,indent=2))
raise SystemExit(code)