Collect NUC host metrics live in all JMeter energy scenarios

This commit is contained in:
Steffen committed 2026-10-07 21:03:19 +02:00
1 parent 45a040f3a2
commit a69b9b2118
12 files changed
+602 -21

No files matched your search

+27 -13
View File
@@ -1,7 +1,9 @@
#!/usr/bin/env python3
"""Preflight and run JMeter; record actual timing for external power measurements."""
import xml.etree.ElementTree as E
import argparse, csv, datetime as dt, hashlib, json, os, platform, subprocess, time, ssl, urllib.request
from pathlib import Path
from perfmon import check_agent, summarize
HERE=Path(__file__).resolve().parent
p=argparse.ArgumentParser()
p.add_argument('scenario',choices=['recording','review','correction','professional','mixed','idle'])
@@ -13,9 +15,14 @@ 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')
p.add_argument('--perfmon-host');p.add_argument('--perfmon-port',type=int,default=4444)
p.add_argument('--perfmon-interval-ms',type=int,default=5000);p.add_argument('--no-perfmon',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')
if a.perfmon_interval_ms<1000 or a.perfmon_interval_ms%1000: p.error('PerfMon interval must be a whole number of seconds, at least 1000 ms')
agent_host=a.perfmon_host or a.host
if not a.no_perfmon: check_agent(agent_host,a.perfmon_port)
rows=[]
if a.users_file:
with open(a.users_file,newline='') as f:
@@ -48,28 +55,29 @@ for row in {r['account_id']:r for r in rows}.values():
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()
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)
source_plan=HERE/'plans'/(a.scenario+'.jmx');metadata['plan_sha256']=hashlib.sha256(source_plan.read_bytes()).hexdigest()
plan=out/'runtime.jmx'; document=E.parse(source_plan)
for collector in document.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):
collector.set('enabled','false' if a.no_perfmon else 'true')
document.write(plan,encoding='utf-8',xml_declaration=True)
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.autoflush=true','-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()
cmd += ['-Jperfmon_host='+agent_host,'-Jperfmon_port='+str(a.perfmon_port),'-Jperfmon_file='+str(out/'perfmon.csv'),'-JjmeterPlugin.perfmon.interval='+str(a.perfmon_interval_ms),'-JjmeterPlugin.perfmon.useUDP=false']
metadata['perfmon']={'enabled':not a.no_perfmon,'host':agent_host,'port':a.perfmon_port,'interval_ms':a.perfmon_interval_ms}
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)
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)
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']:
@@ -88,6 +96,12 @@ if a.scenario!='idle' and (out/'samples.csv').exists():
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
if not a.no_perfmon:
try:
metadata['server_metrics']=summarize(out/'perfmon.csv',out/'perfmon-measured.csv',metadata['measurement_start_ms'],metadata['measurement_end_ms'],a.perfmon_interval_ms)
print('Live PerfMon metrics saved and measurement interval validated')
except (OSError,ValueError,KeyError) as error:
metadata['monitoring_error']=str(error);print('Invalid monitoring:',error);code=1
metadata['exit_code']=code
(out/'run.json').write_text(json.dumps(metadata,indent=2))
raise SystemExit(code)