forked from mdmonk/python_snippets
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rrd.py
61 lines (53 loc) · 2.13 KB
/
rrd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env python
"""rrdtool stuff."""
import subprocess
import os
import logging
class RRD(object):
def __init__(self, name, options):
# Sanity checks.
directory = options['directory']
if not name.endswith('.rrd'):
raise Exception('Output file <%s> should end with .rrd' % name)
if not os.path.exists(directory):
raise Exception('Output directory <%s> does not exist' % directory)
self.filename = os.path.join(directory, name)
self._init_datasources(options)
if not os.path.exists(self.filename):
self._create(options)
self._get_last_update()
def _create(self, options):
logging.info('Creating RRD %s' % self.filename)
args = \
['/usr/bin/rrdtool', 'create', self.filename,
'--start=%s' % options['start']] \
+ ['DS:%s:%s:%s:%s:%s' %
(value['ds'], value['dst'], options['heartbeat'],
value['min'], value['max'])
for value in self._datasources] \
+ options['rras'].split(' ')
retcode = subprocess.call(args)
if retcode != 0:
raise Exception('<%s> exited with code %d' % (' '.join(args), retcode))
def _get_last_update(self):
rrdtool = subprocess.Popen(['/usr/bin/rrdtool', 'last', self.filename],
stdout=subprocess.PIPE)
self.last_update = int(rrdtool.stdout.read().rstrip())
retcode = rrdtool.wait()
if retcode != 0:
raise Exception('rrdlast exited with code %d' % retcode)
logging.debug('Last update on RRD <%s> was %d'
% (self.filename, self.last_update))
def update(self, timestamp, values):
"""Updates the RRD.
@param values list of values.
"""
args = [
'/usr/bin/rrdupdate',
self.filename,
('%d:' % timestamp) + ':'.join(values),
]
logging.debug('Executing: <%s>' % ' '.join(args))
retcode = subprocess.call(args)
if retcode != 0:
raise Exception('rrdupdate exited with code %d' % retcode)