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

+50 -3
View File
@@ -2,7 +2,7 @@
JMeter 5.6.3 is installed on this development computer at `~/.local/bin/jmeter`. JMeter 5.6.3 is installed on this development computer at `~/.local/bin/jmeter`.
Its launcher uses the installed Java 17; the default Java 26 cannot compile Its launcher uses the installed Java 17; the default Java 26 cannot compile
JMeter's bundled Groovy scripts. No JMeter plugins are needed. JMeter's bundled Groovy scripts. The `jpgc-perfmon` 2.1 plugin is installed for live server monitoring.
Runs default to **30 minutes of warmup + 4 hours of measurement**. A few additional Runs default to **30 minutes of warmup + 4 hours of measurement**. A few additional
seconds allow startup/draining. Only requests entirely inside the four-hour window seconds allow startup/draining. Only requests entirely inside the four-hour window
@@ -37,6 +37,42 @@ for less frequent patient visits increase `--session-pause-ms` and its deviation
A closed-loop user waits for each response; throughput decreases when the server slows. A closed-loop user waits for each response; throughput decreases when the server slows.
Concurrency means resident simulated users, including their idle/thinking time. Concurrency means resident simulated users, including their idle/thinking time.
## Live NUC monitoring in JMeter
All six plans contain **jp@gc – PerfMon Metrics Collector**, including idle.
The listener connects over TCP to the agent on the target (default port 4444),
samples every five seconds, and writes `perfmon.csv` directly on this computer
through JMeter during the run. No server log transfer is needed. In GUI mode the
listener shows live graphs; use CLI mode for actual energy experiments.
Collected host metrics: CPU combined utilisation and I/O wait (%), memory usage
(% and actual-used bytes), swap-used bytes, disk read/write bytes per second,
and network received/sent bytes per second. These are system totals, not per-service
attribution. Network/disk counters depend on SIGAR's device support; zero values on
an idle host do not establish their accuracy. Compare the readings against Linux
utilities before treating the agent as a validated measurement instrument.
The runner checks agent access/metric availability before starting. It records
`--perfmon-host`, `--perfmon-port` and `--perfmon-interval-ms` (default 5000) in
`run.json`; by default the agent host matches `--host`. Failed, missing or widely
spaced measurements invalidate monitoring. `perfmon-measured.csv` excludes warmup,
decodes the plugin's synthetic `elapsed` field into metric values/units, and retains
timestamps from this computer's collector, not server-origin timestamps.
**PerfMon's elapsed field is not HTTP latency.** Host metrics stay separate
from application request counts. Raw `perfmon.csv` contains warmup and measured data.
`run.json` also includes each metric's sample count, mean and maximum.
Keep the agent running on the NUC for the full warmup and measured run. Its TCP
connection is plain-text and provides no authentication; restrict port 4444 to the
load-generator computer. Restart it with `--no-exec --udp-port 0 --tcp-port 4444`
to disable the agent's executable custom metrics; these plans use only built-in metrics.
`--no-perfmon` is for isolated workflow testing and explicitly records that no server
monitoring was collected. The plugin must still be installed to load its JMX element.
The validation fixture uses this switch and does not connect to the NUC.
[PerfMon listener documentation](https://jmeter-plugins.org/wiki/PerfMon/),
[agent metrics/protocol](https://github.com/undera/perfmon-agent).
## 1. Prepare distinct test accounts (outside measurement) ## 1. Prepare distinct test accounts (outside measurement)
The installer initially supplies only one ordinary patient account. Use distinct The installer initially supplies only one ordinary patient account. Use distinct
@@ -140,12 +176,12 @@ Use the same-duration `idle` run to establish baseline power:
python3 tools/energy-jmeter/run.py idle --host 192.168.1.125 --ca tools/energy-jmeter/.private/healthapp-ca.crt --warmup 1800 --duration 14400 --output tools/energy-jmeter/results/idle-run1 python3 tools/energy-jmeter/run.py idle --host 192.168.1.125 --ca tools/energy-jmeter/.private/healthapp-ca.crt --warmup 1800 --duration 14400 --output tools/energy-jmeter/results/idle-run1
``` ```
The idle runner sends one TLS preflight request before the observation period. The idle runner sends one TLS preflight request before the observation period, then uses a JMeter idle plan with live PerfMon collection.
The application services/PostgreSQL stay running. The load generator and HTML-report The application services/PostgreSQL stay running. The load generator and HTML-report
creation stay on this computer, outside the NUC's energy measurement. Keep server creation stay on this computer, outside the NUC's energy measurement. Keep server
power settings, dataset, service versions, logging and other workloads consistent. power settings, dataset, service versions, logging and other workloads consistent.
Record those settings, thermal state, meter sampling interval and clock synchronisation. Record those settings, thermal state, meter sampling interval and clock synchronisation.
Repeat runs and vary their order to check drift. No live NUC load has been run by Codex. Repeat runs and vary their order to check drift. Only a brief monitoring-only JMeter check has been run against the NUC; no application load has been sent by Codex.
## 4. Read results and energy ## 4. Read results and energy
@@ -177,6 +213,7 @@ but does not provide certificate validation. Do not describe this as a TLS secur
```bash ```bash
python3 tools/energy-jmeter/generate-plans.py python3 tools/energy-jmeter/generate-plans.py
python3 tools/energy-jmeter/verify-plans.py python3 tools/energy-jmeter/verify-plans.py
python3 tools/energy-jmeter/verify-perfmon.py
``` ```
The validation script exercises every plan against an isolated local HTTPS contract The validation script exercises every plan against an isolated local HTTPS contract
@@ -187,3 +224,13 @@ suite. The real-server short capacity trial is required before a four-hour measu
References: [Apache release](https://jmeter.apache.org/download_jmeter.cgi), References: [Apache release](https://jmeter.apache.org/download_jmeter.cgi),
[CLI load testing](https://jmeter.apache.org/usermanual/get-started.html), [CLI load testing](https://jmeter.apache.org/usermanual/get-started.html),
[JMeter components](https://jmeter.apache.org/usermanual/component_reference.html). [JMeter components](https://jmeter.apache.org/usermanual/component_reference.html).
For a short live monitoring-only check (no patient requests):
```bash
python3 tools/energy-jmeter/verify-perfmon.py --host 192.168.1.125 --output tools/energy-jmeter/results/perfmon-check-new
```
This verifies that JMeter saves readings while it is still running, then checks
metric coverage and decoding. A monitoring-only check succeeded against the NUC;
comparison with independent Linux readings is still needed to validate accuracy.
+23 -2
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Generate stock-JMeter plans; no plugins or application changes required.""" """Generate JMeter plans with the PerfMon listener; no application changes required."""
from pathlib import Path from pathlib import Path
import xml.etree.ElementTree as E import xml.etree.ElementTree as E
from perfmon import METRICS
OUT = Path(__file__).parent / 'plans' OUT = Path(__file__).parent / 'plans'
@@ -69,18 +70,38 @@ def record(t, correction=False):
request(t,'Remove duplicate test entry','DELETE','/api/observations/${observation_id}',status=204) request(t,'Remove duplicate test entry','DELETE','/api/observations/${observation_id}',status=204)
request(t,'Confirm removal','GET','/api/observations/${observation_id}',status=404) request(t,'Confirm removal','GET','/api/observations/${observation_id}',status=404)
for scenario in ['recording','review','correction','professional','mixed']: 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') 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) plan, pt=element(tree,'TestPlan','TestPlanGui','HealthApp energy: '+scenario)
prop(plan,'TestPlan.comments','Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.') prop(plan,'TestPlan.comments','Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.')
prop(plan,'TestPlan.functional_mode',False,'boolProp'); prop(plan,'TestPlan.serialize_threadgroups',False,'boolProp') 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') E.SubElement(E.SubElement(plan,'elementProp',name='TestPlan.user_defined_variables',elementType='Arguments',guiclass='ArgumentsPanel',testclass='Arguments',enabled='true'),'collectionProp',name='Arguments.arguments')
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') group, gt=element(pt,'ThreadGroup','ThreadGroupGui','Users')
prop(group,'ThreadGroup.on_sample_error','stopthread') prop(group,'ThreadGroup.on_sample_error','stopthread')
loop=E.SubElement(group,'elementProp',name='ThreadGroup.main_controller',elementType='LoopController',guiclass='LoopControlPanel',testclass='LoopController',enabled='true') 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) 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,16205)}'),('ThreadGroup.delay','0')]: prop(group,k,v) for k,v in [('ThreadGroup.num_threads','${__P(users,1)}'),('ThreadGroup.ramp_time','${__P(ramp_seconds,60)}'),('ThreadGroup.duration','${__P(total_duration_seconds,16205)}'),('ThreadGroup.delay','0')]: prop(group,k,v)
prop(group,'ThreadGroup.scheduler',True,'boolProp'); prop(group,'ThreadGroup.same_user_on_next_iteration',True,'boolProp') 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') headers, _=element(gt,'HeaderManager','HeaderPanel','JSON and bearer token')
coll=E.SubElement(headers,'collectionProp',name='HeaderManager.headers') coll=E.SubElement(headers,'collectionProp',name='HeaderManager.headers')
for name,value in [('Content-Type','application/json'),('Authorization','Bearer ${token}')]: for name,value in [('Content-Type','application/json'),('Authorization','Bearer ${token}')]:
+35
View File
@@ -0,0 +1,35 @@
"""PerfMon agent preflight and JMeter's metric-file decoding."""
import csv, math, socket
METRICS=[('CPU','combined','percent'),('CPU','iowait','percent'),('Memory','usedperc','percent'),('Memory','actualused','bytes'),('Swap','used','bytes'),('Disks I/O','readbytes','bytes/second'),('Disks I/O','writebytes','bytes/second'),('Network I/O','bytesrecv','bytes/second'),('Network I/O','bytessent','bytes/second')]
TYPES={'CPU':'cpu','Memory':'memory','Swap':'swap','Disks I/O':'disks','Network I/O':'network'}
def check_agent(host,port):
specs=[TYPES[k]+':'+param for k,param,_ in METRICS]
with socket.create_connection((host,port),timeout=5) as s:
s.settimeout(5);s.sendall(('metrics-single:'+'\t'.join(specs)+'\n').encode())
values=s.makefile('r').readline(8192).strip().split('\t')
if len(values)!=len(specs):raise ValueError('PerfMon returned an incomplete metric response')
if any(not math.isfinite(float(v)) or float(v)<0 for v in values):raise ValueError('PerfMon reported unavailable/invalid metrics')
return dict(zip(specs,map(float,values)))
def summarize(raw,output,start,end,interval_ms):
with raw.open() as f: rows=list(csv.DictReader(f))
result=[];by_metric={}
for row in rows:
# PerfMon encodes the metric as synthetic elapsed milliseconds, not HTTP latency.
if row.get('success','true').lower()!='true':raise ValueError('PerfMon collector reported a failed sample')
value=float(row['elapsed'])/1000
if not math.isfinite(value) or value<0:raise ValueError('PerfMon collector reported a metric error')
timestamp=int(row['timeStamp'])
if not start<=timestamp<=end:continue
label=row['label']; unit=next((unit for kind,param,unit in METRICS if label.endswith(kind+' '+param)),'unknown')
if unit=='unknown':raise ValueError('Unknown PerfMon label: '+label)
result.append({'timestamp_ms':timestamp,'metric':label,'value':value,'unit':unit})
by_metric.setdefault(label,[]).append((timestamp,value))
if len(by_metric)!=len(METRICS):raise ValueError('Measured interval is missing required PerfMon metrics')
stats={}
for label,points in by_metric.items():
points.sort();gaps=[b[0]-a[0] for a,b in zip(points,points[1:])]
if max([points[0][0]-start,end-points[-1][0],*gaps])>interval_ms*3:raise ValueError('Gap in live monitoring: '+label)
stats[label]={'samples':len(points),'mean':sum(v for _,v in points)/len(points),'max':max(v for _,v in points)}
with output.open('w') as f:
w=csv.DictWriter(f,fieldnames=['timestamp_ms','metric','value','unit']);w.writeheader();w.writerows(result)
return stats
+61
View File
@@ -10,6 +10,67 @@
</elementProp> </elementProp>
</TestPlan> </TestPlan>
<hashTree> <hashTree>
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
<boolProp name="ResultCollector.error_logging">false</boolProp>
<collectionProp name="metricConnections">
<collectionProp name="0">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">combined</stringProp>
</collectionProp>
<collectionProp name="1">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">iowait</stringProp>
</collectionProp>
<collectionProp name="2">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">usedperc</stringProp>
</collectionProp>
<collectionProp name="3">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">actualused</stringProp>
</collectionProp>
<collectionProp name="4">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Swap</stringProp>
<stringProp name="3">used</stringProp>
</collectionProp>
<collectionProp name="5">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">readbytes</stringProp>
</collectionProp>
<collectionProp name="6">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">writebytes</stringProp>
</collectionProp>
<collectionProp name="7">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytesrecv</stringProp>
</collectionProp>
<collectionProp name="8">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytessent</stringProp>
</collectionProp>
</collectionProp>
</kg.apc.jmeter.perfmon.PerfMonCollector>
<hashTree />
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true"> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp> <stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true"> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
+114
View File
@@ -0,0 +1,114 @@
<?xml version='1.0' encoding='utf-8'?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.6.3">
<hashTree>
<TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="HealthApp energy: idle" enabled="true">
<stringProp name="TestPlan.comments">Synthetic closed-loop sessions; default duration four hours. Setup and energy-meter control are external.</stringProp>
<boolProp name="TestPlan.functional_mode">false</boolProp>
<boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
<elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" enabled="true">
<collectionProp name="Arguments.arguments" />
</elementProp>
</TestPlan>
<hashTree>
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
<boolProp name="ResultCollector.error_logging">false</boolProp>
<collectionProp name="metricConnections">
<collectionProp name="0">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">combined</stringProp>
</collectionProp>
<collectionProp name="1">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">iowait</stringProp>
</collectionProp>
<collectionProp name="2">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">usedperc</stringProp>
</collectionProp>
<collectionProp name="3">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">actualused</stringProp>
</collectionProp>
<collectionProp name="4">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Swap</stringProp>
<stringProp name="3">used</stringProp>
</collectionProp>
<collectionProp name="5">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">readbytes</stringProp>
</collectionProp>
<collectionProp name="6">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">writebytes</stringProp>
</collectionProp>
<collectionProp name="7">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytesrecv</stringProp>
</collectionProp>
<collectionProp name="8">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytessent</stringProp>
</collectionProp>
</collectionProp>
</kg.apc.jmeter.perfmon.PerfMonCollector>
<hashTree />
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
<boolProp name="LoopController.continue_forever">false</boolProp>
<stringProp name="LoopController.loops">-1</stringProp>
</elementProp>
<stringProp name="ThreadGroup.num_threads">${__P(users,1)}</stringProp>
<stringProp name="ThreadGroup.ramp_time">${__P(ramp_seconds,60)}</stringProp>
<stringProp name="ThreadGroup.duration">${__P(total_duration_seconds,16205)}</stringProp>
<stringProp name="ThreadGroup.delay">0</stringProp>
<boolProp name="ThreadGroup.scheduler">true</boolProp>
<boolProp name="ThreadGroup.same_user_on_next_iteration">true</boolProp>
<stringProp name="ThreadGroup.num_threads">1</stringProp>
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
</ThreadGroup>
<hashTree>
<OnceOnlyController guiclass="OnceOnlyControllerGui" testclass="OnceOnlyController" testname="Record idle measurement window" enabled="true" />
<hashTree>
<JSR223Sampler guiclass="JSR223SamplerGui" testclass="JSR223Sampler" testname="Idle timing" enabled="true">
<stringProp name="scriptLanguage">groovy</stringProp>
<stringProp name="cacheKey">true</stringProp>
<stringProp name="filename" />
<stringProp name="parameters" />
<stringProp name="script">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])
</stringProp>
</JSR223Sampler>
<hashTree />
</hashTree>
<TestAction guiclass="TestActionGui" testclass="TestAction" testname="Idle wait; no application requests" enabled="true">
<intProp name="ActionProcessor.action">1</intProp>
<intProp name="ActionProcessor.target">0</intProp>
<stringProp name="ActionProcessor.duration">1000</stringProp>
</TestAction>
<hashTree />
</hashTree>
</hashTree>
</hashTree>
</jmeterTestPlan>
+61
View File
@@ -10,6 +10,67 @@
</elementProp> </elementProp>
</TestPlan> </TestPlan>
<hashTree> <hashTree>
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
<boolProp name="ResultCollector.error_logging">false</boolProp>
<collectionProp name="metricConnections">
<collectionProp name="0">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">combined</stringProp>
</collectionProp>
<collectionProp name="1">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">iowait</stringProp>
</collectionProp>
<collectionProp name="2">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">usedperc</stringProp>
</collectionProp>
<collectionProp name="3">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">actualused</stringProp>
</collectionProp>
<collectionProp name="4">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Swap</stringProp>
<stringProp name="3">used</stringProp>
</collectionProp>
<collectionProp name="5">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">readbytes</stringProp>
</collectionProp>
<collectionProp name="6">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">writebytes</stringProp>
</collectionProp>
<collectionProp name="7">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytesrecv</stringProp>
</collectionProp>
<collectionProp name="8">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytessent</stringProp>
</collectionProp>
</collectionProp>
</kg.apc.jmeter.perfmon.PerfMonCollector>
<hashTree />
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true"> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp> <stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true"> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
@@ -10,6 +10,67 @@
</elementProp> </elementProp>
</TestPlan> </TestPlan>
<hashTree> <hashTree>
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
<boolProp name="ResultCollector.error_logging">false</boolProp>
<collectionProp name="metricConnections">
<collectionProp name="0">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">combined</stringProp>
</collectionProp>
<collectionProp name="1">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">iowait</stringProp>
</collectionProp>
<collectionProp name="2">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">usedperc</stringProp>
</collectionProp>
<collectionProp name="3">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">actualused</stringProp>
</collectionProp>
<collectionProp name="4">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Swap</stringProp>
<stringProp name="3">used</stringProp>
</collectionProp>
<collectionProp name="5">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">readbytes</stringProp>
</collectionProp>
<collectionProp name="6">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">writebytes</stringProp>
</collectionProp>
<collectionProp name="7">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytesrecv</stringProp>
</collectionProp>
<collectionProp name="8">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytessent</stringProp>
</collectionProp>
</collectionProp>
</kg.apc.jmeter.perfmon.PerfMonCollector>
<hashTree />
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true"> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp> <stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true"> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
+61
View File
@@ -10,6 +10,67 @@
</elementProp> </elementProp>
</TestPlan> </TestPlan>
<hashTree> <hashTree>
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
<boolProp name="ResultCollector.error_logging">false</boolProp>
<collectionProp name="metricConnections">
<collectionProp name="0">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">combined</stringProp>
</collectionProp>
<collectionProp name="1">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">iowait</stringProp>
</collectionProp>
<collectionProp name="2">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">usedperc</stringProp>
</collectionProp>
<collectionProp name="3">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">actualused</stringProp>
</collectionProp>
<collectionProp name="4">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Swap</stringProp>
<stringProp name="3">used</stringProp>
</collectionProp>
<collectionProp name="5">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">readbytes</stringProp>
</collectionProp>
<collectionProp name="6">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">writebytes</stringProp>
</collectionProp>
<collectionProp name="7">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytesrecv</stringProp>
</collectionProp>
<collectionProp name="8">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytessent</stringProp>
</collectionProp>
</collectionProp>
</kg.apc.jmeter.perfmon.PerfMonCollector>
<hashTree />
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true"> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp> <stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true"> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
+61
View File
@@ -10,6 +10,67 @@
</elementProp> </elementProp>
</TestPlan> </TestPlan>
<hashTree> <hashTree>
<kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="NUC live CPU RAM disk and network" enabled="true">
<stringProp name="filename">${__P(perfmon_file,perfmon.csv)}</stringProp>
<boolProp name="ResultCollector.error_logging">false</boolProp>
<collectionProp name="metricConnections">
<collectionProp name="0">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">combined</stringProp>
</collectionProp>
<collectionProp name="1">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">CPU</stringProp>
<stringProp name="3">iowait</stringProp>
</collectionProp>
<collectionProp name="2">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">usedperc</stringProp>
</collectionProp>
<collectionProp name="3">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Memory</stringProp>
<stringProp name="3">actualused</stringProp>
</collectionProp>
<collectionProp name="4">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Swap</stringProp>
<stringProp name="3">used</stringProp>
</collectionProp>
<collectionProp name="5">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">readbytes</stringProp>
</collectionProp>
<collectionProp name="6">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Disks I/O</stringProp>
<stringProp name="3">writebytes</stringProp>
</collectionProp>
<collectionProp name="7">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytesrecv</stringProp>
</collectionProp>
<collectionProp name="8">
<stringProp name="0">${__P(perfmon_host,192.168.1.125)}</stringProp>
<stringProp name="1">${__P(perfmon_port,4444)}</stringProp>
<stringProp name="2">Network I/O</stringProp>
<stringProp name="3">bytessent</stringProp>
</collectionProp>
</collectionProp>
</kg.apc.jmeter.perfmon.PerfMonCollector>
<hashTree />
<ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true"> <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Users" enabled="true">
<stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp> <stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true"> <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" enabled="true">
+27 -13
View File
@@ -1,7 +1,9 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Preflight and run JMeter; record actual timing for external power measurements.""" """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 import argparse, csv, datetime as dt, hashlib, json, os, platform, subprocess, time, ssl, urllib.request
from pathlib import Path from pathlib import Path
from perfmon import check_agent, summarize
HERE=Path(__file__).resolve().parent HERE=Path(__file__).resolve().parent
p=argparse.ArgumentParser() p=argparse.ArgumentParser()
p.add_argument('scenario',choices=['recording','review','correction','professional','mixed','idle']) 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('--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('--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('--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() 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.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.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=[] rows=[]
if a.users_file: if a.users_file:
with open(a.users_file,newline='') as f: 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') 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) 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'} 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'
runtime_csv=out/'runtime-users.csv' with runtime_csv.open('x') as f:
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)
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=HERE/'plans'/(a.scenario+'.jmx');metadata['plan_sha256']=hashlib.sha256(plan.read_bytes()).hexdigest() plan=out/'runtime.jmx'; document=E.parse(source_plan)
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'] for collector in document.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):
metadata['jmeter_version']=subprocess.check_output([a.jmeter,'--version'],text=True).strip() 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() metadata['started_utc']=dt.datetime.now(dt.timezone.utc).isoformat(); started=time.monotonic()
(out/'run.json').write_text(json.dumps(metadata,indent=2)) (out/'run.json').write_text(json.dumps(metadata,indent=2))
print('Measurement workload starts:',metadata['started_utc'],flush=True) print('Measurement workload starts:',metadata['started_utc'],flush=True)
code=0 code=0
try: try:
if a.scenario=='idle': code=subprocess.call(cmd)
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 except KeyboardInterrupt: code=130
finally: finally:
metadata['finished_utc']=dt.datetime.now(dt.timezone.utc).isoformat();metadata['actual_elapsed_seconds']=time.monotonic()-started;metadata['exit_code']=code 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)) (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(): if (out/'timeline.json').exists():
timeline=json.loads((out/'timeline.json').read_text());metadata.update(timeline) timeline=json.loads((out/'timeline.json').read_text());metadata.update(timeline)
for name in ['warmup_start','measurement_start','measurement_end']: 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)}') print(f'HTTP samples: {len(samples)}; failures: {failed}; measured samples: {len(measured)}')
if all_failed or not measured: code=1 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 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 metadata['exit_code']=code
(out/'run.json').write_text(json.dumps(metadata,indent=2)) (out/'run.json').write_text(json.dumps(metadata,indent=2))
raise SystemExit(code) raise SystemExit(code)
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Verify metric decoding; optionally verify a live JMeter-to-agent connection."""
import argparse, csv, json, subprocess, tempfile, time
from pathlib import Path
from perfmon import METRICS, check_agent, summarize
p=argparse.ArgumentParser();p.add_argument('--host');p.add_argument('--port',type=int,default=4444);p.add_argument('--output');a=p.parse_args()
with tempfile.TemporaryDirectory(prefix='healthapp-perfmon-unit-') as name:
root=Path(name);raw=root/'raw.csv'
def fixture(skip=None,gap=False):
with raw.open('w') as f:
writer=csv.DictWriter(f,fieldnames=['timeStamp','elapsed','label']);writer.writeheader()
for timestamp in ([5000,25000] if gap else range(0,30001,5000)):
for kind,param,unit in METRICS:
if (kind,param)==skip:continue
writer.writerow({'timeStamp':timestamp,'elapsed':73250 if kind=='CPU' else 123000,'label':'fixture '+kind+' '+param})
fixture();stats=summarize(raw,root/'measured.csv',5000,25000,5000)
assert stats['fixture CPU combined']['mean']==73.25
assert len(stats)==9 and all(s['samples']==5 for s in stats.values())
for skipped,gap in [(('CPU','combined'),False),(None,True)]:
fixture(skipped,gap)
try:summarize(raw,root/'invalid.csv',5000,25000,5000)
except ValueError:pass
else:raise AssertionError('Missing metrics/collection gaps were accepted')
print('Metric decoding, warmup exclusion and gap detection passed')
if a.host:
if not a.output:p.error('--output is required for a live check')
check_agent(a.host,a.port)
out=Path(a.output).resolve();out.mkdir(parents=True,mode=0o700,exist_ok=False)
plan=Path(__file__).parent/'plans/idle.jmx'
cmd=[str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(plan),'-l',str(out/'samples.csv'),'-j',str(out/'jmeter.log'),'-Jperfmon_host='+a.host,'-Jperfmon_port='+str(a.port),'-Jperfmon_file='+str(out/'perfmon.csv'),'-JjmeterPlugin.perfmon.interval=5000','-JjmeterPlugin.perfmon.useUDP=false','-Jjmeter.save.saveservice.autoflush=true','-Jwarmup_seconds=5','-Jduration_seconds=20','-Jtotal_duration_seconds=30','-Jtimeline_file='+str(out/'timeline.json')]
process=subprocess.Popen(cmd);saved_live=False
while process.poll() is None:
raw=out/'perfmon.csv'
if raw.exists() and raw.stat().st_size>0:saved_live=True
time.sleep(.25)
assert process.returncode==0 and saved_live, 'Metrics were not saved while JMeter was running'
timeline=json.loads((out/'timeline.json').read_text())
stats=summarize(out/'perfmon.csv',out/'perfmon-measured.csv',timeline['measurement_start_ms'],timeline['measurement_end_ms'],5000)
(out/'summary.json').write_text(json.dumps(stats,indent=2))
print('Live JMeter collection passed: nine metrics written during the run; no application load sent')
print('Results:',out)
+7 -3
View File
@@ -3,6 +3,7 @@
import datetime, json, os, ssl, subprocess, tempfile, threading, uuid import datetime, json, os, ssl, subprocess, tempfile, threading, uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path from pathlib import Path
import xml.etree.ElementTree as E
from urllib.parse import urlsplit from urllib.parse import urlsplit
HERE=Path(__file__).resolve().parent HERE=Path(__file__).resolve().parent
class Handler(BaseHTTPRequestHandler): class Handler(BaseHTTPRequestHandler):
@@ -68,7 +69,7 @@ with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
# Professional runner preflight is intentionally separate: fixture credentials are patient roles. # Professional runner preflight is intentionally separate: fixture credentials are patient roles.
for scenario in ['recording','review','correction','mixed']: for scenario in ['recording','review','correction','mixed']:
initial_logins=Handler.logins initial_logins=Handler.logins
result=subprocess.run(['python3',str(HERE/'run.py'),scenario,'--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','1','--duration','6','--ramp','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','100','--session-stddev-ms','25','--output',str(root/scenario)],capture_output=True,text=True) result=subprocess.run(['python3',str(HERE/'run.py'),scenario,'--no-perfmon','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','1','--duration','6','--ramp','0','--think-mean-ms','10','--think-stddev-ms','5','--session-pause-ms','100','--session-stddev-ms','25','--output',str(root/scenario)],capture_output=True,text=True)
if result.returncode: if result.returncode:
print(result.stdout,result.stderr) print(result.stdout,result.stderr)
print((root/scenario/'jmeter.log').read_text()[-6000:]) print((root/scenario/'jmeter.log').read_text()[-6000:])
@@ -76,13 +77,16 @@ with tempfile.TemporaryDirectory(prefix='healthapp-jmeter-verify-') as temp:
assert Handler.logins - initial_logins >= 6, 'Initial login and token renewal were not exercised' assert Handler.logins - initial_logins >= 6, 'Initial login and token renewal were not exercised'
data=json.loads((root/scenario/'run.json').read_text());assert data['measurement_end_ms']-data['measurement_start_ms']==6000; assert data['measured_http_samples']>0; print(scenario, 'passed;',data['http_samples'],'HTTP samples;', data['failed_http_samples'],'failures') data=json.loads((root/scenario/'run.json').read_text());assert data['measurement_end_ms']-data['measurement_start_ms']==6000; assert data['measured_http_samples']>0; print(scenario, 'passed;',data['http_samples'],'HTTP samples;', data['failed_http_samples'],'failures')
# Run the professional plan directly so its assigned-patient semantic assertion is exercised. # Run the professional plan directly so its assigned-patient semantic assertion is exercised.
result=subprocess.run([str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(HERE/'plans/professional.jmx'),'-l',str(root/'professional.csv'),'-j',str(root/'professional.log'),'-Jhost=127.0.0.1','-Jport='+str(server.server_port),'-Jusers_file='+str(users),'-Jusers=2','-Jtotal_duration_seconds=8','-Jramp_seconds=0','-Jthink_mean_ms=0','-Jthink_stddev_ms=0','-Jsession_pause_ms=100','-Jsession_stddev_ms=25','-Jperiod_from=2026-01-01T00:00:00Z','-Jperiod_to=2027-01-01T00:00:00Z'],capture_output=True,text=True) professional=E.parse(HERE/'plans/professional.jmx')
for collector in professional.iter('kg.apc.jmeter.perfmon.PerfMonCollector'):collector.set('enabled','false')
professional.write(root/'professional.jmx')
result=subprocess.run([str(Path.home()/'.local/bin/jmeter'),'-n','-t',str(root/'professional.jmx'),'-l',str(root/'professional.csv'),'-j',str(root/'professional.log'),'-Jperfmon_enabled=false','-Jhost=127.0.0.1','-Jport='+str(server.server_port),'-Jusers_file='+str(users),'-Jusers=2','-Jtotal_duration_seconds=8','-Jramp_seconds=0','-Jthink_mean_ms=0','-Jthink_stddev_ms=0','-Jsession_pause_ms=100','-Jsession_stddev_ms=25','-Jperiod_from=2026-01-01T00:00:00Z','-Jperiod_to=2027-01-01T00:00:00Z'],capture_output=True,text=True)
import csv import csv
with (root/'professional.csv').open() as f: samples=list(csv.DictReader(f)) with (root/'professional.csv').open() as f: samples=list(csv.DictReader(f))
assert result.returncode==0 and samples and all(r['success']=='true' for r in samples), result.stdout+result.stderr assert result.returncode==0 and samples and all(r['success']=='true' for r in samples), result.stdout+result.stderr
print('professional passed;',len(samples),'samples; token renewal exercised across all plans') print('professional passed;',len(samples),'samples; token renewal exercised across all plans')
Handler.break_insights=True Handler.break_insights=True
failed=subprocess.run(['python3',str(HERE/'run.py'),'review','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','0','--duration','5','--ramp','0','--think-mean-ms','0','--think-stddev-ms','0','--session-pause-ms','0','--session-stddev-ms','0','--output',str(root/'expected-failure')],capture_output=True,text=True) failed=subprocess.run(['python3',str(HERE/'run.py'),'review','--no-perfmon','--host','127.0.0.1','--port',str(server.server_port),'--ca',str(cert),'--users-file',str(users),'--users','2','--warmup','0','--duration','5','--ramp','0','--think-mean-ms','0','--think-stddev-ms','0','--session-pause-ms','0','--session-stddev-ms','0','--output',str(root/'expected-failure')],capture_output=True,text=True)
assert failed.returncode!=0 assert failed.returncode!=0
assert json.loads((root/'expected-failure/run.json').read_text())['failed_http_samples']>0 assert json.loads((root/'expected-failure/run.json').read_text())['failed_http_samples']>0
print('Unexpected upstream failure correctly invalidates the run') print('Unexpected upstream failure correctly invalidates the run')