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")
100 since_last = int((t_start - self.timetable['last']) * 1000000)
101 msg.debug(self.chart_name +
102 " ready to run, after " + str(int((t_start - self.timetable['last']) * 1000)) +
103 " ms (update_every: " + str(self.timetable['freq'] * 1000) +
104 " ms, latency: " + str(int((t_start - self.timetable['next']) * 1000)) + " ms)")
105 if not self.update(since_last):
108 self.timetable['next'] = t_end - (t_end % self.timetable['freq']) + self.timetable['freq']
110 # draw performance graph
111 run_time = str(int((t_end - t_start) * 1000))
112 run_time_chart = "BEGIN netdata.plugin_pythond_" + self.chart_name + " " + str(since_last) + '\n'
113 run_time_chart += "SET run_time = " + run_time + '\n'
114 run_time_chart += "END\n"
115 sys.stdout.write(run_time_chart)
116 msg.debug(self.chart_name + " updated in " + str(run_time) + " ms")
117 self.timetable['last'] = t_start
122 Runs job in thread. Handles retries.
123 Exits when job failed or timed out.
126 self.timetable['last'] = time.time()
129 status = self._run_once()
130 except Exception as e:
131 msg.error("Something wrong: " + str(e))
134 time.sleep(self.timetable['next'] - time.time())
135 self.retries_left = self.retries
137 self.retries_left -= 1
138 if self.retries_left <= 0:
139 msg.error("no more retries. Exiting")
142 time.sleep(self.timetable['freq'])
144 def _line(self, instruction, *params):
146 Converts *params to string and joins them with one space between every one.
147 :param params: str/int/float
149 self._data_stream += instruction
159 self._data_stream += " " + p
160 self._data_stream += "\n"
162 def chart(self, type_id, name="", title="", units="", family="",
163 category="", charttype="line", priority="", update_every=""):
172 :param charttype: str
173 :param priority: int/str
174 :param update_every: int/str
176 self._charts.append(type_id)
177 self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
179 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
181 Defines a new dimension for the chart
184 :param algorithm: str
185 :param multiplier: int/str
186 :param divisor: int/str
187 :param hidden: boolean
193 self.error("malformed dimension: multiplier is not a number:", multiplier)
198 self.error("malformed dimension: divisor is not a number:", divisor)
202 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
203 algorithm = "absolute"
205 self._dimensions.append(id)
207 self._line("DIMENSION", id, name, algorithm, multiplier, divisor, "hidden")
209 self._line("DIMENSION", id, name, algorithm, multiplier, divisor)
211 def begin(self, type_id, microseconds=0):
215 :param microseconds: int
218 if type_id not in self._charts:
219 self.error("wrong chart type_id:", type_id)
224 self.error("malformed begin statement: microseconds are not a number:", microseconds)
227 self._line("BEGIN", type_id, microseconds)
230 def set(self, id, value):
232 Set value to dimension
234 :param value: int/float
237 if id not in self._dimensions:
238 self.error("wrong dimension id:", id)
241 value = str(int(value))
243 self.error("cannot set non-numeric value:", value)
245 self._line("SET", id, "=", value)
253 Upload new data to netdata
255 print(self._data_stream)
256 self._data_stream = ""
258 def error(self, *params):
260 Show error message on stderr
262 msg.error(self.chart_name, *params)
264 def debug(self, *params):
266 Show debug message on stderr
268 msg.debug(self.chart_name, *params)
270 def info(self, *params):
272 Show information message on stderr
274 msg.info(self.chart_name, *params)
281 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
289 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
292 def update(self, interval):
298 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
302 class SimpleService(BaseService):
303 def __init__(self, configuration=None, name=None):
305 self.definitions = {}
306 BaseService.__init__(self, configuration=configuration, name=name)
326 data = self._get_data()
331 for name in self.order:
332 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
333 self.chart(self.chart_name + "." + name, *options)
334 # check if server has this datapoint
335 for line in self.definitions[name]['lines']:
337 self.dimension(*line)
343 def update(self, interval):
349 data = self._get_data()
354 for chart in self.order:
355 if self.begin(self.chart_name + "." + chart, interval):
357 for dim in self.definitions[chart]['lines']:
359 self.set(dim[0], data[dim[0]])
369 class UrlService(SimpleService):
370 def __init__(self, configuration=None, name=None):
374 SimpleService.__init__(self, configuration=configuration, name=name)
376 def __add_auth(self):
377 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
378 passman.add_password(None, self.url, self.user, self.password)
379 authhandler = urllib2.HTTPBasicAuthHandler(passman)
380 opener = urllib2.build_opener(authhandler)
381 urllib2.install_opener(opener)
383 def _get_raw_data(self):
385 Get raw data from http request
390 f = urllib2.urlopen(self.url, timeout=self.update_every)
391 except Exception as e:
392 msg.error(self.__module__, str(e))
396 raw = f.read().decode('utf-8')
397 except Exception as e:
398 msg.error(self.__module__, str(e))
405 Format configuration data and try to connect to server
408 if self.name is None or self.name == str(None):
410 self.chart_name += "_" + self.name
412 self.name = str(self.name)
414 self.url = str(self.configuration['url'])
415 except (KeyError, TypeError):
418 self.user = str(self.configuration['user'])
419 except (KeyError, TypeError):
422 self.password = str(self.configuration['password'])
423 except (KeyError, TypeError):
426 if self.user is not None and self.password is not None:
429 if self._get_data() is not None:
435 class SocketService(SimpleService):
436 def __init__(self, configuration=None, name=None):
437 self.host = "localhost"
440 self.unix_socket = None
442 SimpleService.__init__(self, configuration=configuration, name=name)
444 def _get_raw_data(self):
446 Get raw data with low-level "socket" module.
449 if self.sock is None:
451 if self.unix_socket is None:
452 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
453 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
454 sock.settimeout(self.update_every)
455 sock.connect((self.host, self.port))
457 sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
458 sock.settimeout(self.update_every)
459 sock.connect(self.unix_socket)
461 except Exception as e:
466 if self.request != "".encode():
468 sock.send(self.request)
478 data = sock.recv(1024)
481 buf = sock.recv(1024)
492 def _parse_config(self):
494 Parse configuration data
497 if self.name is not None or self.name != str(None):
500 self.name = str(self.name)
502 self.unix_socket = int(self.configuration['unix_socket'])
503 except (KeyError, TypeError):
504 self.error("No unix socket specified. Trying TCP/IP socket.")
506 self.host = str(self.configuration['host'])
507 except (KeyError, TypeError):
508 self.error("No host specified. Using: '" + self.host + "'")
510 self.port = int(self.configuration['port'])
511 except (KeyError, TypeError):
512 self.error("No port specified. Using: '" + str(self.port) + "'")
514 self.request = str(self.configuration['request'])
515 except (KeyError, TypeError):
516 self.error("No request specified. Using: '" + str(self.request) + "'")
517 self.request = self.request.encode()
520 class LogService(SimpleService):
521 def __init__(self, configuration=None, name=None):
523 self._last_position = 0
524 # self._log_reader = None
525 SimpleService.__init__(self, configuration=configuration, name=name)
526 self.retries = 100000 # basically always retry
528 def _get_raw_data(self):
530 Get log lines since last poll
535 if os.path.getsize(self.log_path) < self._last_position:
536 self._last_position = 0
537 elif os.path.getsize(self.log_path) == self._last_position:
539 with open(self.log_path, "r") as fp:
540 fp.seek(self._last_position)
541 for i, line in enumerate(fp):
543 self._last_position = fp.tell()
544 except Exception as e:
545 self.error(self.__module__, str(e))
553 Parse basic configuration and check if log file exists
556 if self.name is not None or self.name != str(None):
559 self.name = str(self.name)
561 self.log_path = str(self.configuration['path'])
562 except (KeyError, TypeError):
563 self.error("No path to log specified. Using: '" + self.log_path + "'")
565 if os.access(self.log_path, os.R_OK):
568 self.error("Cannot access file: '" + self.log_path + "'")
572 status = SimpleService.create(self)
573 self._last_position = 0
577 class ExecutableService(SimpleService):
578 command_whitelist = ['exim', 'postqueue']
579 bad_substrings = ('&', '|', ';', '>', '<')
581 def __init__(self, configuration=None, name=None):
583 SimpleService.__init__(self, configuration=configuration, name=name)
585 def _get_raw_data(self):
587 Get raw data from executed command
591 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
592 except Exception as e:
593 self.error(self.__module__, str(e))
596 for line in p.stdout.readlines():
597 data.append(str(line.decode()))
603 Parse basic configuration, check if command is whitelisted and is returning values
606 if self.name is not None or self.name != str(None):
609 self.name = str(self.name)
611 # self.command = str(self.configuration['path'])
612 # except (KeyError, TypeError):
613 # self.error("No command specified. Using: '" + self.command + "'")
614 self.command = self.command.split(' ')
615 if self.command[0] not in self.command_whitelist:
616 self.error("Command is not whitelisted.")
619 for arg in self.command[1:]:
620 if any(st in arg for st in self.bad_substrings):
621 self.error("Bad command argument:" + " ".join(self.command[1:]))
623 # test command and search for it in /usr/sbin or /sbin when failed
624 base = self.command[0]
625 if self._get_raw_data() is None:
626 for prefix in ['/sbin/', '/usr/sbin/']:
627 self.command[0] = prefix + base
628 if os.path.isfile(self.command[0]):
630 #if self._get_raw_data() is not None:
633 if self._get_data() is None or len(self._get_data()) == 0: