Record architecture B corrections and measurement tooling

This commit is contained in:
Steffen committed 2026-11-23 00:01:07 +01:00
1 parent 097d156c18
commit 6ea20b2365
78 files changed
+45820 -67

No files matched your search

+151
View File
@@ -0,0 +1,151 @@
#!/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 tls import application_context
from pathlib import Path
from perfmon import check_agent, summarize
import shelly
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');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-min-ms',type=int,default=500);p.add_argument('--think-mean-ms',type=int,default=1000);p.add_argument('--think-stddev-ms',type=int,default=250)
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('--capacity-trial',action='store_true',help='Read-only trial: restart a session after an error so the configured duration is retained')
p.add_argument('--perfmon-host');p.add_argument('--perfmon-port',type=int,default=4444)
p.add_argument('--perfmon-interval-ms',type=int,default=1000);p.add_argument('--no-perfmon',action='store_true')
p.add_argument('--shelly-host',default='192.168.1.44');p.add_argument('--shelly-port',type=int,default=80)
p.add_argument('--shelly-switch-id',type=int,default=0);p.add_argument('--shelly-interval-ms',type=int,default=1000);p.add_argument('--no-shelly',action='store_true')
a=p.parse_args()
if a.capacity_trial and a.scenario not in ['review','professional']:p.error('Capacity trial is restricted to read-only workloads')
if a.users<1 or a.duration<1 or a.warmup<0 or a.ramp<0 or min(a.think_min_ms,a.think_mean_ms,a.think_stddev_ms,a.session_pause_ms,a.session_stddev_ms)<0: p.error('Invalid timing/concurrency')
if a.think_mean_ms<a.think_min_ms:p.error('Think-time mean must be at least the minimum')
if a.scenario!='idle' and not a.users_file: p.error('--users-file is required')
if a.scenario!='idle' and not a.ca: p.error('--ca is required for application scenarios')
if a.scenario=='idle' and a.users_file:p.error('Idle does not use accounts; omit --users-file')
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)
if a.shelly_interval_ms<1000 or a.shelly_switch_id<0:p.error('Invalid Shelly interval/switch ID')
shelly_info=None if a.no_shelly else shelly.check_plug(a.shelly_host,a.shelly_port,a.shelly_switch_id)
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]
if a.scenario!='idle':
context=application_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('Application 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={'architecture':'B','scenario':a.scenario,'users':0 if a.scenario=='idle' else a.users,'measurement_duration_seconds':a.duration,'warmup_seconds':a.warmup,'ramp_seconds':0 if a.scenario=='idle' else a.ramp,'think_min_ms':a.think_min_ms,'think_max_ms':2*a.think_mean_ms-a.think_min_ms,'think_distribution':'symmetrically truncated Gaussian','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':'none; no application requests' if a.scenario=='idle' else 'initial login and renewal before expiry included','energy':'Shelly status polled live by JMeter; calculations exclude warmup'}
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')
for group in document.iter('ThreadGroup'):
if a.capacity_trial and group.get('testname')=='Users':
for setting in group.findall('stringProp'):
if setting.get('name')=='ThreadGroup.on_sample_error':setting.text='startnextloop'
if group.get('testname')=='Shelly live power':group.set('enabled','false' if a.no_shelly else 'true')
document.write(plan,encoding='utf-8',xml_declaration=True)
drain_seconds=max(5,a.shelly_interval_ms//1000+5) if not a.no_shelly else 5
total_duration_seconds=a.warmup+a.duration+drain_seconds
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(total_duration_seconds),'-Jtimeline_file='+str(out/'timeline.json'),'-Jramp_seconds='+str(a.ramp),'-Jthink_min_ms='+str(a.think_min_ms),'-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']
cmd += ['-Jshelly_host='+a.shelly_host,'-Jshelly_port='+str(a.shelly_port),'-Jshelly_switch_id='+str(a.shelly_switch_id),'-Jshelly_interval_ms='+str(a.shelly_interval_ms),'-Jshelly_file='+str(out/'shelly.csv'),'-Jsample_variables='+','.join(shelly.VARIABLES)]
metadata['capacity_trial']=a.capacity_trial
metadata['error_policy']='restart session on error' if a.capacity_trial else 'stop user on error'
metadata['shelly']={'enabled':not a.no_shelly,'host':a.shelly_host,'port':a.shelly_port,'switch_id':a.shelly_switch_id,'interval_ms':a.shelly_interval_ms,'device':shelly_info}
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:
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))
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':
with (out/'samples.csv').open() as f: idle_samples=list(csv.DictReader(f))
app_samples=[r for r in idle_samples if r['label'].startswith('HTTP ')]
metadata.update(http_samples=len(app_samples),measured_http_samples=len(app_samples),measured_http_requests_per_second=0,failed_samples_including_scripts=sum(r['success'].lower()!='true' for r in idle_samples))
if app_samples or metadata['failed_samples_including_scripts']:
print('Idle baseline contains application requests or failed samples');code=1
if metadata['actual_elapsed_seconds']+2<a.warmup+a.duration:
print('Idle baseline stopped early; measurement is incomplete');code=1
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
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
if not a.no_shelly:
try:
metadata['power_energy']=shelly.summarize(out/'shelly.csv',out/'shelly-measured.csv',metadata['measurement_start_ms'],metadata['measurement_end_ms'],a.shelly_interval_ms)
print('Live Shelly power and measured-window energy saved')
except (OSError,ValueError,KeyError) as error:
metadata['power_error']=str(error);print('Invalid power measurement:',error);code=1
metadata['exit_code']=code
(out/'run.json').write_text(json.dumps(metadata,indent=2))
if (out/'timeline.json').exists():
try:
from report import build
build(out)
except Exception as error:
print('Graph generation failed; raw measurements are preserved:',error)
metadata['report_error']=str(error);(out/'run.json').write_text(json.dumps(metadata,indent=2))
raise SystemExit(code)