1 # -*- coding: utf-8 -*-
2 # Description: netdata python modules framework
3 # Author: Pawel Krupa (paulfantom)
6 # ALL CODE NEEDS TO BE COMPATIBLE WITH Python > 2.7 and Python > 3.1
7 # Follow PEP8 as much as it is possible
8 # "check" and "create" CANNOT be blocking.
9 # "update" CAN be blocking
10 # "update" function needs to be fast, so follow:
11 # https://wiki.python.org/moin/PythonSpeed/PerformanceTips
13 # - use local variables wherever it is possible
14 # - avoid dots in expressions that are executed many times
15 # - use "join()" instead of "+"
16 # - use "import" only at the beginning
18 # using ".encode()" in one thread can block other threads as well (only in python2)
26 import urllib.request as urllib2
30 from subprocess import Popen, PIPE
37 PATH = os.getenv('PATH').split(':')
38 except AttributeError:
39 PATH = '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'.split(':')
42 # class BaseService(threading.Thread):
43 class SimpleService(threading.Thread):
45 Prototype of Service class.
46 Implemented basic functionality to run jobs by `python.d.plugin`
48 def __init__(self, configuration=None, name=None):
50 This needs to be initialized in child classes
51 :param configuration: dict
54 threading.Thread.__init__(self)
55 self._data_stream = ""
59 self.priority = 140000
62 self.override_name = None
66 self.__chart_set = False
67 self.__first_run = True
70 if configuration is None:
71 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
74 self._extract_base_config(configuration)
76 self.create_timetable()
78 # --- BASIC SERVICE CONFIGURATION ---
80 def _extract_base_config(self, config):
82 Get basic parameters to run service
84 config = {'update_every':1,
91 self.override_name = pop('name')
94 self.update_every = int(pop('update_every'))
95 self.priority = int(pop('priority'))
96 self.retries = int(pop('retries'))
97 self.retries_left = self.retries
98 self.configuration = config
100 def create_timetable(self, freq=None):
102 Create service timetable.
105 timetable = {'last': 1466370091.3767564,
111 freq = self.update_every
113 self.timetable = {'last': now,
114 'next': now - (now % freq) + freq,
117 # --- THREAD CONFIGURATION ---
121 Executes self.update(interval) and draws run time chart.
122 Return value presents exit status of update()
125 t_start = float(time.time())
126 chart_name = self.chart_name
128 since_last = int((t_start - self.timetable['last']) * 1000000)
132 if not self.update(since_last):
133 self.error("update function failed.")
136 # draw performance graph
137 run_time = int((time.time() - t_start) * 1000)
138 print("BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" %
139 (self.chart_name, str(since_last), str(run_time)))
141 self.debug(chart_name, "updated in", str(run_time), "ms")
142 self.timetable['last'] = t_start
143 self.__first_run = False
148 Runs job in thread. Handles retries.
149 Exits when job failed or timed out.
152 step = float(self.timetable['freq'])
154 self.timetable['last'] = float(time.time() - step)
155 self.debug("starting data collection - update frequency:", str(step), " retries allowed:", str(self.retries))
156 while True: # run forever, unless something is wrong
157 now = float(time.time())
158 next = self.timetable['next'] = now - (now % step) + step + penalty
160 # it is important to do this in a loop
161 # sleep() is interruptable
163 self.debug("sleeping for", str(next - now), "secs to reach frequency of", str(step), "secs, now:", str(now), " next:", str(next), " penalty:", str(penalty))
164 time.sleep(next - now)
165 now = float(time.time())
169 status = self._run_once()
170 except Exception as e:
175 self.retries_left = self.retries
179 self.retries_left -= 1
180 if self.retries_left <= 0:
182 penalty = float(self.retries * step) / 2
189 self.retries_left = self.retries
190 self.alert("failed to collect data for " + str(self.retries) + " times - increasing penalty to " + str(penalty) + " sec and trying again")
193 self.error("failed to collect data - " + str(self.retries_left) + " retries left - penalty: " + str(penalty) + " sec")
200 Escape and convert passed arguments.
201 :param args: anything
205 append = params.append
210 if type(p) is not str:
217 def _line(self, instruction, *params):
219 Converts *params to string and joins them with one space between every one.
220 Result is appended to self._data_stream
221 :param params: str/int/float
223 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
224 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
226 def chart(self, type_id, name="", title="", units="", family="",
227 category="", chart_type="line", priority="", update_every=""):
236 :param chart_type: str
237 :param priority: int/str
238 :param update_every: int/str
240 self._charts.append(type_id)
242 p = self._format(type_id, name, title, units, family, category, chart_type, priority, update_every)
243 self._line("CHART", *p)
245 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
247 Defines a new dimension for the chart
250 :param algorithm: str
251 :param multiplier: int/str
252 :param divisor: int/str
253 :param hidden: boolean
259 self.error("malformed dimension: multiplier is not a number:", multiplier)
264 self.error("malformed dimension: divisor is not a number:", divisor)
268 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
269 algorithm = "absolute"
271 self._dimensions.append(str(id))
273 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
275 p = self._format(id, name, algorithm, multiplier, divisor)
277 self._line("DIMENSION", *p)
279 def begin(self, type_id, microseconds=0):
283 :param microseconds: int
286 if type_id not in self._charts:
287 self.error("wrong chart type_id:", type_id)
292 self.error("malformed begin statement: microseconds are not a number:", microseconds)
295 self._line("BEGIN", type_id, str(microseconds))
298 def set(self, id, value):
300 Set value to dimension
302 :param value: int/float
305 if id not in self._dimensions:
306 self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
309 value = str(int(value))
311 self.error("cannot set non-numeric value:", str(value))
313 self._line("SET", id, "=", str(value))
314 self.__chart_set = True
320 self.__chart_set = False
322 pos = self._data_stream.rfind("BEGIN")
323 self._data_stream = self._data_stream[:pos]
327 Upload new data to netdata.
330 print(self._data_stream)
331 except Exception as e:
332 msg.fatal('cannot send data to netdata:', str(e))
333 self._data_stream = ""
335 # --- ERROR HANDLING ---
337 def error(self, *params):
339 Show error message on stderr
341 msg.error(self.chart_name, *params)
343 def alert(self, *params):
345 Show error message on stderr
347 msg.alert(self.chart_name, *params)
349 def debug(self, *params):
351 Show debug message on stderr
353 msg.debug(self.chart_name, *params)
355 def info(self, *params):
357 Show information message on stderr
359 msg.info(self.chart_name, *params)
361 # --- MAIN METHODS ---
375 self.debug("Module", str(self.__module__), "doesn't implement check() function. Using default.")
376 data = self._get_data()
379 self.debug("failed to receive data during check().")
383 self.debug("empty data during check().")
386 self.debug("successfully received data during check(): '" + str(data) + "'")
394 data = self._get_data()
396 self.debug("failed to receive data during create().")
400 for name in self.order:
401 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
402 self.chart(self.chart_name + "." + name, *options)
403 # check if server has this datapoint
404 for line in self.definitions[name]['lines']:
406 self.dimension(*line)
412 def update(self, interval):
418 data = self._get_data()
420 self.debug("failed to receive data during update().")
424 for chart in self.order:
425 if self.begin(self.chart_name + "." + chart, interval):
427 for dim in self.definitions[chart]['lines']:
429 self.set(dim[0], data[dim[0]])
436 self.error("no charts to update")
440 def find_binary(self, binary):
442 if isinstance(binary, str):
443 binary = os.path.basename(binary)
444 return next(('/'.join([p, binary]) for p in PATH
445 if os.path.isfile('/'.join([p, binary]))
446 and os.access('/'.join([p, binary]), os.X_OK)))
449 except StopIteration:
453 class UrlService(SimpleService):
454 # TODO add support for https connections
455 def __init__(self, configuration=None, name=None):
460 SimpleService.__init__(self, configuration=configuration, name=name)
462 def __add_openers(self):
463 # TODO add error handling
466 ctx = ssl.create_default_context()
467 ctx.check_hostname = False
468 ctx.verify_mode = ssl.CERT_NONE
469 self.opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))
470 except Exception as error:
471 self.error(str(error))
472 self.opener = urllib2.build_opener()
474 self.opener = urllib2.build_opener()
477 # TODO currently self.proxies isn't parsed from configuration file
478 # if len(self.proxies) > 0:
479 # for proxy in self.proxies:
482 # if "user" in proxy and "pass" in proxy:
483 # if url.lower().startswith('https://'):
484 # url = 'https://' + proxy['user'] + ':' + proxy['pass'] + '@' + url[8:]
486 # url = 'http://' + proxy['user'] + ':' + proxy['pass'] + '@' + url[7:]
487 # # FIXME move proxy auth to sth like this:
488 # # passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
489 # # passman.add_password(None, url, proxy['user'], proxy['password'])
490 # # opener.add_handler(urllib2.HTTPBasicAuthHandler(passman))
492 # if url.lower().startswith('https://'):
493 # opener.add_handler(urllib2.ProxyHandler({'https': url}))
495 # opener.add_handler(urllib2.ProxyHandler({'https': url}))
498 if self.user is not None and self.password is not None:
499 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
500 passman.add_password(None, self.url, self.user, self.password)
501 self.opener.add_handler(urllib2.HTTPBasicAuthHandler(passman))
502 self.debug("Enabling HTTP basic auth")
504 #urllib2.install_opener(opener)
506 def _get_raw_data(self):
508 Get raw data from http request
513 f = self.opener.open(self.url, timeout=self.update_every * 2)
514 # f = urllib2.urlopen(self.url, timeout=self.update_every * 2)
515 except Exception as e:
520 raw = f.read().decode('utf-8', 'ignore')
521 except Exception as e:
529 Format configuration data and try to connect to server
532 if self.name is None or self.name == str(None):
534 self.chart_name += "_" + self.name
536 self.name = str(self.name)
538 self.url = str(self.configuration['url'])
539 except (KeyError, TypeError):
542 self.user = str(self.configuration['user'])
543 except (KeyError, TypeError):
546 self.password = str(self.configuration['pass'])
547 except (KeyError, TypeError):
549 self.ss_cert = self.configuration.get('ss_cert')
552 test = self._get_data()
553 if test is None or len(test) == 0:
559 class SocketService(SimpleService):
560 def __init__(self, configuration=None, name=None):
562 self._keep_alive = False
563 self.host = "localhost"
565 self.unix_socket = None
567 self.__socket_config = None
568 self.__empty_request = "".encode()
569 SimpleService.__init__(self, configuration=configuration, name=name)
571 def _socketerror(self, message=None):
572 if self.unix_socket is not None:
573 self.error("unix socket '" + self.unix_socket + "':", message)
575 if self.__socket_config is not None:
576 af, socktype, proto, canonname, sa = self.__socket_config
577 self.error("socket to '" + str(sa[0]) + "' port " + str(sa[1]) + ":", message)
579 self.error("unknown socket:", message)
581 def _connect2socket(self, res=None):
583 Connect to a socket, passing the result of getaddrinfo()
587 res = self.__socket_config
589 self.error("Cannot create socket to 'None':")
592 af, socktype, proto, canonname, sa = res
594 self.debug("creating socket to '" + str(sa[0]) + "', port " + str(sa[1]))
595 self._sock = socket.socket(af, socktype, proto)
596 except socket.error as e:
597 self.error("Failed to create socket to '" + str(sa[0]) + "', port " + str(sa[1]) + ":", str(e))
599 self.__socket_config = None
603 self.debug("connecting socket to '" + str(sa[0]) + "', port " + str(sa[1]))
604 self._sock.connect(sa)
605 except socket.error as e:
606 self.error("Failed to connect to '" + str(sa[0]) + "', port " + str(sa[1]) + ":", str(e))
608 self.__socket_config = None
611 self.debug("connected to '" + str(sa[0]) + "', port " + str(sa[1]))
612 self.__socket_config = res
615 def _connect2unixsocket(self):
617 Connect to a unix socket, given its filename
620 if self.unix_socket is None:
621 self.error("cannot connect to unix socket 'None'")
625 self.debug("attempting DGRAM unix socket '" + str(self.unix_socket) + "'")
626 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
627 self._sock.connect(self.unix_socket)
628 self.debug("connected DGRAM unix socket '" + str(self.unix_socket) + "'")
630 except socket.error as e:
631 self.debug("Failed to connect DGRAM unix socket '" + str(self.unix_socket) + "':", str(e))
634 self.debug("attempting STREAM unix socket '" + str(self.unix_socket) + "'")
635 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
636 self._sock.connect(self.unix_socket)
637 self.debug("connected STREAM unix socket '" + str(self.unix_socket) + "'")
639 except socket.error as e:
640 self.debug("Failed to connect STREAM unix socket '" + str(self.unix_socket) + "':", str(e))
641 self.error("Failed to connect to unix socket '" + str(self.unix_socket) + "':", str(e))
647 Recreate socket and connect to it since sockets cannot be reused after closing
648 Available configurations are IPv6, IPv4 or UNIX socket
652 if self.unix_socket is not None:
653 self._connect2unixsocket()
656 if self.__socket_config is not None:
657 self._connect2socket()
659 for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
660 if self._connect2socket(res): break
662 except Exception as e:
664 self.__socket_config = None
666 if self._sock is not None:
667 self._sock.setblocking(0)
668 self._sock.settimeout(5)
669 self.debug("set socket timeout to: " + str(self._sock.gettimeout()))
671 def _disconnect(self):
673 Close socket connection
676 if self._sock is not None:
678 self.debug("closing socket")
679 self._sock.shutdown(2) # 0 - read, 1 - write, 2 - all
690 # Send request if it is needed
691 if self.request != self.__empty_request:
693 self.debug("sending request:", str(self.request))
694 self._sock.send(self.request)
695 except Exception as e:
696 self._socketerror("error sending request:" + str(e))
703 Receive data from socket
708 self.debug("receiving response")
710 buf = self._sock.recv(4096)
711 except Exception as e:
712 self._socketerror("failed to receive response:" + str(e))
716 if buf is None or len(buf) == 0: # handle server disconnect
718 self._socketerror("unexpectedly disconnected")
720 self.debug("server closed the connection")
724 self.debug("received data:", str(buf))
725 data += buf.decode('utf-8', 'ignore')
726 if self._check_raw_data(data):
729 self.debug("final response:", str(data))
732 def _get_raw_data(self):
734 Get raw data with low-level "socket" module.
737 if self._sock is None:
739 if self._sock is None:
742 # Send request if it is needed
746 data = self._receive()
748 if not self._keep_alive:
753 def _check_raw_data(self, data):
755 Check if all data has been gathered from socket
761 def _parse_config(self):
763 Parse configuration data
766 if self.name is None or self.name == str(None):
769 self.name = str(self.name)
772 self.unix_socket = str(self.configuration['socket'])
773 except (KeyError, TypeError):
774 self.debug("No unix socket specified. Trying TCP/IP socket.")
775 self.unix_socket = None
777 self.host = str(self.configuration['host'])
778 except (KeyError, TypeError):
779 self.debug("No host specified. Using: '" + self.host + "'")
781 self.port = int(self.configuration['port'])
782 except (KeyError, TypeError):
783 self.debug("No port specified. Using: '" + str(self.port) + "'")
786 self.request = str(self.configuration['request'])
787 except (KeyError, TypeError):
788 self.debug("No request specified. Using: '" + str(self.request) + "'")
790 self.request = self.request.encode()
794 return SimpleService.check(self)
797 class LogService(SimpleService):
798 def __init__(self, configuration=None, name=None):
800 self._last_position = 0
801 # self._log_reader = None
802 SimpleService.__init__(self, configuration=configuration, name=name)
803 self.retries = 100000 # basically always retry
805 def _get_raw_data(self):
807 Get log lines since last poll
812 if os.path.getsize(self.log_path) < self._last_position:
813 self._last_position = 0 # read from beginning if file has shrunk
814 elif os.path.getsize(self.log_path) == self._last_position:
815 self.debug("Log file hasn't changed. No new data.")
816 return [] # return empty list if nothing has changed
817 with open(self.log_path, "r") as fp:
818 fp.seek(self._last_position)
819 for i, line in enumerate(fp):
821 self._last_position = fp.tell()
822 except Exception as e:
828 self.error("No data collected.")
833 Parse basic configuration and check if log file exists
836 if self.name is not None or self.name != str(None):
839 self.name = str(self.name)
841 self.log_path = str(self.configuration['path'])
842 except (KeyError, TypeError):
843 self.info("No path to log specified. Using: '" + self.log_path + "'")
845 if os.access(self.log_path, os.R_OK):
848 self.error("Cannot access file: '" + self.log_path + "'")
852 # set cursor at last byte of log file
853 self._last_position = os.path.getsize(self.log_path)
854 status = SimpleService.create(self)
855 # self._last_position = 0
859 class ExecutableService(SimpleService):
860 bad_substrings = ('&', '|', ';', '>', '<')
862 def __init__(self, configuration=None, name=None):
864 SimpleService.__init__(self, configuration=configuration, name=name)
866 def _get_raw_data(self):
868 Get raw data from executed command
872 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
873 except Exception as e:
874 self.error("Executing command", self.command, "resulted in error:", str(e))
877 for line in p.stdout.readlines():
878 data.append(str(line.decode()))
881 self.error("No data collected.")
888 Parse basic configuration, check if command is whitelisted and is returning values
891 if self.name is not None or self.name != str(None):
894 self.name = str(self.name)
896 self.command = str(self.configuration['command'])
897 except (KeyError, TypeError):
898 self.info("No command specified. Using: '" + self.command + "'")
899 # Splitting self.command on every space so subprocess.Popen reads it properly
900 self.command = self.command.split(' ')
902 for arg in self.command[1:]:
903 if any(st in arg for st in self.bad_substrings):
904 self.error("Bad command argument:" + " ".join(self.command[1:]))
907 # test command and search for it in /usr/sbin or /sbin when failed
908 base = self.command[0].split('/')[-1]
909 if self._get_raw_data() is None:
910 for prefix in ['/sbin/', '/usr/sbin/']:
911 self.command[0] = prefix + base
912 if os.path.isfile(self.command[0]):
915 if self._get_data() is None or len(self._get_data()) == 0:
916 self.error("Command", self.command, "returned no data")