]> arthur.barton.de Git - netdata.git/blob - python.d/python_modules/base.py
fix redis mutual exclusion
[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['pass'])
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.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
490                     #sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
491                     #sock.settimeout(self.update_every)
492                     sock.settimeout(0.5)
493                     sock.connect((self.host, self.port))
494                     sock.settimeout(0.5)  # Just to be sure
495                 else:
496                     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
497                     #sock.settimeout(self.update_every)
498                     sock.settimeout(0.05)
499                     sock.connect(self.unix_socket)
500                     sock.settimeout(0.05)  # Just to be sure
501
502             except Exception as e:
503                 self.error(str(e))
504                 self.sock = None
505                 return None
506
507         if self.request != "".encode():
508             try:
509                 sock.send(self.request)
510             except Exception:
511                 try:
512                     sock.shutdown(1)
513                     sock.close()
514                 except:
515                     pass
516                 self.sock = None
517                 return None
518
519         size = 2
520         try:
521             data = sock.recv(size).decode()
522         except Exception as e:
523             self.error(str(e))
524             sock.close()
525             return None
526
527         while True:
528             # implement something like TCP Window Scaling
529             if size < 4096:
530                 size *= 2
531             buf = sock.recv(size)
532             data += buf.decode()
533             if len(buf) < size:
534                 break
535
536         return data
537
538     def _parse_config(self):
539         """
540         Parse configuration data
541         :return: boolean
542         """
543         if self.name is None or self.name == str(None):
544             self.name = ""
545         else:
546             self.name = str(self.name)
547         try:
548             self.unix_socket = str(self.configuration['socket'])
549         except (KeyError, TypeError):
550             self.error("No unix socket specified. Trying TCP/IP socket.")
551             try:
552                 self.host = str(self.configuration['host'])
553             except (KeyError, TypeError):
554                 self.error("No host specified. Using: '" + self.host + "'")
555             try:
556                 self.port = int(self.configuration['port'])
557             except (KeyError, TypeError):
558                 self.error("No port specified. Using: '" + str(self.port) + "'")
559         try:
560             self.request = str(self.configuration['request'])
561         except (KeyError, TypeError):
562             self.error("No request specified. Using: '" + str(self.request) + "'")
563         self.request = self.request.encode()
564
565
566 class LogService(SimpleService):
567     def __init__(self, configuration=None, name=None):
568         self.log_path = ""
569         self._last_position = 0
570         # self._log_reader = None
571         SimpleService.__init__(self, configuration=configuration, name=name)
572         self.retries = 100000  # basically always retry
573
574     def _get_raw_data(self):
575         """
576         Get log lines since last poll
577         :return: list
578         """
579         lines = []
580         try:
581             if os.path.getsize(self.log_path) < self._last_position:
582                 self._last_position = 0
583             elif os.path.getsize(self.log_path) == self._last_position:
584                 return None
585             with open(self.log_path, "r") as fp:
586                 fp.seek(self._last_position)
587                 for i, line in enumerate(fp):
588                     lines.append(line)
589                 self._last_position = fp.tell()
590         except Exception as e:
591             self.error(self.__module__, str(e))
592
593         if len(lines) != 0:
594             return lines
595         return None
596
597     def check(self):
598         """
599         Parse basic configuration and check if log file exists
600         :return: boolean
601         """
602         if self.name is not None or self.name != str(None):
603             self.name = ""
604         else:
605             self.name = str(self.name)
606         try:
607             self.log_path = str(self.configuration['path'])
608         except (KeyError, TypeError):
609             self.error("No path to log specified. Using: '" + self.log_path + "'")
610
611         if os.access(self.log_path, os.R_OK):
612             return True
613         else:
614             self.error("Cannot access file: '" + self.log_path + "'")
615             return False
616
617     def create(self):
618         status = SimpleService.create(self)
619         self._last_position = 0
620         return status
621
622
623 class ExecutableService(SimpleService):
624     #command_whitelist = ['exim', 'postqueue']
625     bad_substrings = ('&', '|', ';', '>', '<')
626
627     def __init__(self, configuration=None, name=None):
628         self.command = ""
629         SimpleService.__init__(self, configuration=configuration, name=name)
630
631     def _get_raw_data(self):
632         """
633         Get raw data from executed command
634         :return: str
635         """
636         try:
637             p = Popen(self.command, stdout=PIPE, stderr=PIPE)
638         except Exception as e:
639             self.error(self.__module__, str(e))
640             return None
641         data = []
642         for line in p.stdout.readlines():
643             data.append(str(line.decode()))
644
645         if len(data) == 0:
646             return None
647
648         return data
649
650     def check(self):
651         """
652         Parse basic configuration, check if command is whitelisted and is returning values
653         :return: boolean
654         """
655         if self.name is not None or self.name != str(None):
656             self.name = ""
657         else:
658             self.name = str(self.name)
659         try:
660             self.command = str(self.configuration['command'])
661         except (KeyError, TypeError):
662             self.error("No command specified. Using: '" + self.command + "'")
663         self.command = self.command.split(' ')
664         #if self.command[0] not in self.command_whitelist:
665         #    self.error("Command is not whitelisted.")
666         #    return False
667
668         for arg in self.command[1:]:
669             if any(st in arg for st in self.bad_substrings):
670                 self.error("Bad command argument:" + " ".join(self.command[1:]))
671                 return False
672         # test command and search for it in /usr/sbin or /sbin when failed
673         base = self.command[0].split('/')[-1]
674         if self._get_raw_data() is None:
675             for prefix in ['/sbin/', '/usr/sbin/']:
676                 self.command[0] = prefix + base
677                 if os.path.isfile(self.command[0]):
678                     break
679                 #if self._get_raw_data() is not None:
680                 #    break
681
682         if self._get_data() is None or len(self._get_data()) == 0:
683             return False
684         return True