Source

woocode / rrdtool / test.py

from time import time

import rrdtool
import random

rrd = 'memory.rrd'

def get_ts():
    return int(time())

def incr_ts(ts, step=300):
    return ts + step

def create_rrd():
    ret = rrdtool.create(rrd, '--step', '300', '--start', '0',
        'DS:active:GAUGE:600:0:4000000',
        'DS:inactive:GAUGE:600:0:4000000',
        'DS:free:GAUGE:600:0:4000000',
        'RRA:MIN:0.5:12:1440',
        'RRA:MAX:0.5:12:1440',
        'RRA:AVERAGE:0.5:1:1440')
    if ret:
        print rrdtool.error()

def update_rrd(ts, *values):
    values = '%d:%s' % (ts, ':'.join([str(i) for i in values]))
    print values
    ret = rrdtool.update(rrd,
            values)
    if ret:
        print rrdtool.error()

def graph():
    ret = rrdtool.graph('memory.png',
        '--vertical-label=KBytes',
        'DEF:active=memory.rrd:active:AVERAGE',
        'DEF:inactive=memory.rrd:inactive:AVERAGE',
        'DEF:free=memory.rrd:free:AVERAGE',
        'LINE1:active#ff0000:Active Usage',
        'LINE1:inactive#0400ff:Inactive Usage',
        'LINE1:free#0700ff:Free'
        )

    if ret:
        print rrdtool.error()

def memprofile():
    d = {}
    with open('/proc/meminfo') as fb:
        for line in fb:
            values = [k.strip() for k in line.split(':')]
            values[1] = values[-1].split()[0]
            d[values[0].lower()] = int(values[-1])
    return d

def get_ranint():
    return random.randrange(1000, 2500)

def main():
    print 'start'
    ts = get_ts()
    times = 50
    create_rrd()
    while True:
        if times == 0:
            break
        d = memprofile()
        update_rrd(ts, d['active'] + get_ranint(), d['inactive'] + get_ranint(), d['memfree'] + get_ranint())
        ts += 300
        times -= 1
    graph()


if __name__ == '__main__':
    main()