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