f8355f80028923e26f11cb3e4e5739193ead0aa0
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
31 import string
34 class Collect(object):
36 def __init__(self, path='/var/run/collectd-unixsock'):
37 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
38 self._path = path
39 self._sock.connect(self._path)
41 def list(self):
42 numvalues = self._cmd('LISTVAL')
43 lines = []
44 if numvalues:
45 lines = self._readlines(numvalues)
46 return lines
48 def get(self, val, flush=True):
49 numvalues = self._cmd('GETVAL "' + val + '"')
50 lines = []
51 if numvalues:
52 lines = self._readlines(numvalues)
53 if flush:
54 self._cmd('FLUSH identifier="' + val + '"')
55 return lines
57 def _cmd(self, c):
58 self._sock.send(c + "\n")
59 stat = string.split(self._readline())
60 status = int(stat[0])
61 if status:
62 return status
63 return False
65 def _readline(self):
66 """Read single line from socket"""
67 data = ''
68 buf = []
69 recv = self._sock.recv
70 while data != "\n":
71 data = recv(1)
72 if not data:
73 break
74 if data != "\n":
75 buf.append(data)
76 return ''.join(buf)
78 def _readlines(self, sizehint=0):
79 """Read multiple lines from socket"""
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()
96 if __name__ == '__main__':
97 """Collect values from socket and dump to STDOUT"""
99 c = Collect('/var/run/collectd-unixsock')
100 list = c.list()
102 for val in list:
103 stamp, key = string.split(val)
104 glines = c.get(key)
105 print stamp + ' ' + key + ' ' + ', '.join(glines)