Merge branch 'pw/exclude_regex'
[collectd.git] / contrib / collectd_unixsock.py
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.
29
30 import socket
31 import sys
32
33
34 class Collectd():
35
36     def __init__(self, path='/var/run/collectd-unixsock', noisy=False):
37         self.noisy = noisy
38         self.path = path
39         self._sock = self._connect()
40
41     def flush(self, timeout=None, plugins=[], identifiers=[]):
42         """Send a FLUSH command.
43
44         Full documentation:
45             http://collectd.org/wiki/index.php/Plain_text_protocol#FLUSH
46
47         """
48         # have to pass at least one plugin or identifier
49         if not plugins and not identifiers:
50             return None
51         args = []
52         if timeout:
53             args.append("timeout=%s" % timeout)
54         if plugins:
55             plugin_args = map(lambda x: "plugin=%s" % x, plugins)
56             args.extend(plugin_args)
57         if identifiers:
58             identifier_args = map(lambda x: "identifier=%s" % x, identifiers)
59             args.extend(identifier_args)
60         return self._cmd('FLUSH %s' % ' '.join(args))
61
62     def getthreshold(self, identifier):
63         """Send a GETTHRESHOLD command.
64
65         Full documentation:
66             http://collectd.org/wiki/index.php/Plain_text_protocol#GETTHRESHOLD
67
68         """
69         numvalues = self._cmd('GETTHRESHOLD "%s"' % identifier)
70         lines = []
71         if numvalues:
72             lines = self._readlines(numvalues)
73         return lines
74
75     def getval(self, identifier, flush_after=True):
76         """Send a GETVAL command.
77
78         Also flushes the identifier if flush_after is True.
79
80         Full documentation:
81             http://collectd.org/wiki/index.php/Plain_text_protocol#GETVAL
82
83         """
84         numvalues = self._cmd('GETVAL "%s"' % identifier)
85         lines = []
86         if numvalues:
87             lines = self._readlines(numvalues)
88         if flush_after:
89             self.flush(identifiers=[identifier])
90         return lines
91
92     def listval(self):
93         """Send a LISTVAL command.
94
95         Full documentation:
96             http://collectd.org/wiki/index.php/Plain_text_protocol#LISTVAL
97
98         """
99         numvalues = self._cmd('LISTVAL')
100         lines = []
101         if numvalues:
102             lines = self._readlines(numvalues)
103         return lines
104
105     def putnotif(self, message, options={}):
106         """Send a PUTNOTIF command.
107
108         Options must be passed as a Python dictionary. Example:
109           options={'severity': 'failure', 'host': 'example.com'}
110
111         Full documentation:
112             http://collectd.org/wiki/index.php/Plain_text_protocol#PUTNOTIF
113
114         """
115         args = []
116         if options:
117             options_args = map(lambda x: "%s=%s" % (x, options[x]), options)
118             args.extend(options_args)
119         args.append('message="%s"' % message)
120         return self._cmd('PUTNOTIF %s' % ' '.join(args))
121
122     def putval(self, identifier, values, options={}):
123         """Send a PUTVAL command.
124
125         Options must be passed as a Python dictionary. Example:
126           options={'interval': 10}
127
128         Full documentation:
129             http://collectd.org/wiki/index.php/Plain_text_protocol#PUTVAL
130
131         """
132         args = []
133         args.append('"%s"' % identifier)
134         if options:
135             options_args = map(lambda x: "%s=%s" % (x, options[x]), options)
136             args.extend(options_args)
137         values = map(str, values)
138         args.append(':'.join(values))
139         return self._cmd('PUTVAL %s' % ' '.join(args))
140
141     def _cmd(self, c):
142         try:
143             return self._cmdattempt(c)
144         except socket.error, (errno, errstr):
145             sys.stderr.write("[error] Sending to socket failed: [%d] %s\n"
146                              % (errno, errstr))
147             self._sock = self._connect()
148             return self._cmdattempt(c)
149
150     def _cmdattempt(self, c):
151         if self.noisy:
152             print "[send] %s" % c
153         if not self._sock:
154             sys.stderr.write("[error] Socket unavailable. Can not send.")
155             return False
156         self._sock.send(c + "\n")
157         status_message = self._readline()
158         if self.noisy:
159             print "[recive] %s" % status_message
160         if not status_message:
161             return None
162         code, message = status_message.split(' ', 1)
163         if int(code):
164             return int(code)
165         return False
166
167     def _connect(self):
168         try:
169             sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
170             sock.connect(self.path)
171             if self.noisy:
172                 print "[socket] connected to %s" % self.path
173             return sock
174         except socket.error, (errno, errstr):
175             sys.stderr.write("[error] Connecting to socket failed: [%d] %s"
176                              % (errno, errstr))
177             return None
178
179     def _readline(self):
180         """Read single line from socket"""
181         if not self._sock:
182             sys.stderr.write("[error] Socket unavailable. Can not read.")
183             return None
184         try:
185             data = ''
186             buf = []
187             recv = self._sock.recv
188             while data != "\n":
189                 data = recv(1)
190                 if not data:
191                     break
192                 if data != "\n":
193                     buf.append(data)
194             return ''.join(buf)
195         except socket.error, (errno, errstr):
196             sys.stderr.write("[error] Reading from socket failed: [%d] %s"
197                              % (errno, errstr))
198             self._sock = self._connect()
199             return None
200
201     def _readlines(self, sizehint=0):
202         """Read multiple lines from socket"""
203         total = 0
204         list = []
205         while True:
206             line = self._readline()
207             if not line:
208                 break
209             list.append(line)
210             total = len(list)
211             if sizehint and total >= sizehint:
212                 break
213         return list
214
215     def __del__(self):
216         if not self._sock:
217             return
218         try:
219             self._sock.close()
220         except socket.error, (errno, errstr):
221             sys.stderr.write("[error] Closing socket failed: [%d] %s"
222                              % (errno, errstr))
223
224
225 if __name__ == '__main__':
226     """Collect values from socket and dump to STDOUT"""
227
228     c = Collectd('/var/run/collectd-unixsock', noisy=True)
229     list = c.listval()
230     for val in list:
231         stamp, identifier = val.split()
232         print "\n%s" % identifier
233         print "\tUpdate time: %s" % stamp
234
235         values = c.getval(identifier)
236         print "\tValue list: %s" % ', '.join(values)
237
238         # don't fetch thresholds by default because collectd will crash
239         # if there is no treshold for the given identifier
240         #thresholds = c.getthreshold(identifier)
241         #print "\tThresholds: %s" % ', '.join(thresholds)