Process Munin RRD files with Python

Today I wanted to process an Munin RRD file with Python, in order to create an Plotly chart. The result can be found here. The use-case doesn't really matter, it could also be an export to JSON or any other sort of post-processing.

It also doesn't matter which Munin database is used, they all contain AVERAGE, MIN and MAX. The available RRA are always the same. The example script below shows how it's possible to fetch the data and create an data object (list) for further processing.

import rrdtool
import datetime

# see https://oss.oetiker.ch/rrdtool/doc/rrdfetch.en.html
munin_rrd_file = '/var/lib/munin/localhost/localhost-cpu-system-d.rrd'
report_start = 'now-30d'
report_end = 'now'
report_step = '1d'

# get the average and create list of tuples which contain datetime object and value
result = rrdtool.fetch(munin_rrd_file, "AVERAGE", '-s', report_start, '-e', report_end, '-r', report_step)
start, end, step = result[0]
data = [(datetime.datetime.fromtimestamp(start + i * step), v[0]) for i, v in enumerate(result[2]) if v[0] is not None]
average = [v[0] for v in result[2] if v[0] is not None]
average = sum(average)/len(average)
print(data)
print(average)

# get the minimum
result = rrdtool.fetch(munin_rrd_file, "MIN", '-s', report_start, '-e', report_end, '-r', report_step)
minimum = min([v[0] for v in result[2] if v[0] is not None])
print(minimum)

# get the maximum
result = rrdtool.fetch(munin_rrd_file, "MAX", '-s', report_start, '-e', report_end, '-r', report_step)
maximum = max([v[0] for v in result[2] if v[0] is not None])
print(maximum)

Schreibe einen Kommentar