1 #-*- coding: ISO-8859-1 -*-
2 # collect.py: the python collectd-unixsock module.
3 #
4 # Requires collectd to be configured with the unixsock plugin, like so:
5 #
6 # LoadPlugin unixsock
7 # <Plugin unixsock>
8 # SocketFile "/var/run/collectd-unixsock"
9 # SocketPerms "0775"
10 # </Plugin>
11 #
12 # Copyright (C) 2008 Clay Loveless <clay@killersoft.com>
13 #
14 # This software is provided 'as-is', without any express or implied
15 # warranty. In no event will the author be held liable for any damages
16 # arising from the use of this software.
17 #
18 # Permission is granted to anyone to use this software for any purpose,
19 # including commercial applications, and to alter it and redistribute it
20 # freely, subject to the following restrictions:
21 #
22 # 1. The origin of this software must not be misrepresented; you must not
23 # claim that you wrote the original software. If you use this software
24 # in a product, an acknowledgment in the product documentation would be
25 # appreciated but is not required.
26 # 2. Altered source versions must be plainly marked as such, and must not be
27 # misrepresented as being the original software.
28 # 3. This notice may not be removed or altered from any source distribution.
30 import socket, string
32 class Collect(object):
34 def __init__(self, path='/var/run/collectd-unixsock'):
35 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
36 self._path = path
37 self._sock.connect(self._path)
39 def list(self):
40 numvalues = self._cmd('LISTVAL')
41 lines = []
42 if numvalues:
43 lines = self._readlines(numvalues)
44 return lines
46 def get(self, val, flush=True):
47 numvalues = self._cmd('GETVAL "' + val + '"')
48 lines = []
49 if numvalues:
50 lines = self._readlines(numvalues)
51 if flush:
52 self._cmd('FLUSH identifier="' + val + '"')
53 return lines
55 def _cmd(self, c):
56 self._sock.send(c + "\n")
57 stat = string.split(self._readline())
58 status = int(stat[0])
59 if status:
60 return status
61 return False
63 '''
64 _readline and _readlines methods borrowed from the _fileobject class
65 in sockets.py, tweaked a little bit for use in the collectd context.
66 '''
67 def _readline(self):
68 data = ''
69 buf = []
70 recv = self._sock.recv
71 while data != "\n":
72 data = recv(1)
73 if not data:
74 break
75 if data != "\n":
76 buf.append(data)
77 return ''.join(buf)
79 def _readlines(self, sizehint=0):
80 total = 0
81 list = []
82 while True:
83 line = self._readline()
84 if not line:
85 break
86 list.append(line)
87 total = len(list)
88 if sizehint and total >= sizehint:
89 break
90 return list
92 def __del__(self):
93 self._sock.close()
97 if __name__ == '__main__':
99 '''
100 Example usage:
101 Collect values from socket and dump to STDOUT.
102 '''
104 c = Collect('/var/run/collectd-unixsock')
105 list = c.list()
107 for val in list:
108 stamp, key = string.split(val)
109 glines = c.get(key)
110 print stamp + ' ' + key + ' ' + ', '.join(glines)