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 self.__chart_set = False
45 if configuration is None:
46 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
49 self._extract_base_config(configuration)
51 self.create_timetable()
53 def _extract_base_config(self, config):
55 Get basic parameters to run service
57 config = {'update_every':1,
63 self.override_name = config.pop('name')
66 self.update_every = int(config.pop('update_every'))
67 self.priority = int(config.pop('priority'))
68 self.retries = int(config.pop('retries'))
69 self.retries_left = self.retries
70 self.configuration = config
72 def create_timetable(self, freq=None):
74 Create service timetable.
77 timetable = {'last': 1466370091.3767564,
83 freq = self.update_every
85 self.timetable = {'last': now,
86 'next': now - (now % freq) + freq,
91 Executes self.update(interval) and draws run time chart.
92 Return value presents exit status of update()
96 # check if it is time to execute job update() function
97 if self.timetable['next'] > t_start:
98 #msg.debug(self.chart_name + " will be run in " +
99 # str(int((self.timetable['next'] - t_start) * 1000)) + " ms")
100 msg.debug(self.chart_name, "will be run in", str(int((self.timetable['next'] - t_start) * 1000)), "ms")
103 since_last = int((t_start - self.timetable['last']) * 1000000)
104 #msg.debug(self.chart_name +
105 # " ready to run, after " + str(int((t_start - self.timetable['last']) * 1000)) +
106 # " ms (update_every: " + str(self.timetable['freq'] * 1000) +
107 # " ms, latency: " + str(int((t_start - self.timetable['next']) * 1000)) + " ms)")
108 msg.debug(self.chart_name,
109 "ready to run, after", str(int((t_start - self.timetable['last']) * 1000)),
110 "ms (update_every:", str(self.timetable['freq'] * 1000),
111 "ms, latency:", str(int((t_start - self.timetable['next']) * 1000)), "ms")
112 if not self.update(since_last):
113 self.error("update function failed.")
116 self.timetable['next'] = t_end - (t_end % self.timetable['freq']) + self.timetable['freq']
117 # draw performance graph
118 run_time = str(int((t_end - t_start) * 1000))
119 #run_time_chart = "BEGIN netdata.plugin_pythond_" + self.chart_name + " " + str(since_last) + '\n'
120 #run_time_chart += "SET run_time = " + run_time + '\n'
121 #run_time_chart += "END\n"
122 #sys.stdout.write(run_time_chart)
123 sys.stdout.write("BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" % \
124 (self.chart_name, str(since_last), run_time))
126 #msg.debug(self.chart_name + " updated in " + str(run_time) + " ms")
127 msg.debug(self.chart_name, "updated in", str(run_time), "ms")
128 self.timetable['last'] = t_start
133 Runs job in thread. Handles retries.
134 Exits when job failed or timed out.
137 self.timetable['last'] = time.time()
140 status = self._run_once()
141 except Exception as e:
142 msg.error("Something wrong: ", str(e))
145 time.sleep(self.timetable['next'] - time.time())
146 self.retries_left = self.retries
148 self.retries_left -= 1
149 if self.retries_left <= 0:
150 msg.error("no more retries. Exiting")
153 time.sleep(self.timetable['freq'])
158 append = params.append
163 if type(p) is not str:
170 def _line(self, instruction, *params):
172 Converts *params to string and joins them with one space between every one.
173 :param params: str/int/float
175 #self._data_stream += instruction
176 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
178 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
180 # self.error(str(" ".join(tmp)))
190 # self._data_stream += " " + p
191 #self._data_stream += "\n"
193 def chart(self, type_id, name="", title="", units="", family="",
194 category="", charttype="line", priority="", update_every=""):
203 :param charttype: str
204 :param priority: int/str
205 :param update_every: int/str
207 self._charts.append(type_id)
208 #self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
210 p = self._format(type_id, name, title, units, family, category, charttype, priority, update_every)
211 self._line("CHART", *p)
213 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
215 Defines a new dimension for the chart
218 :param algorithm: str
219 :param multiplier: int/str
220 :param divisor: int/str
221 :param hidden: boolean
227 self.error("malformed dimension: multiplier is not a number:", multiplier)
232 self.error("malformed dimension: divisor is not a number:", divisor)
236 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
237 algorithm = "absolute"
239 self._dimensions.append(str(id))
241 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
242 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
244 p = self._format(id, name, algorithm, multiplier, divisor)
245 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
247 self._line("DIMENSION", *p)
249 def begin(self, type_id, microseconds=0):
253 :param microseconds: int
256 if type_id not in self._charts:
257 self.error("wrong chart type_id:", type_id)
262 self.error("malformed begin statement: microseconds are not a number:", microseconds)
265 self._line("BEGIN", type_id, str(microseconds))
268 def set(self, id, value):
270 Set value to dimension
272 :param value: int/float
275 if id not in self._dimensions:
276 self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
279 value = str(int(value))
281 self.error("cannot set non-numeric value:", value)
283 self._line("SET", id, "=", str(value))
284 self.__chart_set = True
290 self.__chart_set = False
292 pos = self._data_stream.rfind("BEGIN")
293 self._data_stream = self._data_stream[:pos]
297 Upload new data to netdata
299 print(self._data_stream)
300 self._data_stream = ""
302 def error(self, *params):
304 Show error message on stderr
306 msg.error(self.chart_name, *params)
308 def debug(self, *params):
310 Show debug message on stderr
312 msg.debug(self.chart_name, *params)
314 def info(self, *params):
316 Show information message on stderr
318 msg.info(self.chart_name, *params)
325 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
333 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
336 def update(self, interval):
342 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
346 class SimpleService(BaseService):
347 def __init__(self, configuration=None, name=None):
349 self.definitions = {}
350 BaseService.__init__(self, configuration=configuration, name=name)
370 data = self._get_data()
375 for name in self.order:
376 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
377 self.chart(self.chart_name + "." + name, *options)
378 # check if server has this datapoint
379 for line in self.definitions[name]['lines']:
381 self.dimension(*line)
387 def update(self, interval):
393 data = self._get_data()
395 self.debug("_get_data() returned no data")
399 for chart in self.order:
400 if self.begin(self.chart_name + "." + chart, interval):
402 for dim in self.definitions[chart]['lines']:
404 self.set(dim[0], data[dim[0]])
411 self.error("no charts to update")
416 class UrlService(SimpleService):
417 def __init__(self, configuration=None, name=None):
421 SimpleService.__init__(self, configuration=configuration, name=name)
423 def __add_auth(self):
424 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
425 passman.add_password(None, self.url, self.user, self.password)
426 authhandler = urllib2.HTTPBasicAuthHandler(passman)
427 opener = urllib2.build_opener(authhandler)
428 urllib2.install_opener(opener)
430 def _get_raw_data(self):
432 Get raw data from http request
437 f = urllib2.urlopen(self.url, timeout=self.update_every)
438 except Exception as e:
443 raw = f.read().decode('utf-8')
444 except Exception as e:
452 Format configuration data and try to connect to server
455 if self.name is None or self.name == str(None):
457 self.chart_name += "_" + self.name
459 self.name = str(self.name)
461 self.url = str(self.configuration['url'])
462 except (KeyError, TypeError):
465 self.user = str(self.configuration['user'])
466 except (KeyError, TypeError):
469 self.password = str(self.configuration['pass'])
470 except (KeyError, TypeError):
473 if self.user is not None and self.password is not None:
476 if self._get_data() is not None:
482 class SocketService(SimpleService):
483 def __init__(self, configuration=None, name=None):
485 self._keep_alive = False
486 self.host = "localhost"
488 self.unix_socket = None
490 self.__socket_config = None
491 SimpleService.__init__(self, configuration=configuration, name=name)
495 Recreate socket and connect to it since sockets cannot be reused after closing
496 Available configurations are IPv6, IPv4 or UNIX socket
500 if self.unix_socket is None:
501 if self.__socket_config is None:
502 # establish ipv6 or ipv4 connection.
503 for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
505 af, socktype, proto, canonname, sa = res
506 self._sock = socket.socket(af, socktype, proto)
507 except socket.error as msg:
511 self._sock.connect(sa)
512 except socket.error as msg:
515 self.__socket_config = res
518 # connect to socket with previously established configuration
520 af, socktype, proto, canonname, sa = self.__socket_config
521 self._sock = socket.socket(af, socktype, proto)
522 self._sock.connect(sa)
523 except socket.error as msg:
526 # connect to unix socket
527 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
528 self._sock.connect(self.unix_socket)
529 except Exception as e:
531 "Cannot create socket with following configuration: host:", str(self.host),
532 "port:", str(self.port),
533 "socket:", str(self.unix_socket))
535 self._sock.setblocking(0)
537 def _disconnect(self):
539 Close socket connection
543 self._sock.shutdown(2) # 0 - read, 1 - write, 2 - all
554 # Send request if it is needed
555 if self.request != "".encode():
557 self._sock.send(self.request)
558 except Exception as e:
561 "used configuration: host:", str(self.host),
562 "port:", str(self.port),
563 "socket:", str(self.unix_socket))
569 Receive data from socket
575 ready_to_read, _, in_error = select.select([self._sock], [], [], 15)
576 except Exception as e:
577 self.debug("SELECT", str(e))
580 if len(ready_to_read) > 0:
581 buf = self._sock.recv(4096)
582 if len(buf) == 0 or buf is None: # handle server disconnect
585 if self._check_raw_data(data):
588 self.error("Socket timed out.")
594 def _get_raw_data(self):
596 Get raw data with low-level "socket" module.
599 if self._sock is None:
602 # Send request if it is needed
606 data = self._receive()
608 if not self._keep_alive:
613 def _check_raw_data(self, data):
615 Check if all data has been gathered from socket
621 def _parse_config(self):
623 Parse configuration data
626 if self.name is None or self.name == str(None):
629 self.name = str(self.name)
631 self.unix_socket = str(self.configuration['socket'])
632 except (KeyError, TypeError):
633 self.debug("No unix socket specified. Trying TCP/IP socket.")
635 self.host = str(self.configuration['host'])
636 except (KeyError, TypeError):
637 self.debug("No host specified. Using: '" + self.host + "'")
639 self.port = int(self.configuration['port'])
640 except (KeyError, TypeError):
641 self.debug("No port specified. Using: '" + str(self.port) + "'")
643 self.request = str(self.configuration['request'])
644 except (KeyError, TypeError):
645 self.debug("No request specified. Using: '" + str(self.request) + "'")
646 self.request = self.request.encode()
649 class LogService(SimpleService):
650 def __init__(self, configuration=None, name=None):
652 self._last_position = 0
653 # self._log_reader = None
654 SimpleService.__init__(self, configuration=configuration, name=name)
655 self.retries = 100000 # basically always retry
657 def _get_raw_data(self):
659 Get log lines since last poll
664 if os.path.getsize(self.log_path) < self._last_position:
665 self._last_position = 0
666 elif os.path.getsize(self.log_path) == self._last_position:
667 self.debug("Log file hasn't changed. No new data.")
669 with open(self.log_path, "r") as fp:
670 fp.seek(self._last_position)
671 for i, line in enumerate(fp):
673 self._last_position = fp.tell()
674 except Exception as e:
680 self.error("No data collected.")
685 Parse basic configuration and check if log file exists
688 if self.name is not None or self.name != str(None):
691 self.name = str(self.name)
693 self.log_path = str(self.configuration['path'])
694 except (KeyError, TypeError):
695 self.error("No path to log specified. Using: '" + self.log_path + "'")
697 if os.access(self.log_path, os.R_OK):
700 self.error("Cannot access file: '" + self.log_path + "'")
704 status = SimpleService.create(self)
705 self._last_position = 0
709 class ExecutableService(SimpleService):
710 #command_whitelist = ['exim', 'postqueue']
711 bad_substrings = ('&', '|', ';', '>', '<')
713 def __init__(self, configuration=None, name=None):
715 SimpleService.__init__(self, configuration=configuration, name=name)
717 def _get_raw_data(self):
719 Get raw data from executed command
723 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
724 except Exception as e:
725 self.error("Executing command", self.command, "resulted in error:", str(e))
728 for line in p.stdout.readlines():
729 data.append(str(line.decode()))
732 self.error("No data collected.")
739 Parse basic configuration, check if command is whitelisted and is returning values
742 if self.name is not None or self.name != str(None):
745 self.name = str(self.name)
747 self.command = str(self.configuration['command'])
748 except (KeyError, TypeError):
749 self.error("No command specified. Using: '" + self.command + "'")
750 self.command = self.command.split(' ')
751 #if self.command[0] not in self.command_whitelist:
752 # self.error("Command is not whitelisted.")
755 for arg in self.command[1:]:
756 if any(st in arg for st in self.bad_substrings):
757 self.error("Bad command argument:" + " ".join(self.command[1:]))
759 # test command and search for it in /usr/sbin or /sbin when failed
760 base = self.command[0].split('/')[-1]
761 if self._get_raw_data() is None:
762 for prefix in ['/sbin/', '/usr/sbin/']:
763 self.command[0] = prefix + base
764 if os.path.isfile(self.command[0]):
766 #if self._get_raw_data() is not None:
769 if self._get_data() is None or len(self._get_data()) == 0:
770 self.error("Command", self.command, "returned no data")