]> arthur.barton.de Git - netdata.git/blob - python.d/python_modules/base.py
fix redis
[netdata.git] / python.d / python_modules / base.py
1 # -*- coding: utf-8 -*-
2 # Description: prototypes for netdata python.d modules
3 # Author: Pawel Krupa (paulfantom)
4
5 import time
6 import sys
7 import os
8 import socket
9 import resource
10 try:
11     import urllib.request as urllib2
12 except ImportError:
13     import urllib2
14
15 from subprocess import Popen, PIPE
16
17 import threading
18 import msg
19
20
21 class BaseService(threading.Thread):
22     """
23     Prototype of Service class.
24     Implemented basic functionality to run jobs by `python.d.plugin`
25     """
26     def __init__(self, configuration=None, name=None):
27         """
28         This needs to be initialized in child classes
29         :param configuration: dict
30         :param name: str
31         """
32         threading.Thread.__init__(self)
33         self._data_stream = ""
34         self.daemon = True
35         self.retries = 0
36         self.retries_left = 0
37         self.priority = 140000
38         self.update_every = 1
39         self.name = name
40         self.override_name = None
41         self.chart_name = ""
42         self._dimensions = []
43         self._charts = []
44         if configuration is None:
45             self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
46             raise RuntimeError
47         else:
48             self._extract_base_config(configuration)
49             self.timetable = {}
50             self.create_timetable()
51
52     def _extract_base_config(self, config):
53         """
54         Get basic parameters to run service
55         Minimum config:
56             config = {'update_every':1,
57                       'priority':100000,
58                       'retries':0}
59         :param config: dict
60         """
61         try:
62             self.override_name = config.pop('name')
63         except KeyError:
64             pass
65         self.update_every = int(config.pop('update_every'))
66         self.priority = int(config.pop('priority'))
67         self.retries = int(config.pop('retries'))
68         self.retries_left = self.retries
69         self.configuration = config
70
71     def create_timetable(self, freq=None):
72         """
73         Create service timetable.
74         `freq` is optional
75         Example:
76             timetable = {'last': 1466370091.3767564,
77                          'next': 1466370092,
78                          'freq': 1}
79         :param freq: int
80         """
81         if freq is None:
82             freq = self.update_every
83         now = time.time()
84         self.timetable = {'last': now,
85                           'next': now - (now % freq) + freq,
86                           'freq': freq}
87
88     def _run_once(self):
89         """
90         Executes self.update(interval) and draws run time chart.
91         Return value presents exit status of update()
92         :return: boolean
93         """
94         t_start = time.time()
95         # check if it is time to execute job update() function
96         if self.timetable['next'] > t_start:
97             #msg.debug(self.chart_name + " will be run in " +
98             #          str(int((self.timetable['next'] - t_start) * 1000)) + " ms")
99             msg.debug(self.chart_name,"will be run in", str(int((self.timetable['next'] - t_start) * 1000)), "ms")
100             return True
101
102         since_last = int((t_start - self.timetable['last']) * 1000000)
103         #msg.debug(self.chart_name +
104         #          " ready to run, after " + str(int((t_start - self.timetable['last']) * 1000)) +
105         #          " ms (update_every: " + str(self.timetable['freq'] * 1000) +
106         #          " ms, latency: " + str(int((t_start - self.timetable['next']) * 1000)) + " ms)")
107         msg.debug(self.chart_name,
108                   "ready to run, after", str(int((t_start - self.timetable['last']) * 1000)),
109                   "ms (update_every:", str(self.timetable['freq'] * 1000),
110                   "ms, latency:", str(int((t_start - self.timetable['next']) * 1000)), "ms")
111         if not self.update(since_last):
112             return False
113         t_end = time.time()
114         self.timetable['next'] = t_end - (t_end % self.timetable['freq']) + self.timetable['freq']
115         # draw performance graph
116         run_time = str(int((t_end - t_start) * 1000))
117         #run_time_chart = "BEGIN netdata.plugin_pythond_" + self.chart_name + " " + str(since_last) + '\n'
118         #run_time_chart += "SET run_time = " + run_time + '\n'
119         #run_time_chart += "END\n"
120         #sys.stdout.write(run_time_chart)
121         sys.stdout.write("BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" % \
122                          (self.chart_name, str(since_last), run_time))
123
124         #msg.debug(self.chart_name + " updated in " + str(run_time) + " ms")
125         msg.debug(self.chart_name, "updated in", str(run_time), "ms")
126         self.timetable['last'] = t_start
127         return True
128
129     def run(self):
130         """
131         Runs job in thread. Handles retries.
132         Exits when job failed or timed out.
133         :return: None
134         """
135         self.timetable['last'] = time.time()
136         while True:
137             try:
138                 status = self._run_once()
139             except Exception as e:
140                 msg.error("Something wrong: " + str(e))
141                 return
142             if status:
143                 time.sleep(self.timetable['next'] - time.time())
144                 self.retries_left = self.retries
145             else:
146                 self.retries_left -= 1
147                 if self.retries_left <= 0:
148                     msg.error("no more retries. Exiting")
149                     return
150                 else:
151                     time.sleep(self.timetable['freq'])
152
153     def _format(self, *args):
154         params = []
155         append = params.append
156         for p in args:
157             if p is None:
158                 append(p)
159                 continue
160             if type(p) is not str:
161                 p = str(p)
162             if ' ' in p:
163                 p = "'" + p + "'"
164             append(p)
165         return params
166
167     def _line(self, instruction, *params):
168         """
169         Converts *params to string and joins them with one space between every one.
170         :param params: str/int/float
171         """
172         #self._data_stream += instruction
173         tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
174
175         self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
176
177         # self.error(str(" ".join(tmp)))
178         # for p in params:
179         #     if p is None:
180         #         p = ""
181         #     else:
182         #         p = str(p)
183         #     if len(p) == 0:
184         #         p = "''"
185         #     if ' ' in p:
186         #         p = "'" + p + "'"
187         #     self._data_stream += " " + p
188         #self._data_stream += "\n"
189
190     def chart(self, type_id, name="", title="", units="", family="",
191               category="", charttype="line", priority="", update_every=""):
192         """
193         Defines a new chart.
194         :param type_id: str
195         :param name: str
196         :param title: str
197         :param units: str
198         :param family: str
199         :param category: str
200         :param charttype: str
201         :param priority: int/str
202         :param update_every: int/str
203         """
204         self._charts.append(type_id)
205         #self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
206
207         p = self._format(type_id, name, title, units, family, category, charttype, priority, update_every)
208         self._line("CHART", *p)
209
210     def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
211         """
212         Defines a new dimension for the chart
213         :param id: str
214         :param name: str
215         :param algorithm: str
216         :param multiplier: int/str
217         :param divisor: int/str
218         :param hidden: boolean
219         :return:
220         """
221         try:
222             int(multiplier)
223         except TypeError:
224             self.error("malformed dimension: multiplier is not a number:", multiplier)
225             multiplier = 1
226         try:
227             int(divisor)
228         except TypeError:
229             self.error("malformed dimension: divisor is not a number:", divisor)
230             divisor = 1
231         if name is None:
232             name = id
233         if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
234             algorithm = "absolute"
235
236         self._dimensions.append(str(id))
237         if hidden:
238             p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
239             #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
240         else:
241             p = self._format(id, name, algorithm, multiplier, divisor)
242             #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
243
244         self._line("DIMENSION", *p)
245
246     def begin(self, type_id, microseconds=0):
247         """
248         Begin data set
249         :param type_id: str
250         :param microseconds: int
251         :return: boolean
252         """
253         if type_id not in self._charts:
254             self.error("wrong chart type_id:", type_id)
255             return False
256         try:
257             int(microseconds)
258         except TypeError:
259             self.error("malformed begin statement: microseconds are not a number:", microseconds)
260             microseconds = ""
261
262         self._line("BEGIN", type_id, str(microseconds))
263         return True
264
265     def set(self, id, value):
266         """
267         Set value to dimension
268         :param id: str
269         :param value: int/float
270         :return: boolean
271         """
272         if id not in self._dimensions:
273             self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
274             return False
275         try:
276             value = str(int(value))
277         except TypeError:
278             self.error("cannot set non-numeric value:", value)
279             return False
280         self._line("SET", id, "=", str(value))
281         return True
282
283     def end(self):
284         self._line("END")
285
286     def commit(self):
287         """
288         Upload new data to netdata
289         """
290         print(self._data_stream)
291         self._data_stream = ""
292
293     def error(self, *params):
294         """
295         Show error message on stderr
296         """
297         msg.error(self.chart_name, *params)
298
299     def debug(self, *params):
300         """
301         Show debug message on stderr
302         """
303         msg.debug(self.chart_name, *params)
304
305     def info(self, *params):
306         """
307         Show information message on stderr
308         """
309         msg.info(self.chart_name, *params)
310
311     def check(self):
312         """
313         check() prototype
314         :return: boolean
315         """
316         msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
317         return False
318
319     def create(self):
320         """
321         create() prototype
322         :return: boolean
323         """
324         msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
325         return False
326
327     def update(self, interval):
328         """
329         update() prototype
330         :param interval: int
331         :return: boolean
332         """
333         msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
334         return False
335
336
337 class SimpleService(BaseService):
338     def __init__(self, configuration=None, name=None):
339         self.order = []
340         self.definitions = {}
341         BaseService.__init__(self, configuration=configuration, name=name)
342
343     def _get_data(self):
344         """
345         Get some data
346         :return: dict
347         """
348         return {}
349
350     def check(self):
351         """
352         :return:
353         """
354         return True
355
356     def create(self):
357         """
358         Create charts
359         :return: boolean
360         """
361         data = self._get_data()
362         if data is None:
363             return False
364
365         idx = 0
366         for name in self.order:
367             options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
368             self.chart(self.chart_name + "." + name, *options)
369             # check if server has this datapoint
370             for line in self.definitions[name]['lines']:
371                 if line[0] in data:
372                     self.dimension(*line)
373             idx += 1
374
375         self.commit()
376         return True
377
378     def update(self, interval):
379         """
380         Update charts
381         :param interval: int
382         :return: boolean
383         """
384         data = self._get_data()
385         if data is None:
386             return False
387
388         updated = False
389         for chart in self.order:
390             if self.begin(self.chart_name + "." + chart, interval):
391                 updated = True
392                 for dim in self.definitions[chart]['lines']:
393                     try:
394                         self.set(dim[0], data[dim[0]])
395                     except KeyError:
396                         pass
397                 self.end()
398
399         self.commit()
400
401         return updated
402
403
404 class UrlService(SimpleService):
405     def __init__(self, configuration=None, name=None):
406         self.url = ""
407         self.user = None
408         self.password = None
409         SimpleService.__init__(self, configuration=configuration, name=name)
410
411     def __add_auth(self):
412         passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
413         passman.add_password(None, self.url, self.user, self.password)
414         authhandler = urllib2.HTTPBasicAuthHandler(passman)
415         opener = urllib2.build_opener(authhandler)
416         urllib2.install_opener(opener)
417
418     def _get_raw_data(self):
419         """
420         Get raw data from http request
421         :return: str
422         """
423         raw = None
424         try:
425             f = urllib2.urlopen(self.url, timeout=self.update_every)
426         except Exception as e:
427             msg.error(self.__module__, str(e))
428             return None
429
430         try:
431             raw = f.read().decode('utf-8')
432         except Exception as e:
433             msg.error(self.__module__, str(e))
434         finally:
435             f.close()
436         return raw
437
438     def check(self):
439         """
440         Format configuration data and try to connect to server
441         :return: boolean
442         """
443         if self.name is None or self.name == str(None):
444             self.name = 'local'
445             self.chart_name += "_" + self.name
446         else:
447             self.name = str(self.name)
448         try:
449             self.url = str(self.configuration['url'])
450         except (KeyError, TypeError):
451             pass
452         try:
453             self.user = str(self.configuration['user'])
454         except (KeyError, TypeError):
455             pass
456         try:
457             self.password = str(self.configuration['password'])
458         except (KeyError, TypeError):
459             pass
460
461         if self.user is not None and self.password is not None:
462             self.__add_auth()
463
464         if self._get_data() is not None:
465             return True
466         else:
467             return False
468
469
470 class SocketService(SimpleService):
471     def __init__(self, configuration=None, name=None):
472         self.host = "localhost"
473         self.port = None
474         self.sock = None
475         self.unix_socket = None
476         self.request = ""
477         SimpleService.__init__(self, configuration=configuration, name=name)
478
479     def _get_raw_data(self):
480         """
481         Get raw data with low-level "socket" module.
482         :return: str
483         """
484         if self.sock is None:
485             try:
486                 if self.unix_socket is None:
487                     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
488                     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
489                     sock.settimeout(self.update_every)
490                     sock.connect((self.host, self.port))
491                 else:
492                     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
493                     sock.settimeout(self.update_every)
494                     sock.connect(self.unix_socket)
495
496             except Exception as e:
497                 self.error(str(e))
498                 self.sock = None
499                 return None
500
501         if self.request != "".encode():
502             try:
503                 sock.send(self.request)
504             except Exception:
505                 try:
506                     sock.shutdown(1)
507                     sock.close()
508                 except:
509                     pass
510                 self.sock = None
511                 return None
512
513         #data = sock.recv(2)
514         data = ""
515         try:
516             while True:
517                 #try:
518                 buf = sock.recv(1024, 0x40)  # get 1024 bytes in NON-BLOCKING mode
519                 #except socket.error:
520                 #    break
521
522                 if len(buf) == 0:
523                     break
524                 else:
525                     data += buf.decode()
526         except:
527             sock.close()
528             return None
529
530         return data
531
532     def _parse_config(self):
533         """
534         Parse configuration data
535         :return: boolean
536         """
537         if self.name is not None or self.name != str(None):
538             self.name = ""
539         else:
540             self.name = str(self.name)
541         try:
542             self.unix_socket = str(self.configuration['socket'])
543         except (KeyError, TypeError):
544             self.error("No unix socket specified. Trying TCP/IP socket.")
545             try:
546                 self.host = str(self.configuration['host'])
547             except (KeyError, TypeError):
548                 self.error("No host specified. Using: '" + self.host + "'")
549             try:
550                 self.port = int(self.configuration['port'])
551             except (KeyError, TypeError):
552                 self.error("No port specified. Using: '" + str(self.port) + "'")
553         try:
554             self.request = str(self.configuration['request'])
555         except (KeyError, TypeError):
556             self.error("No request specified. Using: '" + str(self.request) + "'")
557         self.request = self.request.encode()
558
559
560 class LogService(SimpleService):
561     def __init__(self, configuration=None, name=None):
562         self.log_path = ""
563         self._last_position = 0
564         # self._log_reader = None
565         SimpleService.__init__(self, configuration=configuration, name=name)
566         self.retries = 100000  # basically always retry
567
568     def _get_raw_data(self):
569         """
570         Get log lines since last poll
571         :return: list
572         """
573         lines = []
574         try:
575             if os.path.getsize(self.log_path) < self._last_position:
576                 self._last_position = 0
577             elif os.path.getsize(self.log_path) == self._last_position:
578                 return None
579             with open(self.log_path, "r") as fp:
580                 fp.seek(self._last_position)
581                 for i, line in enumerate(fp):
582                     lines.append(line)
583                 self._last_position = fp.tell()
584         except Exception as e:
585             self.error(self.__module__, str(e))
586
587         if len(lines) != 0:
588             return lines
589         return None
590
591     def check(self):
592         """
593         Parse basic configuration and check if log file exists
594         :return: boolean
595         """
596         if self.name is not None or self.name != str(None):
597             self.name = ""
598         else:
599             self.name = str(self.name)
600         try:
601             self.log_path = str(self.configuration['path'])
602         except (KeyError, TypeError):
603             self.error("No path to log specified. Using: '" + self.log_path + "'")
604
605         if os.access(self.log_path, os.R_OK):
606             return True
607         else:
608             self.error("Cannot access file: '" + self.log_path + "'")
609             return False
610
611     def create(self):
612         status = SimpleService.create(self)
613         self._last_position = 0
614         return status
615
616
617 class ExecutableService(SimpleService):
618     command_whitelist = ['exim', 'postqueue']
619     bad_substrings = ('&', '|', ';', '>', '<')
620
621     def __init__(self, configuration=None, name=None):
622         self.command = ""
623         SimpleService.__init__(self, configuration=configuration, name=name)
624
625     def _get_raw_data(self):
626         """
627         Get raw data from executed command
628         :return: str
629         """
630         try:
631             p = Popen(self.command, stdout=PIPE, stderr=PIPE)
632         except Exception as e:
633             self.error(self.__module__, str(e))
634             return None
635         data = []
636         for line in p.stdout.readlines():
637             data.append(str(line.decode()))
638
639         return data
640
641     def check(self):
642         """
643         Parse basic configuration, check if command is whitelisted and is returning values
644         :return: boolean
645         """
646         if self.name is not None or self.name != str(None):
647             self.name = ""
648         else:
649             self.name = str(self.name)
650         # try:
651         #     self.command = str(self.configuration['path'])
652         # except (KeyError, TypeError):
653         #     self.error("No command specified. Using: '" + self.command + "'")
654         self.command = self.command.split(' ')
655         if self.command[0] not in self.command_whitelist:
656             self.error("Command is not whitelisted.")
657             return False
658
659         for arg in self.command[1:]:
660             if any(st in arg for st in self.bad_substrings):
661                 self.error("Bad command argument:" + " ".join(self.command[1:]))
662                 return False
663         # test command and search for it in /usr/sbin or /sbin when failed
664         base = self.command[0]
665         if self._get_raw_data() is None:
666             for prefix in ['/sbin/', '/usr/sbin/']:
667                 self.command[0] = prefix + base
668                 if os.path.isfile(self.command[0]):
669                     break
670                 #if self._get_raw_data() is not None:
671                 #    break
672
673         if self._get_data() is None or len(self._get_data()) == 0:
674             return False
675         return True