Files

36 lines
2.6 KiB
Python

"""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