]> arthur.barton.de Git - netdata.git/blob - python.d/python_modules/base.py
Merge pull request #677 from paulfantom/master
[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
211
212     def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
213         """
214         Defines a new dimension for the chart
215         :param id: str
216         :param name: str
217         :param algorithm: str
218         :param multiplier: int/str
219         :param divisor: int/str
220         :param hidden: boolean
221         :return:
222         """
223         try:
224             int(multiplier)
225         except TypeError:
226             self.error("malformed dimension: multiplier is not a number:", multiplier)
227             multiplier = 1
228         try:
229             int(divisor)
230         except TypeError:
231             self.error("malformed dimension: divisor is not a number:", divisor)
232             divisor = 1
233         if name is None:
234             name = id
235         if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
236             algorithm = "absolute"
237
238         self._dimensions.append(id)
239         if hidden:
240             p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
241             #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
242         else:
243             p = self._format(id, name, algorithm, multiplier, divisor)
244             #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
245
246         self._line("DIMENSION", *p)
247
248     def begin(self, type_id, microseconds=0):
249         """
250         Begin data set
251         :param type_id: str
252         :param microseconds: int
253         :return: boolean
254         """
255         if type_id not in self._charts:
256             self.error("wrong chart type_id:", type_id)
257             return False
258         try:
259             int(microseconds)
260         except TypeError:
261             self.error("malformed begin statement: microseconds are not a number:", microseconds)
262             microseconds = ""
263
264         self._line("BEGIN", type_id, str(microseconds))
265         return True
266
267     def set(self, id, value):
268         """
269         Set value to dimension
270         :param id: str
271         :param value: int/float
272         :return: boolean
273         """
274         if id not in self._dimensions:
275             self.error("wrong dimension id:", id)
276             return False
277         try:
278             value = str(int(value))
279         except TypeError:
280             self.error("cannot set non-numeric value:", value)
281             return False
282         self._line("SET", id, "=", str(value))
283         return True
284
285     def end(self):
286         self._line("END")
287
288     def commit(self):
289         """
290         Upload new data to netdata
291         """
292         print(self._data_stream)
293         self._data_stream = ""
294
295     def error(self, *params):
296         """
297         Show error message on stderr
298         """
299         msg.error(self.chart_name, *params)
300
301     def debug(self, *params):
302         """
303         Show debug message on stderr
304         """
305         msg.debug(self.chart_name, *params)
306
307     def info(self, *params):
308         """
309         Show information message on stderr
310         """
311         msg.info(self.chart_name, *params)
312
313     def check(self):
314         """
315         check() prototype
316         :return: boolean
317         """
318         msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
319         return False
320
321     def create(self):
322         """
323         create() prototype
324         :return: boolean
325         """
326         msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
327         return False
328
329     def update(self, interval):
330         """
331         update() prototype
332         :param interval: int
333         :return: boolean
334         """
335         msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
336         return False
337
338
339 class SimpleService(BaseService):
340     def __init__(self, configuration=None, name=None):
341         self.order = []
342         self.definitions = {}
343         BaseService.__init__(self, configuration=configuration, name=name)
344
345     def _get_data(self):
346         """
347         Get some data
348         :return: dict
349         """
350         return {}
351
352     def check(self):
353         """
354         :return:
355         """
356         return True
357
358     def create(self):
359         """
360         Create charts
361         :return: boolean
362         """
363         data = self._get_data()
364         if data is None:
365             return False
366
367         idx = 0
368         for name in self.order:
369             options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
370             self.chart(self.chart_name + "." + name, *options)
371             # check if server has this datapoint
372             for line in self.definitions[name]['lines']:
373                 if line[0] in data:
374                     self.dimension(*line)
375             idx += 1
376
377         self.commit()
378         return True
379
380     def update(self, interval):
381         """
382         Update charts
383         :param interval: int
384         :return: boolean
385         """
386         data = self._get_data()
387         if data is None:
388             return False
389
390         updated = False
391         for chart in self.order:
392             if self.begin(self.chart_name + "." + chart, interval):
393                 updated = True
394                 for dim in self.definitions[chart]['lines']:
395                     try:
396                         self.set(dim[0], data[dim[0]])
397                     except KeyError:
398                         pass
399                 self.end()
400
401         self.commit()
402
403         return updated
404
405
406 class UrlService(SimpleService):
407     def __init__(self, configuration=None, name=None):
408         self.url = ""
409         self.user = None
410         self.password = None
411         SimpleService.__init__(self, configuration=configuration, name=name)
412
413     def __add_auth(self):
414         passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
415         passman.add_password(None, self.url, self.user, self.password)
416         authhandler = urllib2.HTTPBasicAuthHandler(passman)
417         opener = urllib2.build_opener(authhandler)
418         urllib2.install_opener(opener)
419
420     def _get_raw_data(self):
421         """
422         Get raw data from http request
423         :return: str
424         """
425         raw = None
426         try:
427             f = urllib2.urlopen(self.url, timeout=self.update_every)
428         except Exception as e:
429             msg.error(self.__module__, str(e))
430             return None
431
432         try:
433             raw = f.read().decode('utf-8')
434         except Exception as e:
435             msg.error(self.__module__, str(e))
436         finally:
437             f.close()
438         return raw
439
440     def check(self):
441         """
442         Format configuration data and try to connect to server
443         :return: boolean
444         """
445         if self.name is None or self.name == str(None):
446             self.name = 'local'
447             self.chart_name += "_" + self.name
448         else:
449             self.name = str(self.name)
450         try:
451             self.url = str(self.configuration['url'])
452         except (KeyError, TypeError):
453             pass
454         try:
455             self.user = str(self.configuration['user'])
456         except (KeyError, TypeError):
457             pass
458         try:
459             self.password = str(self.configuration['password'])
460         except (KeyError, TypeError):
461             pass
462
463         if self.user is not None and self.password is not None:
464             self.__add_auth()
465
466         if self._get_data() is not None:
467             return True
468         else:
469             return False
470
471
472 class SocketService(SimpleService):
473     def __init__(self, configuration=None, name=None):
474         self.host = "localhost"
475         self.port = None
476         self.sock = None
477         self.unix_socket = None
478         self.request = ""
479         SimpleService.__init__(self, configuration=configuration, name=name)
480
481     def _get_raw_data(self):
482         """
483         Get raw data with low-level "socket" module.
484         :return: str
485         """
486         if self.sock is None:
487             try:
488                 if self.unix_socket is None:
489                     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
490                     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
491                     #sock.settimeout(self.update_every)
492                     sock.connect((self.host, self.port))
493                 else:
494                     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
495                     #sock.settimeout(self.update_every)
496                     sock.connect(self.unix_socket)
497
498             except Exception as e:
499                 self.error(e)
500                 self.sock = None
501                 return None
502
503         if self.request != "".encode():
504             try:
505                 sock.send(self.request)
506             except Exception:
507                 try:
508                     sock.shutdown(1)
509                     sock.close()
510                 except:
511                     pass
512                 self.sock = None
513                 return None
514
515         data = sock.recv(2)
516         try:
517             while True:
518                 try:
519                     buf = sock.recv(1024, 0x40)  # get 1024 bytes in NON-BLOCKING mode
520                 except socket.error:
521                     break
522
523                 if len(buf) == 0:
524                     break
525                 else:
526                     data += buf
527         except:
528             sock.close()
529             return None
530
531         return data.decode()
532
533     def _parse_config(self):
534         """
535         Parse configuration data
536         :return: boolean
537         """
538         if self.name is not None or self.name != str(None):
539             self.name = ""
540         else:
541             self.name = str(self.name)
542         try:
543             self.unix_socket = str(self.configuration['socket'])
544         except (KeyError, TypeError):
545             self.error("No unix socket specified. Trying TCP/IP socket.")
546             try:
547                 self.host = str(self.configuration['host'])
548             except (KeyError, TypeError):
549                 self.error("No host specified. Using: '" + self.host + "'")
550             try:
551                 self.port = int(self.configuration['port'])
552             except (KeyError, TypeError):
553                 self.error("No port specified. Using: '" + str(self.port) + "'")
554         try:
555             self.request = str(self.configuration['request'])
556         except (KeyError, TypeError):
557             self.error("No request specified. Using: '" + str(self.request) + "'")
558         self.request = self.request.encode()
559
560
561 class LogService(SimpleService):
562     def __init__(self, configuration=None, name=None):
563         self.log_path = ""
564         self._last_position = 0
565         # self._log_reader = None
566         SimpleService.__init__(self, configuration=configuration, name=name)
567         self.retries = 100000  # basically always retry
568
569     def _get_raw_data(self):
570         """
571         Get log lines since last poll
572         :return: list
573         """
574         lines = []
575         try:
576             if os.path.getsize(self.log_path) < self._last_position:
577                 self._last_position = 0
578             elif os.path.getsize(self.log_path) == self._last_position:
579                 return None
580             with open(self.log_path, "r") as fp:
581                 fp.seek(self._last_position)
582                 for i, line in enumerate(fp):
583                     lines.append(line)
584                 self._last_position = fp.tell()
585         except Exception as e:
586             self.error(self.__module__, str(e))
587
588         if len(lines) != 0:
589             return lines
590         return None
591
592     def check(self):
593         """
594         Parse basic configuration and check if log file exists
595         :return: boolean
596         """
597         if self.name is not None or self.name != str(None):
598             self.name = ""
599         else:
600             self.name = str(self.name)
601         try:
602             self.log_path = str(self.configuration['path'])
603         except (KeyError, TypeError):
604             self.error("No path to log specified. Using: '" + self.log_path + "'")
605
606         if os.access(self.log_path, os.R_OK):
607             return True
608         else:
609             self.error("Cannot access file: '" + self.log_path + "'")
610             return False
611
612     def create(self):
613         status = SimpleService.create(self)
614         self._last_position = 0
615         return status
616
617
618 class ExecutableService(SimpleService):
619     command_whitelist = ['exim', 'postqueue']
620     bad_substrings = ('&', '|', ';', '>', '<')
621
622     def __init__(self, configuration=None, name=None):
623         self.command = ""
624         SimpleService.__init__(self, configuration=configuration, name=name)
625
626     def _get_raw_data(self):
627         """
628         Get raw data from executed command
629         :return: str
630         """
631         try:
632             p = Popen(self.command, stdout=PIPE, stderr=PIPE)
633         except Exception as e:
634             self.error(self.__module__, str(e))
635             return None
636         data = []
637         for line in p.stdout.readlines():
638             data.append(str(line.decode()))
639
640         return data
641
642     def check(self):
643         """
644         Parse basic configuration, check if command is whitelisted and is returning values
645         :return: boolean
646         """
647         if self.name is not None or self.name != str(None):
648             self.name = ""
649         else:
650             self.name = str(self.name)
651         # try:
652         #     self.command = str(self.configuration['path'])
653         # except (KeyError, TypeError):
654         #     self.error("No command specified. Using: '" + self.command + "'")
655         self.command = self.command.split(' ')
656         if self.command[0] not in self.command_whitelist:
657             self.error("Command is not whitelisted.")
658             return False
659
660         for arg in self.command[1:]:
661             if any(st in arg for st in self.bad_substrings):
662                 self.error("Bad command argument:" + " ".join(self.command[1:]))
663                 return False
664         # test command and search for it in /usr/sbin or /sbin when failed
665         base = self.command[0]
666         if self._get_raw_data() is None:
667             for prefix in ['/sbin/', '/usr/sbin/']:
668                 self.command[0] = prefix + base
669                 if os.path.isfile(self.command[0]):
670                     break
671                 #if self._get_raw_data() is not None:
672                 #    break
673
674         if self._get_data() is None or len(self._get_data()) == 0:
675             return False
676         return True