179 lines
15 KiB
Python
179 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate JMeter plans with the PerfMon listener; no application changes required."""
|
|
from pathlib import Path
|
|
import xml.etree.ElementTree as E
|
|
from perfmon import METRICS
|
|
|
|
OUT = Path(__file__).parent / 'plans'
|
|
|
|
def prop(parent, name, value, kind='stringProp'):
|
|
E.SubElement(parent, kind, name=name).text = str(value).lower() if isinstance(value, bool) else str(value)
|
|
|
|
def element(tree, tag, gui, name, **attrs):
|
|
e = E.SubElement(tree, tag, guiclass=gui, testclass=tag, testname=name, enabled='true', **attrs)
|
|
return e, E.SubElement(tree, 'hashTree')
|
|
|
|
def script(tree, tag, name, code):
|
|
e, t = element(tree, tag, tag+'Gui', name)
|
|
for k,v in [('scriptLanguage','groovy'),('cacheKey','true'),('filename',''),('parameters',''),('script',code)]: prop(e,k,v)
|
|
return t
|
|
|
|
def request(tree, name, method, path, body='', status=200, check=''):
|
|
e, t = element(tree,'HTTPSamplerProxy','HttpTestSampleGui','HTTP '+name)
|
|
args = E.SubElement(e,'elementProp',name='HTTPsampler.Arguments',elementType='Arguments',guiclass='HTTPArgumentsPanel',testclass='Arguments',enabled='true')
|
|
collection = E.SubElement(args,'collectionProp',name='Arguments.arguments')
|
|
if body:
|
|
arg = E.SubElement(collection,'elementProp',name='',elementType='HTTPArgument')
|
|
prop(arg,'HTTPArgument.always_encode',False,'boolProp'); prop(arg,'Argument.value',body); prop(arg,'Argument.metadata','=')
|
|
for k,v in [('HTTPSampler.domain','${__P(host,127.0.0.1)}'),('HTTPSampler.port','${__P(port,5443)}'),('HTTPSampler.protocol','https'),('HTTPSampler.path',path),('HTTPSampler.method',method),('HTTPSampler.implementation','HttpClient4'),('HTTPSampler.connect_timeout','10000'),('HTTPSampler.response_timeout','30000')]: prop(e,k,v)
|
|
for k,v in [('HTTPSampler.postBodyRaw',bool(body)),('HTTPSampler.follow_redirects',False),('HTTPSampler.auto_redirects',False),('HTTPSampler.use_keepalive',True),('HTTPSampler.DO_MULTIPART_POST',False)]: prop(e,k,v,'boolProp')
|
|
# HTTP status and semantic checks fail the thread rather than generating cascades.
|
|
script(t,'JSR223Assertion','Expected response',f'''if (prev.getResponseCode() != '{status}') {{
|
|
AssertionResult.setFailure(true); AssertionResult.setFailureMessage('Unexpected HTTP status: '+prev.getResponseCode()); return
|
|
}}
|
|
// Expected negative outcomes (e.g. deletion confirmed with 404) are successful checks.
|
|
prev.setSuccessful(true)
|
|
{('def json = new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())' if check else '')}
|
|
{check}
|
|
''')
|
|
script(t,'JSR223Timer','Gaussian interaction pause', """def rng = vars.getObject('user_random')
|
|
double mean = Double.parseDouble(props.getProperty('think_mean_ms','4000'))
|
|
double deviation = Double.parseDouble(props.getProperty('think_stddev_ms','2000'))
|
|
return Math.max(0L,Math.round(mean + rng.nextGaussian() * deviation))
|
|
""")
|
|
|
|
PERIOD = 'from=${period_from}&to=${period_to}'
|
|
PATIENT = '/api/patients/${patient_id}'
|
|
|
|
def review(t, professional=False):
|
|
if professional:
|
|
request(t,'Assigned patients','GET','/api/professionals/me/patients',check="assert json.any { it.patientId == vars.get('patient_id') } : 'Target patient is not assigned'")
|
|
request(t,'Read profile','GET',PATIENT if professional else '/api/patients/me',check="assert json.patientId == vars.get('patient_id')")
|
|
request(t,'Latest reading','GET',PATIENT+'/observations/latest',check="assert json.patientId == vars.get('patient_id')")
|
|
request(t,'Home resting history','GET',PATIENT+'/observations?'+PERIOD+'&setting=Home&activityCondition=AtRest',check="assert json instanceof List && !json.empty : 'Seed observations first'")
|
|
request(t,'Numerical insights','GET',PATIENT+'/insights?'+PERIOD+'&setting=Home&activityCondition=AtRest',check="assert json.contributingCount > 0")
|
|
request(t,'Trends','GET',PATIENT+'/trends?'+PERIOD)
|
|
overview(t)
|
|
|
|
def overview(t):
|
|
request(t,'Health overview','GET',PATIENT+'/overview?'+PERIOD,check="assert json.patient.patientId == vars.get('patient_id'); assert json.latestObservation != null; assert json.insight != null")
|
|
|
|
def record(t, correction=False):
|
|
request(t,'Measurement guidance','GET','/api/measurement-guidance?setting=Home&activityCondition=AtRest')
|
|
request(t,'Read own profile','GET','/api/patients/me',check="assert json.patientId == vars.get('patient_id')")
|
|
request(t,'Record synthetic measurement','POST',PATIENT+'/observations','${observation_body}',201,"assert json.patientId == vars.get('patient_id'); assert json.observationId; vars.put('observation_id',json.observationId)")
|
|
if correction:
|
|
request(t,'Correct entry and context','PATCH','/api/observations/${observation_id}','{"systolic":128,"measurementContext":{"additionalCircumstances":"Corrected synthetic entry"}}',check="assert json.systolic == 128")
|
|
request(t,'Confirm saved reading','GET','/api/observations/${observation_id}',check="assert json.observationId == vars.get('observation_id')")
|
|
overview(t)
|
|
if correction:
|
|
request(t,'Remove duplicate test entry','DELETE','/api/observations/${observation_id}',status=204)
|
|
request(t,'Confirm removal','GET','/api/observations/${observation_id}',status=404)
|
|
|
|
def shelly_group(tree):
|
|
group,gt=element(tree,'ThreadGroup','ThreadGroupGui','Shelly live power')
|
|
prop(group,'ThreadGroup.on_sample_error','continue')
|
|
loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true')
|
|
prop(loop,'LoopController.continue_forever',False,'boolProp');prop(loop,'LoopController.loops',-1)
|
|
for k,v in [('ThreadGroup.num_threads','1'),('ThreadGroup.ramp_time','0'),('ThreadGroup.duration','${__P(total_duration_seconds,16210)}'),('ThreadGroup.delay','0')]:prop(group,k,v)
|
|
prop(group,'ThreadGroup.scheduler',True,'boolProp')
|
|
e,t=element(gt,'HTTPSamplerProxy','HttpTestSampleGui','POWER Shelly status')
|
|
E.SubElement(E.SubElement(e,'elementProp',name='HTTPsampler.Arguments',elementType='Arguments'),'collectionProp',name='Arguments.arguments')
|
|
for k,v in [('HTTPSampler.domain','${__P(shelly_host,192.168.1.44)}'),('HTTPSampler.port','${__P(shelly_port,80)}'),('HTTPSampler.protocol','http'),('HTTPSampler.path','/rpc/Switch.GetStatus?id=${__P(shelly_switch_id,0)}'),('HTTPSampler.method','GET'),('HTTPSampler.implementation','HttpClient4'),('HTTPSampler.connect_timeout','3000'),('HTTPSampler.response_timeout','3000')]:prop(e,k,v)
|
|
for k,v in [('HTTPSampler.follow_redirects',False),('HTTPSampler.use_keepalive',True)]:prop(e,k,v,'boolProp')
|
|
script(t,'JSR223Timer','Fixed meter cadence', "if (!vars.get('shelly_last_poll_ms')) return 0L; return Math.max(0L, Long.parseLong(vars.get('shelly_last_poll_ms')) + Long.parseLong(props.getProperty('shelly_interval_ms','1000')) - System.currentTimeMillis())")
|
|
script(t,'JSR223PreProcessor','Clear stale power values', "['shelly_power_watts','shelly_voltage_volts','shelly_current_amps','shelly_energy_wh'].each { vars.put(it,'') }")
|
|
script(t,'JSR223Assertion','Validate and extract plug readings', """vars.put('shelly_last_poll_ms',prev.getStartTime().toString())
|
|
try {
|
|
assert prev.getResponseCode() == '200'
|
|
def json=new groovy.json.JsonSlurper().parseText(prev.getResponseDataAsString())
|
|
assert json.output == true : 'Outlet is off'
|
|
def readings=[shelly_power_watts:json.apower,shelly_voltage_volts:json.voltage,shelly_current_amps:json.current,shelly_energy_wh:json.aenergy?.total]
|
|
readings.each { key,value -> assert value instanceof Number && Double.isFinite(value.doubleValue()) && value >= 0; vars.put(key,value.toString()) }
|
|
} catch (Throwable error) {
|
|
AssertionResult.setFailure(true);AssertionResult.setFailureMessage('Shelly status/measurement unavailable');prev.setSuccessful(false)
|
|
}
|
|
""")
|
|
collector,_=element(gt,'ResultCollector','SimpleDataWriter','Shelly measurements saved live')
|
|
prop(collector,'filename','${__P(shelly_file,shelly.csv)}');prop(collector,'ResultCollector.error_logging',False,'boolProp')
|
|
|
|
for scenario in ['recording','review','correction','professional','mixed','idle']:
|
|
root=E.Element('jmeterTestPlan',version='1.2',properties='5.0',jmeter='5.6.3'); tree=E.SubElement(root,'hashTree')
|
|
plan, pt=element(tree,'TestPlan','TestPlanGui','HealthApp energy: '+scenario)
|
|
prop(plan,'TestPlan.comments','Synthetic closed-loop sessions; default duration four hours. Setup is external; Shelly power is collected live without changing the outlet.')
|
|
prop(plan,'TestPlan.functional_mode',False,'boolProp'); prop(plan,'TestPlan.serialize_threadgroups',False,'boolProp')
|
|
E.SubElement(E.SubElement(plan,'elementProp',name='TestPlan.user_defined_variables',elementType='Arguments',guiclass='ArgumentsPanel',testclass='Arguments',enabled='true'),'collectionProp',name='Arguments.arguments')
|
|
shelly_group(pt)
|
|
collector, _ = element(pt,'kg.apc.jmeter.perfmon.PerfMonCollector','kg.apc.jmeter.vizualizers.PerfMonGui','NUC live CPU RAM disk and network')
|
|
collector.set('enabled','true')
|
|
prop(collector,'filename','${__P(perfmon_file,perfmon.csv)}')
|
|
prop(collector,'ResultCollector.error_logging',False,'boolProp')
|
|
connections=E.SubElement(collector,'collectionProp',name='metricConnections')
|
|
for i,(kind,param,unit) in enumerate(METRICS):
|
|
row=E.SubElement(connections,'collectionProp',name=str(i))
|
|
for j,value in enumerate(['${__P(perfmon_host,192.168.1.125)}','${__P(perfmon_port,4444)}',kind,param]):prop(row,str(j),value)
|
|
group, gt=element(pt,'ThreadGroup','ThreadGroupGui','Users')
|
|
prop(group,'ThreadGroup.on_sample_error','stopthread')
|
|
loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true')
|
|
prop(loop,'LoopController.continue_forever',False,'boolProp'); prop(loop,'LoopController.loops',-1)
|
|
for k,v in [('ThreadGroup.num_threads','${__P(users,1)}'),('ThreadGroup.ramp_time','${__P(ramp_seconds,60)}'),('ThreadGroup.duration','${__P(total_duration_seconds,16210)}'),('ThreadGroup.delay','0')]: prop(group,k,v)
|
|
prop(group,'ThreadGroup.scheduler',True,'boolProp'); prop(group,'ThreadGroup.same_user_on_next_iteration',True,'boolProp')
|
|
if scenario=='idle':
|
|
prop(group,'ThreadGroup.num_threads','1');prop(group,'ThreadGroup.ramp_time','0')
|
|
once, ot=element(gt,'OnceOnlyController','OnceOnlyControllerGui','Record idle measurement window')
|
|
script(ot,'JSR223Sampler','Idle timing', '''long start=System.currentTimeMillis()
|
|
long measurement=start+Long.parseLong(props.getProperty('warmup_seconds','1800'))*1000
|
|
long end=measurement+Long.parseLong(props.getProperty('duration_seconds','14400'))*1000
|
|
if (props.get('timeline_file')) new File(props.get('timeline_file')).text=groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
|
''')
|
|
pause,_=element(gt,'TestAction','TestActionGui','Idle wait; no application requests')
|
|
prop(pause,'ActionProcessor.action',1,'intProp');prop(pause,'ActionProcessor.target',0,'intProp');prop(pause,'ActionProcessor.duration','1000')
|
|
E.indent(root);E.ElementTree(root).write(OUT/(scenario+'.jmx'),encoding='utf-8',xml_declaration=True)
|
|
continue
|
|
headers, _=element(gt,'HeaderManager','HeaderPanel','JSON and bearer token')
|
|
coll=E.SubElement(headers,'collectionProp',name='HeaderManager.headers')
|
|
for name,value in [('Content-Type','application/json'),('Authorization','Bearer ${token}')]:
|
|
h=E.SubElement(coll,'elementProp',name='',elementType='Header');prop(h,'Header.name',name);prop(h,'Header.value',value)
|
|
once, ot=element(gt,'OnceOnlyController','OnceOnlyControllerGui','Assign one account per user')
|
|
script(ot,'JSR223Sampler','Initialize user', '''def rows = new File(props.get('users_file')).readLines('UTF-8').drop(1).findAll { it.trim() }
|
|
def row = rows[ctx.getThreadNum()].split(',', -1)
|
|
vars.put('account_id', row[0]); vars.put('password', row[1]); vars.put('patient_id', row[2])
|
|
vars.put('token', ''); vars.put('expires_at', '0'); vars.put('session_number','0')
|
|
vars.putObject('user_random', new Random(Long.parseLong(props.getProperty('random_seed','42')) + ctx.getThreadNum()))
|
|
synchronized(props) {
|
|
if (props.get('timeline_file') && !props.get('workload_start_ms')) {
|
|
long start = System.currentTimeMillis()
|
|
long measurement = start + Long.parseLong(props.getProperty('warmup_seconds','1800')) * 1000
|
|
long end = measurement + Long.parseLong(props.getProperty('duration_seconds','14400')) * 1000
|
|
props.put('workload_start_ms',start.toString())
|
|
new File(props.get('timeline_file')).text = groovy.json.JsonOutput.toJson([warmup_start_ms:start,measurement_start_ms:measurement,measurement_end_ms:end])
|
|
}
|
|
}
|
|
''')
|
|
script(gt,'JSR223Sampler','Prepare session', '''def now = java.time.Instant.now()
|
|
vars.put('refresh_login', (now.epochSecond >= Long.parseLong(vars.get('expires_at')) - 60).toString())
|
|
vars.put('login_body',groovy.json.JsonOutput.toJson([accountId:vars.get('account_id'),password:vars.get('password')]))
|
|
vars.put('period_from',props.get('period_from')); vars.put('period_to',props.get('period_to'))
|
|
int n = Integer.parseInt(vars.get('session_number')); vars.put('session_number',(n+1).toString())
|
|
// Random session mix: expected 65% review, 30% recording, 5% correction.
|
|
int slot = vars.getObject('user_random').nextInt(20)
|
|
vars.put('session_kind',slot < 13 ? 'review' : slot < 19 ? 'recording' : 'correction')
|
|
double mean = Double.parseDouble(props.getProperty('session_pause_ms','120000'))
|
|
double deviation = Double.parseDouble(props.getProperty('session_stddev_ms','30000'))
|
|
vars.put('session_delay_ms',Math.max(0L,Math.round(mean + vars.getObject('user_random').nextGaussian()*deviation)).toString())
|
|
vars.put('observation_body',groovy.json.JsonOutput.toJson([measuredAt:now.toString(),systolic:128+(n%7),diastolic:82+(n%4),pulse:68+(n%6),measurementContext:[setting:'Home',activityCondition:'AtRest',restDurationMinutes:5,bodyPosition:'Seated'],note:'Synthetic JMeter energy workload']))
|
|
''')
|
|
login, lt=element(gt,'IfController','IfControllerPanel','Login or renew expired token')
|
|
prop(login,'IfController.condition','${refresh_login}');prop(login,'IfController.evaluateAll',False,'boolProp');prop(login,'IfController.useExpression',True,'boolProp')
|
|
request(lt,'Login','POST','/api/authentication/login','${login_body}',check="assert json.accessToken; vars.put('token',json.accessToken); vars.put('expires_at',(java.time.Instant.now().epochSecond + (json.expiresIn as long)).toString())")
|
|
if scenario=='mixed':
|
|
for kind in ['review','recording','correction']:
|
|
branch,bt=element(gt,'IfController','IfControllerPanel',kind+' session')
|
|
prop(branch,'IfController.condition',"${__groovy(vars.get('session_kind') == '"+kind+"')}");prop(branch,'IfController.useExpression',True,'boolProp');prop(branch,'IfController.evaluateAll',False,'boolProp')
|
|
review(bt) if kind=='review' else record(bt,kind=='correction')
|
|
elif scenario in ['review','professional']: review(gt,scenario=='professional')
|
|
else: record(gt,scenario=='correction')
|
|
pause, _ = element(gt,'TestAction','TestActionGui','Between-session pause')
|
|
prop(pause,'ActionProcessor.action',1,'intProp'); prop(pause,'ActionProcessor.target',0,'intProp'); prop(pause,'ActionProcessor.duration','${session_delay_ms}')
|
|
E.indent(root); E.ElementTree(root).write(OUT/(scenario+'.jmx'),encoding='utf-8',xml_declaration=True)
|