1 # -*- coding: utf-8 -*-
2 # Description: prototypes for netdata python.d modules
3 # Author: Pawel Krupa (paulfantom)
10 import urllib.request as urllib2
14 from subprocess import Popen, PIPE
20 class BaseService(threading.Thread):
22 Prototype of Service class.
23 Implemented basic functionality to run jobs by `python.d.plugin`
25 def __init__(self, configuration=None, name=None):
27 This needs to be initialized in child classes
28 :param configuration: dict
31 threading.Thread.__init__(self)
32 self._data_stream = ""
36 self.priority = 140000
39 self.override_name = None
43 if configuration is None:
44 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
47 self._extract_base_config(configuration)
49 self.create_timetable()
51 def _extract_base_config(self, config):
53 Get basic parameters to run service
55 config = {'update_every':1,
61 self.override_name = config.pop('name')
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
70 def create_timetable(self, freq=None):
72 Create service timetable.
75 timetable = {'last': 1466370091.3767564,
81 freq = self.update_every
83 self.timetable = {'last': now,
84 'next': now - (now % freq) + freq,
89 Executes self.update(interval) and draws run time chart.
90 Return value presents exit status of update()
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")
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):
113 self.timetable['next'] = t_end - (t_end % self.timetable['freq']) + self.timetable['freq']
114 # draw performance graph
115 run_time = str(int((t_end - t_start) * 1000))
116 #run_time_chart = "BEGIN netdata.plugin_pythond_" + self.chart_name + " " + str(since_last) + '\n'
117 #run_time_chart += "SET run_time = " + run_time + '\n'
118 #run_time_chart += "END\n"
119 run_time_chart = "BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" % \
120 (self.chart_name, str(since_last), run_time)
121 sys.stdout.write(run_time_chart)
122 #msg.debug(self.chart_name + " updated in " + str(run_time) + " ms")
123 msg.debug(self.chart_name, "updated in", str(run_time), "ms")
124 self.timetable['last'] = t_start
129 Runs job in thread. Handles retries.
130 Exits when job failed or timed out.
133 self.timetable['last'] = time.time()
136 status = self._run_once()
137 except Exception as e:
138 msg.error("Something wrong: " + str(e))
141 time.sleep(self.timetable['next'] - time.time())
142 self.retries_left = self.retries
144 self.retries_left -= 1
145 if self.retries_left <= 0:
146 msg.error("no more retries. Exiting")
149 time.sleep(self.timetable['freq'])
151 def _format(self, *input):
153 append = params.append
158 if type(p) is not str:
165 def _line(self, instruction, *params):
167 Converts *params to string and joins them with one space between every one.
168 :param params: str/int/float
170 #self._data_stream += instruction
171 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
173 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
175 # self.error(str(" ".join(tmp)))
185 # self._data_stream += " " + p
186 #self._data_stream += "\n"
188 def chart(self, type_id, name="", title="", units="", family="",
189 category="", charttype="line", priority="", update_every=""):
198 :param charttype: str
199 :param priority: int/str
200 :param update_every: int/str
202 self._charts.append(type_id)
203 #self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
205 p = self._format(type_id, name, title, units, family, category, charttype, priority, update_every)
206 self._line("CHART", *p)
210 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
212 Defines a new dimension for the chart
215 :param algorithm: str
216 :param multiplier: int/str
217 :param divisor: int/str
218 :param hidden: boolean
224 self.error("malformed dimension: multiplier is not a number:", multiplier)
229 self.error("malformed dimension: divisor is not a number:", divisor)
233 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
234 algorithm = "absolute"
236 self._dimensions.append(id)
238 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
239 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
241 p = self._format(id, name, algorithm, multiplier, divisor)
242 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
244 self._line("DIMENSION", *p)
246 def begin(self, type_id, microseconds=0):
250 :param microseconds: int
253 if type_id not in self._charts:
254 self.error("wrong chart type_id:", type_id)
259 self.error("malformed begin statement: microseconds are not a number:", microseconds)
262 self._line("BEGIN", type_id, str(microseconds))
265 def set(self, id, value):
267 Set value to dimension
269 :param value: int/float
272 if id not in self._dimensions:
273 self.error("wrong dimension id:", id)
276 value = str(int(value))
278 self.error("cannot set non-numeric value:", value)
280 self._line("SET", id, "=", str(value))
288 Upload new data to netdata
290 print(self._data_stream)
291 self._data_stream = ""
293 def error(self, *params):
295 Show error message on stderr
297 msg.error(self.chart_name, *params)
299 def debug(self, *params):
301 Show debug message on stderr
303 msg.debug(self.chart_name, *params)
305 def info(self, *params):
307 Show information message on stderr
309 msg.info(self.chart_name, *params)
316 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
324 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
327 def update(self, interval):
333 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
337 class SimpleService(BaseService):
338 def __init__(self, configuration=None, name=None):
340 self.definitions = {}
341 BaseService.__init__(self, configuration=configuration, name=name)
361 data = self._get_data()
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']:
372 self.dimension(*line)
378 def update(self, interval):
384 data = self._get_data()
389 for chart in self.order:
390 if self.begin(self.chart_name + "." + chart, interval):
392 for dim in self.definitions[chart]['lines']:
394 self.set(dim[0], data[dim[0]])
404 class UrlService(SimpleService):
405 def __init__(self, configuration=None, name=None):
409 SimpleService.__init__(self, configuration=configuration, name=name)
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)
418 def _get_raw_data(self):
420 Get raw data from http request
425 f = urllib2.urlopen(self.url, timeout=self.update_every)
426 except Exception as e:
427 msg.error(self.__module__, str(e))
431 raw = f.read().decode('utf-8')
432 except Exception as e:
433 msg.error(self.__module__, str(e))
440 Format configuration data and try to connect to server
443 if self.name is None or self.name == str(None):
445 self.chart_name += "_" + self.name
447 self.name = str(self.name)
449 self.url = str(self.configuration['url'])
450 except (KeyError, TypeError):
453 self.user = str(self.configuration['user'])
454 except (KeyError, TypeError):
457 self.password = str(self.configuration['password'])
458 except (KeyError, TypeError):
461 if self.user is not None and self.password is not None:
464 if self._get_data() is not None:
470 class SocketService(SimpleService):
471 def __init__(self, configuration=None, name=None):
472 self.host = "localhost"
475 self.unix_socket = None
477 SimpleService.__init__(self, configuration=configuration, name=name)
479 def _get_raw_data(self):
481 Get raw data with low-level "socket" module.
484 if self.sock is None:
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))
492 sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
493 sock.settimeout(self.update_every)
494 sock.connect(self.unix_socket)
496 except Exception as e:
501 if self.request != "".encode():
503 sock.send(self.request)
516 buf = sock.recv(1024)
530 def _parse_config(self):
532 Parse configuration data
535 if self.name is not None or self.name != str(None):
538 self.name = str(self.name)
540 self.unix_socket = str(self.configuration['socket'])
541 except (KeyError, TypeError):
542 self.error("No unix socket specified. Trying TCP/IP socket.")
544 self.host = str(self.configuration['host'])
545 except (KeyError, TypeError):
546 self.error("No host specified. Using: '" + self.host + "'")
548 self.port = int(self.configuration['port'])
549 except (KeyError, TypeError):
550 self.error("No port specified. Using: '" + str(self.port) + "'")
552 self.request = str(self.configuration['request'])
553 except (KeyError, TypeError):
554 self.error("No request specified. Using: '" + str(self.request) + "'")
555 self.request = self.request.encode()
558 class LogService(SimpleService):
559 def __init__(self, configuration=None, name=None):
561 self._last_position = 0
562 # self._log_reader = None
563 SimpleService.__init__(self, configuration=configuration, name=name)
564 self.retries = 100000 # basically always retry
566 def _get_raw_data(self):
568 Get log lines since last poll
573 if os.path.getsize(self.log_path) < self._last_position:
574 self._last_position = 0
575 elif os.path.getsize(self.log_path) == self._last_position:
577 with open(self.log_path, "r") as fp:
578 fp.seek(self._last_position)
579 for i, line in enumerate(fp):
581 self._last_position = fp.tell()
582 except Exception as e:
583 self.error(self.__module__, str(e))
591 Parse basic configuration and check if log file exists
594 if self.name is not None or self.name != str(None):
597 self.name = str(self.name)
599 self.log_path = str(self.configuration['path'])
600 except (KeyError, TypeError):
601 self.error("No path to log specified. Using: '" + self.log_path + "'")
603 if os.access(self.log_path, os.R_OK):
606 self.error("Cannot access file: '" + self.log_path + "'")
610 status = SimpleService.create(self)
611 self._last_position = 0
615 class ExecutableService(SimpleService):
616 command_whitelist = ['exim', 'postqueue']
617 bad_substrings = ('&', '|', ';', '>', '<')
619 def __init__(self, configuration=None, name=None):
621 SimpleService.__init__(self, configuration=configuration, name=name)
623 def _get_raw_data(self):
625 Get raw data from executed command
629 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
630 except Exception as e:
631 self.error(self.__module__, str(e))
634 for line in p.stdout.readlines():
635 data.append(str(line.decode()))
641 Parse basic configuration, check if command is whitelisted and is returning values
644 if self.name is not None or self.name != str(None):
647 self.name = str(self.name)
649 # self.command = str(self.configuration['path'])
650 # except (KeyError, TypeError):
651 # self.error("No command specified. Using: '" + self.command + "'")
652 self.command = self.command.split(' ')
653 if self.command[0] not in self.command_whitelist:
654 self.error("Command is not whitelisted.")
657 for arg in self.command[1:]:
658 if any(st in arg for st in self.bad_substrings):
659 self.error("Bad command argument:" + " ".join(self.command[1:]))
661 # test command and search for it in /usr/sbin or /sbin when failed
662 base = self.command[0]
663 if self._get_raw_data() is None:
664 for prefix in ['/sbin/', '/usr/sbin/']:
665 self.command[0] = prefix + base
666 if os.path.isfile(self.command[0]):
668 #if self._get_raw_data() is not None:
671 if self._get_data() is None or len(self._get_data()) == 0: