1 # -*- coding: utf-8 -*-
2 # Description: prototypes for netdata python.d modules
3 # Author: Pawel Krupa (paulfantom)
11 import urllib.request as urllib2
15 from subprocess import Popen, PIPE
21 class BaseService(threading.Thread):
23 Prototype of Service class.
24 Implemented basic functionality to run jobs by `python.d.plugin`
26 def __init__(self, configuration=None, name=None):
28 This needs to be initialized in child classes
29 :param configuration: dict
32 threading.Thread.__init__(self)
33 self._data_stream = ""
37 self.priority = 140000
40 self.override_name = None
44 if configuration is None:
45 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
48 self._extract_base_config(configuration)
50 self.create_timetable()
52 def _extract_base_config(self, config):
54 Get basic parameters to run service
56 config = {'update_every':1,
62 self.override_name = config.pop('name')
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
71 def create_timetable(self, freq=None):
73 Create service timetable.
76 timetable = {'last': 1466370091.3767564,
82 freq = self.update_every
84 self.timetable = {'last': now,
85 'next': now - (now % freq) + freq,
90 Executes self.update(interval) and draws run time chart.
91 Return value presents exit status of update()
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")
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):
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))
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
131 Runs job in thread. Handles retries.
132 Exits when job failed or timed out.
135 self.timetable['last'] = time.time()
138 status = self._run_once()
139 except Exception as e:
140 msg.error("Something wrong: " + str(e))
143 time.sleep(self.timetable['next'] - time.time())
144 self.retries_left = self.retries
146 self.retries_left -= 1
147 if self.retries_left <= 0:
148 msg.error("no more retries. Exiting")
151 time.sleep(self.timetable['freq'])
153 def _format(self, *args):
155 append = params.append
160 if type(p) is not str:
167 def _line(self, instruction, *params):
169 Converts *params to string and joins them with one space between every one.
170 :param params: str/int/float
172 #self._data_stream += instruction
173 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
175 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
177 # self.error(str(" ".join(tmp)))
187 # self._data_stream += " " + p
188 #self._data_stream += "\n"
190 def chart(self, type_id, name="", title="", units="", family="",
191 category="", charttype="line", priority="", update_every=""):
200 :param charttype: str
201 :param priority: int/str
202 :param update_every: int/str
204 self._charts.append(type_id)
205 #self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
207 p = self._format(type_id, name, title, units, family, category, charttype, priority, update_every)
208 self._line("CHART", *p)
212 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
214 Defines a new dimension for the chart
217 :param algorithm: str
218 :param multiplier: int/str
219 :param divisor: int/str
220 :param hidden: boolean
226 self.error("malformed dimension: multiplier is not a number:", multiplier)
231 self.error("malformed dimension: divisor is not a number:", divisor)
235 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
236 algorithm = "absolute"
238 self._dimensions.append(id)
240 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
241 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
243 p = self._format(id, name, algorithm, multiplier, divisor)
244 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
246 self._line("DIMENSION", *p)
248 def begin(self, type_id, microseconds=0):
252 :param microseconds: int
255 if type_id not in self._charts:
256 self.error("wrong chart type_id:", type_id)
261 self.error("malformed begin statement: microseconds are not a number:", microseconds)
264 self._line("BEGIN", type_id, str(microseconds))
267 def set(self, id, value):
269 Set value to dimension
271 :param value: int/float
274 if id not in self._dimensions:
275 self.error("wrong dimension id:", id)
278 value = str(int(value))
280 self.error("cannot set non-numeric value:", value)
282 self._line("SET", id, "=", str(value))
290 Upload new data to netdata
292 print(self._data_stream)
293 self._data_stream = ""
295 def error(self, *params):
297 Show error message on stderr
299 msg.error(self.chart_name, *params)
301 def debug(self, *params):
303 Show debug message on stderr
305 msg.debug(self.chart_name, *params)
307 def info(self, *params):
309 Show information message on stderr
311 msg.info(self.chart_name, *params)
318 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
326 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
329 def update(self, interval):
335 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
339 class SimpleService(BaseService):
340 def __init__(self, configuration=None, name=None):
342 self.definitions = {}
343 BaseService.__init__(self, configuration=configuration, name=name)
363 data = self._get_data()
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']:
374 self.dimension(*line)
380 def update(self, interval):
386 data = self._get_data()
391 for chart in self.order:
392 if self.begin(self.chart_name + "." + chart, interval):
394 for dim in self.definitions[chart]['lines']:
396 self.set(dim[0], data[dim[0]])
406 class UrlService(SimpleService):
407 def __init__(self, configuration=None, name=None):
411 SimpleService.__init__(self, configuration=configuration, name=name)
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)
420 def _get_raw_data(self):
422 Get raw data from http request
427 f = urllib2.urlopen(self.url, timeout=self.update_every)
428 except Exception as e:
429 msg.error(self.__module__, str(e))
433 raw = f.read().decode('utf-8')
434 except Exception as e:
435 msg.error(self.__module__, str(e))
442 Format configuration data and try to connect to server
445 if self.name is None or self.name == str(None):
447 self.chart_name += "_" + self.name
449 self.name = str(self.name)
451 self.url = str(self.configuration['url'])
452 except (KeyError, TypeError):
455 self.user = str(self.configuration['user'])
456 except (KeyError, TypeError):
459 self.password = str(self.configuration['password'])
460 except (KeyError, TypeError):
463 if self.user is not None and self.password is not None:
466 if self._get_data() is not None:
472 class SocketService(SimpleService):
473 def __init__(self, configuration=None, name=None):
474 self.host = "localhost"
477 self.unix_socket = None
479 SimpleService.__init__(self, configuration=configuration, name=name)
481 def _get_raw_data(self):
483 Get raw data with low-level "socket" module.
486 if self.sock is None:
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))
494 sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
495 #sock.settimeout(self.update_every)
496 sock.connect(self.unix_socket)
498 except Exception as e:
503 if self.request != "".encode():
505 sock.send(self.request)
519 buf = sock.recv(1024, 0x40) # get 1024 bytes in NON-BLOCKING mode
533 def _parse_config(self):
535 Parse configuration data
538 if self.name is not None or self.name != str(None):
541 self.name = str(self.name)
543 self.unix_socket = str(self.configuration['socket'])
544 except (KeyError, TypeError):
545 self.error("No unix socket specified. Trying TCP/IP socket.")
547 self.host = str(self.configuration['host'])
548 except (KeyError, TypeError):
549 self.error("No host specified. Using: '" + self.host + "'")
551 self.port = int(self.configuration['port'])
552 except (KeyError, TypeError):
553 self.error("No port specified. Using: '" + str(self.port) + "'")
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()
561 class LogService(SimpleService):
562 def __init__(self, configuration=None, name=None):
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
569 def _get_raw_data(self):
571 Get log lines since last poll
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:
580 with open(self.log_path, "r") as fp:
581 fp.seek(self._last_position)
582 for i, line in enumerate(fp):
584 self._last_position = fp.tell()
585 except Exception as e:
586 self.error(self.__module__, str(e))
594 Parse basic configuration and check if log file exists
597 if self.name is not None or self.name != str(None):
600 self.name = str(self.name)
602 self.log_path = str(self.configuration['path'])
603 except (KeyError, TypeError):
604 self.error("No path to log specified. Using: '" + self.log_path + "'")
606 if os.access(self.log_path, os.R_OK):
609 self.error("Cannot access file: '" + self.log_path + "'")
613 status = SimpleService.create(self)
614 self._last_position = 0
618 class ExecutableService(SimpleService):
619 command_whitelist = ['exim', 'postqueue']
620 bad_substrings = ('&', '|', ';', '>', '<')
622 def __init__(self, configuration=None, name=None):
624 SimpleService.__init__(self, configuration=configuration, name=name)
626 def _get_raw_data(self):
628 Get raw data from executed command
632 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
633 except Exception as e:
634 self.error(self.__module__, str(e))
637 for line in p.stdout.readlines():
638 data.append(str(line.decode()))
644 Parse basic configuration, check if command is whitelisted and is returning values
647 if self.name is not None or self.name != str(None):
650 self.name = str(self.name)
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.")
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:]))
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]):
671 #if self._get_raw_data() is not None:
674 if self._get_data() is None or len(self._get_data()) == 0: