Report aligned per-second CPU power requests latency and errors

This commit is contained in:
Steffen committed 2026-10-08 12:59:43 +02:00
1 parent 17f3b0dbd3
commit 743674a022
5 files changed
+201

No files matched your search

+35
View File
@@ -284,3 +284,38 @@ python3 tools/energy-jmeter/verify-perfmon.py --host 192.168.1.125 --output tool
This verifies that JMeter saves readings while it is still running, then checks 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; metric coverage and decoding. A monitoring-only check succeeded against the NUC;
comparison with independent Linux readings is still needed to validate accuracy. comparison with independent Linux readings is still needed to validate accuracy.
## Time-aligned graphs and one-second request reporting
Every finished run generates `report.html` (interactive), `report.png`, `report.svg`
and `per-second.csv`. The plotting dependency is Matplotlib, already installed on
this computer. If setting up another load generator, install Matplotlib there.
All panels share UTC timestamps and experiment-relative one-second intervals,
starting at the recorded warmup start. Warmup is shaded; measurement begins after
the exact configured warmup duration.
CPU, RAM, power, disk and network values are averaged only when multiple samples
fall into a second; missing readings stay blank and create graph gaps. Application
requests and failed requests are counted individually per second. Mean/p95/max
latency is grouped by request start time, with p95 using the nearest-rank definition.
Requests spanning the measurement end are excluded from measured application figures,
matching `run.json`. Meter requests and internal timing samples never count as
application traffic. Seconds without requests have zero request/error counts and
no response-time value. The graph keeps every one-second bin; a wide full-run view
can visually compress points. Use the interactive range controls to inspect seconds.
For a running experiment, generate a snapshot or keep refreshing its artifacts:
```bash
python3 tools/energy-jmeter/report.py tools/energy-jmeter/results/RUN_FOLDER
python3 tools/energy-jmeter/report.py tools/energy-jmeter/results/RUN_FOLDER --follow
```
`--follow` refreshes artifacts every minute, using one-second data, and generates the
final report when the run finishes. Open `report.html` locally and use **Refresh
snapshot** to load new data. It provides a shared cursor across panels and a measured-
window selection. The latest seconds of a running snapshot are provisional because
JMeter writes request samples after their responses arrive. Missing future seconds
are not plotted as zeros. Report creation runs on the load generator.
Verify aggregation with `python3 tools/energy-jmeter/verify-report.py`.
+25
View File
@@ -0,0 +1,25 @@
<!doctype html><html lang="en"><meta charset="utf-8"><title>HealthApp measurement report</title>
<style>body{font:15px system-ui;margin:24px;background:#f6f8fb;color:#182230}header,section{background:white;padding:18px;margin-bottom:16px;border-radius:8px}canvas{width:100%;height:210px}h2{font-size:16px;margin:0 0 8px}.controls{position:sticky;top:0;background:white;padding:12px;z-index:2;border-bottom:1px solid #ccc}input{width:220px}#cursor{font-family:monospace}small{color:#485566}</style>
<header><h1>HealthApp — one-second measurements</h1><p id="status"></p><p id="window"></p><small>All panels share the same UTC timeline. Grey shading marks warmup. Missing measurements are gaps, never zero-filled. Latency is grouped by request start time; intervals with no requests have no latency value. Counter values are the plug’s absolute Wh counter.</small></header>
<div class="controls"><button onclick="location.reload()">Refresh snapshot</button> <button id="all">Include warmup</button> <button id="measured">Measured window</button> <label>From second <input id="from" type="number" min="0"></label> <label>To second <input id="to" type="number" min="1"></label><p id="cursor">Move over any graph to inspect the same second across all panels.</p></div><main id="charts"></main>
<script type="application/json" id="data">PAYLOAD_JSON</script><script>
const data=JSON.parse(document.getElementById('data').textContent),rows=data.rows,fields=data.fields,idx=Object.fromEntries(fields.map((f,i)=>[f,i]));
const panels=[['CPU (%)',['cpu_percent','cpu_iowait_percent']],['RAM (%)',['ram_percent']],['RAM / swap (MiB)',['ram_MiB','swap_MiB']],['Power (W)',['power_watts']],['Application requests / errors per second',['requests_s','errors_s']],['Application latency (ms)',['latency_mean_ms','latency_p95_ms','latency_max_ms']],['Disk / network (KiB/s)',['disk_read_KiB_s','disk_write_KiB_s','network_receive_KiB_s','network_send_KiB_s']],['Plug counter (Wh)',['energy_counter_Wh']]];
const colors=['#176bc1','#dc5a18','#379d55','#9450bd'];let lo=0,hi=rows.length-1,selected=null;
const date=t=>new Date(t).toISOString();document.getElementById('status').textContent=`${data.scenario}: ${data.status}. ${rows.length} recorded one-second intervals.`;
document.getElementById('window').textContent=`Measured window: ${date(data.timeline.measurement_start_ms)} — ${date(data.timeline.measurement_end_ms)}. All times UTC.`;
document.getElementById('measured').disabled=rows[rows.length-1][0]<data.timeline.measurement_start_ms;
const canvases=panels.map(([title,keys])=>{const s=document.createElement('section');s.innerHTML=`<h2>${title}</h2><canvas></canvas><small></small>`;document.getElementById('charts').append(s);return {canvas:s.querySelector('canvas'),legend:s.querySelector('small'),keys}});
function draw(){for(const {canvas,legend,keys} of canvases){const rect=canvas.getBoundingClientRect(),dpr=window.devicePixelRatio||1;canvas.width=rect.width*dpr;canvas.height=210*dpr;const c=canvas.getContext('2d');c.scale(dpr,dpr);const w=rect.width,h=210,left=55,right=w-15,top=12,bottom=h-32;
const x=i=>left+(right-left)*(i-lo)/Math.max(1,hi-lo);let max=1;for(let i=lo;i<=hi;i++)for(const k of keys){const v=rows[i][idx[k]];if(v!==null)max=Math.max(max,v)}max*=1.08;const y=v=>bottom-(bottom-top)*v/max;
const warmupIndex=(data.timeline.measurement_start_ms-rows[0][0])/1000;if(warmupIndex>lo){c.fillStyle='#e9ebee';c.fillRect(left,top,Math.max(0,Math.min(right,x(warmupIndex))-left),bottom-top)}
c.font='11px system-ui';for(let j=0;j<=4;j++){const yy=bottom-j*(bottom-top)/4;c.strokeStyle='#e4e7ec';c.beginPath();c.moveTo(left,yy);c.lineTo(right,yy);c.stroke();c.fillStyle='#526070';c.fillText((max*j/4).toFixed(max<10?2:0),2,yy+3)}
keys.forEach((k,n)=>{c.strokeStyle=colors[n];c.lineWidth=1.2;c.beginPath();let pen=false;for(let i=lo;i<=hi;i++){const v=rows[i][idx[k]];if(v===null){pen=false;continue}if(!pen)c.moveTo(x(i),y(v));else c.lineTo(x(i),y(v));pen=true}c.stroke()});
c.fillStyle='#526070';for(let j=0;j<=3;j++){const i=Math.round(lo+(hi-lo)*j/3);c.fillText(date(rows[i][0]).slice(11,19),Math.max(left,Math.min(right-55,x(i)-22)),h-10)}
if(selected!==null&&selected>=lo&&selected<=hi){c.strokeStyle='#182230';c.beginPath();c.moveTo(x(selected),top);c.lineTo(x(selected),bottom);c.stroke()}
legend.innerHTML=keys.map((k,n)=>`<span style="color:${colors[n]}">${k}${selected===null?'':': '+(rows[selected][idx[k]]===null?'missing':rows[selected][idx[k]].toFixed(3))}</span>`).join(' · ');
canvas.onmousemove=e=>{selected=Math.max(lo,Math.min(hi,Math.round(lo+(e.offsetX-left)/(right-left)*Math.max(1,hi-lo))));document.getElementById('cursor').textContent=`${date(rows[selected][0])} — ${rows[selected][idx.phase]}`;draw()};}}
function limits(a,b){lo=Math.max(0,Math.min(rows.length-1,a));hi=Math.max(lo,Math.min(rows.length-1,b));selected=null;document.getElementById('from').value=lo;document.getElementById('to').value=hi;draw()}
document.getElementById('all').onclick=()=>limits(0,rows.length-1);document.getElementById('measured').onclick=()=>limits(Math.floor((data.timeline.measurement_start_ms-rows[0][0])/1000),rows.length-1);
for(const id of ['from','to'])document.getElementById(id).onchange=()=>limits(Number(document.getElementById('from').value),Number(document.getElementById('to').value));window.onresize=draw;limits(0,rows.length-1);
</script></html>
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Align raw JMeter measurements into experiment-relative one-second bins."""
import os,time
import argparse,csv,datetime as dt,json,math
from pathlib import Path
FIELDS=['timestamp_ms','phase','cpu_percent','cpu_iowait_percent','ram_percent','ram_MiB','swap_MiB','power_watts','energy_counter_Wh','disk_read_KiB_s','disk_write_KiB_s','network_receive_KiB_s','network_send_KiB_s','requests_s','errors_s','error_percent','latency_mean_ms','latency_p95_ms','latency_max_ms','power_poll_errors_s']
METRIC_FIELDS={'CPU combined':('cpu_percent',1),'CPU iowait':('cpu_iowait_percent',1),'Memory usedperc':('ram_percent',1),'Memory actualused':('ram_MiB',1/1048576),'Swap used':('swap_MiB',1/1048576),'Disks I/O readbytes':('disk_read_KiB_s',1/1024),'Disks I/O writebytes':('disk_write_KiB_s',1/1024),'Network I/O bytesrecv':('network_receive_KiB_s',1/1024),'Network I/O bytessent':('network_send_KiB_s',1/1024)}
def read_csv(path):
if not path.exists():return []
with path.open(newline='') as f:
# Autoflush can expose the final line during a write; ignore incomplete rows.
return [r for r in csv.DictReader(f) if r and None not in r and all(v is not None for v in r.values())]
def finished(meta):
return ('finished_utc' in meta
and (not meta.get('perfmon',{}).get('enabled') or 'server_metrics' in meta or 'monitoring_error' in meta)
and (not meta.get('shelly',{}).get('enabled') or 'power_energy' in meta or 'power_error' in meta))
def build(folder):
folder=Path(folder);meta=json.loads((folder/'run.json').read_text());timeline=json.loads((folder/'timeline.json').read_text())
start=timeline['warmup_start_ms'];measurement_start=timeline['measurement_start_ms'];end=timeline['measurement_end_ms']
bins={};latest=start;bad_rows=0
def bucket(timestamp):
nonlocal latest
if not start<=timestamp<end:return None
index=int((timestamp-start)//1000);latest=max(latest,timestamp)
return bins.setdefault(index,{'averages':{},'latencies':[],'requests_s':0,'errors_s':0,'power_poll_errors_s':0})
def reading(timestamp,field,value):
row=bucket(timestamp)
if row is not None and math.isfinite(value):row['averages'].setdefault(field,[]).append(value)
for r in read_csv(folder/'perfmon.csv'):
try:
if r.get('success','true').lower()!='true':continue
timestamp=float(r['timeStamp']);value=float(r['elapsed'])/1000
if value<0:continue
for suffix,(field,scale) in METRIC_FIELDS.items():
if r['label'].endswith(' '+suffix):reading(timestamp,field,value*scale);break
except (ValueError,KeyError,TypeError):bad_rows+=1
for r in read_csv(folder/'shelly.csv'):
try:
timestamp=float(r['timeStamp'])+float(r['elapsed'])/2
row=bucket(timestamp)
if r['success'].lower()!='true':
if row is not None:row['power_poll_errors_s']+=1
continue
reading(timestamp,'power_watts',float(r['shelly_power_watts']))
reading(timestamp,'energy_counter_Wh',float(r['shelly_energy_wh']))
except (ValueError,KeyError,TypeError):bad_rows+=1
for r in read_csv(folder/'samples.csv'):
try:
if not r['label'].startswith('HTTP '):continue
row=bucket(float(r['timeStamp']))
if row is None:continue
if float(r['timeStamp'])>=measurement_start and float(r['timeStamp'])+float(r['elapsed'])>end:continue
row['requests_s']+=1;row['errors_s']+=r['success'].lower()!='true';row['latencies'].append(float(r['elapsed']))
except (ValueError,KeyError,TypeError):bad_rows+=1
completed=finished(meta)
if completed:
finish=int(dt.datetime.fromisoformat(meta['finished_utc']).timestamp()*1000)
observed_end=min(end,finish)
else:observed_end=min(end,int(latest)+1)
count=max(1,math.ceil((observed_end-start)/1000));rows=[]
for index in range(count):
timestamp=start+index*1000;source=bins.get(index,{'averages':{},'latencies':[],'requests_s':0,'errors_s':0,'power_poll_errors_s':0})
row={field:None for field in FIELDS};row.update(timestamp_ms=timestamp,phase='warmup' if timestamp<measurement_start else 'measurement')
for field,values in source['averages'].items():row[field]=sum(values)/len(values)
for field in ['requests_s','errors_s','power_poll_errors_s']:row[field]=source[field]
latencies=sorted(source['latencies'])
if latencies:
row.update(error_percent=100*source['errors_s']/len(latencies),latency_mean_ms=sum(latencies)/len(latencies),latency_p95_ms=latencies[max(0,math.ceil(.95*len(latencies))-1)],latency_max_ms=max(latencies))
rows.append(row)
with (folder/'per-second.csv').open('w') as f:
w=csv.DictWriter(f,fieldnames=FIELDS);w.writeheader();w.writerows(rows)
payload={'fields':FIELDS,'rows':[[r[k] for k in FIELDS] for r in rows],'timeline':timeline,'status':'completed' if meta.get('exit_code')==0 else 'incomplete/failed' if completed else 'running — snapshot','scenario':meta['scenario'],'skipped_rows':bad_rows,'interval_ms':1000}
encoded=json.dumps(payload,separators=(',',':'),allow_nan=False).replace('<','\\u003c')
template=(Path(__file__).parent/'report-template.html').read_text()
(folder/'report.html').write_text(template.replace('PAYLOAD_JSON',encoded))
plot(rows,timeline,folder,payload['status'])
print(f'Report saved: {folder / "report.html"}; {count} one-second intervals; {payload["status"]}')
return rows
PANELS=[('CPU utilisation (%)',['cpu_percent','cpu_iowait_percent']),('RAM usage (%)',['ram_percent']),('RAM / swap (MiB)',['ram_MiB','swap_MiB']),('Power (W)',['power_watts']),('Application requests / errors per second',['requests_s','errors_s']),('Application latency (ms)',['latency_mean_ms','latency_p95_ms','latency_max_ms']),('Disk / network (KiB/s)',['disk_read_KiB_s','disk_write_KiB_s','network_receive_KiB_s','network_send_KiB_s']),('Plug energy counter (Wh)',['energy_counter_Wh'])]
def plot(rows,timeline,folder,status):
os.environ.setdefault('MPLCONFIGDIR',str(folder/'.matplotlib'))
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
times=[dt.datetime.fromtimestamp(r['timestamp_ms']/1000,dt.timezone.utc) for r in rows]
warmup_end=dt.datetime.fromtimestamp(timeline['measurement_start_ms']/1000,dt.timezone.utc)
finish=dt.datetime.fromtimestamp(timeline['measurement_end_ms']/1000,dt.timezone.utc)
figure,axes=plt.subplots(len(PANELS),1,sharex=True,figsize=(16,19),layout='constrained')
for ax,(title,fields) in zip(axes,PANELS):
for field in fields:ax.plot(times,[float('nan') if r[field] is None else r[field] for r in rows],label=field,linewidth=.8)
ax.set_ylabel(title);ax.grid(alpha=.2);ax.legend(loc='upper right',fontsize=7)
if times[0]<warmup_end:ax.axvspan(times[0],min(warmup_end,times[-1]),color='gray',alpha=.15)
if times[0]<=warmup_end<=times[-1]:ax.axvline(warmup_end,color='black',linestyle='--',linewidth=.8)
ax.set_ylim(bottom=0)
if fields[0]=='requests_s' and not any(r['requests_s'] for r in rows):
ax.set_ylim(-.05,1);ax.text(.5,.5,'Zero application requests',transform=ax.transAxes,ha='center')
if fields[0]=='latency_mean_ms' and all(r['latency_mean_ms'] is None for r in rows):
ax.set_ylim(0,1);ax.text(.5,.5,'No requests: response time unavailable',transform=ax.transAxes,ha='center')
axes[-1].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S',tz=dt.timezone.utc))
axes[-1].set_xlabel('UTC time — experiment-relative one-second bins; shaded area is warmup')
figure.suptitle('HealthApp measurements — '+status+'\nMeasured window: '+warmup_end.isoformat()+' to '+finish.isoformat(),fontsize=13)
figure.savefig(folder/'report.png',dpi=150);figure.savefig(folder/'report.svg');plt.close(figure)
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('run_folder');parser.add_argument('--follow',action='store_true');args=parser.parse_args()
while True:
build(args.run_folder)
if not args.follow or finished(json.loads((Path(args.run_folder)/'run.json').read_text())):break
time.sleep(60)
+7
View File
@@ -132,4 +132,11 @@ if not a.no_shelly:
metadata['power_error']=str(error);print('Invalid power measurement:',error);code=1 metadata['power_error']=str(error);print('Invalid power measurement:',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))
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) raise SystemExit(code)
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Verify clock alignment, one-second aggregation and missing-data semantics."""
import csv,datetime as dt,json,tempfile
from pathlib import Path
import report
with tempfile.TemporaryDirectory(prefix='healthapp-report-') as name:
folder=Path(name);start=1000000
(folder/'timeline.json').write_text(json.dumps({'warmup_start_ms':start,'measurement_start_ms':start+2000,'measurement_end_ms':start+5000}))
(folder/'run.json').write_text(json.dumps({'scenario':'mixed','exit_code':0,'finished_utc':dt.datetime.fromtimestamp((start+5000)/1000,dt.timezone.utc).isoformat()}))
def write(name,fields,rows):
with (folder/name).open('w') as f:w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(rows)
write('samples.csv',['timeStamp','elapsed','label','success'],[{'timeStamp':start+2050,'elapsed':200,'label':'HTTP Read profile','success':'true'},{'timeStamp':start+2200,'elapsed':1000,'label':'HTTP Read overview','success':'false'},{'timeStamp':start+2250,'elapsed':10,'label':'POWER Shelly status','success':'true'}])
write('perfmon.csv',['timeStamp','elapsed','label','success'],[{'timeStamp':start+2100,'elapsed':30000,'label':'NUC CPU combined','success':'true'},{'timeStamp':start+2800,'elapsed':50000,'label':'NUC CPU combined','success':'true'},{'timeStamp':start+2110,'elapsed':104857600000,'label':'NUC Memory actualused','success':'true'}])
write('shelly.csv',['timeStamp','elapsed','label','success','shelly_power_watts','shelly_energy_wh'],[{'timeStamp':start+2150,'elapsed':100,'label':'POWER Shelly status','success':'true','shelly_power_watts':20,'shelly_energy_wh':3}])
original=report.plot;report.plot=lambda *args:None
rows=report.build(folder)
report.plot=original
assert len(rows)==5
assert rows[2]['phase']=='measurement' and rows[1]['phase']=='warmup'
assert rows[2]['cpu_percent']==40 and rows[2]['ram_MiB']==100 and rows[2]['power_watts']==20
assert rows[2]['requests_s']==2 and rows[2]['errors_s']==1 and rows[2]['error_percent']==50
assert rows[2]['latency_mean_ms']==600 and rows[2]['latency_p95_ms']==1000
assert rows[3]['cpu_percent'] is None and rows[3]['latency_mean_ms'] is None and rows[3]['requests_s']==0
assert (folder/'report.html').exists() and (folder/'per-second.csv').exists()
print('One-second request/latency/error aggregation, UTC alignment, warmup and missing measurements passed')