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 self._data_from_check = dict()
71 if configuration is None:
72 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
75 self._extract_base_config(configuration)
77 self.create_timetable()
79 # --- BASIC SERVICE CONFIGURATION ---
81 def _extract_base_config(self, config):
83 Get basic parameters to run service
85 config = {'update_every':1,
92 self.override_name = pop('name')
95 self.update_every = int(pop('update_every'))
96 self.priority = int(pop('priority'))
97 self.retries = int(pop('retries'))
98 self.retries_left = self.retries
99 self.configuration = config
101 def create_timetable(self, freq=None):
103 Create service timetable.
106 timetable = {'last': 1466370091.3767564,
112 freq = self.update_every
114 self.timetable = {'last': now,
115 'next': now - (now % freq) + freq,
118 # --- THREAD CONFIGURATION ---
122 Executes self.update(interval) and draws run time chart.
123 Return value presents exit status of update()
126 t_start = float(time.time())
127 chart_name = self.chart_name
129 since_last = int((t_start - self.timetable['last']) * 1000000)
133 if not self.update(since_last):
134 self.error("update function failed.")
137 # draw performance graph
138 run_time = int((time.time() - t_start) * 1000)
139 print("BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" %
140 (self.chart_name, str(since_last), str(run_time)))
142 self.debug(chart_name, "updated in", str(run_time), "ms")
143 self.timetable['last'] = t_start
144 self.__first_run = False
149 Runs job in thread. Handles retries.
150 Exits when job failed or timed out.
153 step = float(self.timetable['freq'])
155 self.timetable['last'] = float(time.time() - step)
156 self.debug("starting data collection - update frequency:", str(step), " retries allowed:", str(self.retries))
157 while True: # run forever, unless something is wrong
158 now = float(time.time())
159 next = self.timetable['next'] = now - (now % step) + step + penalty
161 # it is important to do this in a loop
162 # sleep() is interruptable
164 self.debug("sleeping for", str(next - now), "secs to reach frequency of", str(step), "secs, now:", str(now), " next:", str(next), " penalty:", str(penalty))
165 time.sleep(next - now)
166 now = float(time.time())
170 status = self._run_once()
171 except Exception as e:
176 self.retries_left = self.retries
180 self.retries_left -= 1
181 if self.retries_left <= 0:
183 penalty = float(self.retries * step) / 2
190 self.retries_left = self.retries
191 self.alert("failed to collect data for " + str(self.retries) + " times - increasing penalty to " + str(penalty) + " sec and trying again")
194 self.error("failed to collect data - " + str(self.retries_left) + " retries left - penalty: " + str(penalty) + " sec")
201 Escape and convert passed arguments.
202 :param args: anything
206 append = params.append
211 if type(p) is not str:
218 def _line(self, instruction, *params):
220 Converts *params to string and joins them with one space between every one.
221 Result is appended to self._data_stream
222 :param params: str/int/float
224 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
225 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
227 def chart(self, type_id, name="", title="", units="", family="",
228 category="", chart_type="line", priority="", update_every=""):
237 :param chart_type: str
238 :param priority: int/str
239 :param update_every: int/str
241 self._charts.append(type_id)
243 p = self._format(type_id, name, title, units, family, category, chart_type, priority, update_every)
244 self._line("CHART", *p)
246 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
248 Defines a new dimension for the chart
251 :param algorithm: str
252 :param multiplier: int/str
253 :param divisor: int/str
254 :param hidden: boolean
260 self.error("malformed dimension: multiplier is not a number:", multiplier)
265 self.error("malformed dimension: divisor is not a number:", divisor)
269 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
270 algorithm = "absolute"
272 self._dimensions.append(str(id))
274 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
276 p = self._format(id, name, algorithm, multiplier, divisor)
278 self._line("DIMENSION", *p)
280 def begin(self, type_id, microseconds=0):
284 :param microseconds: int
287 if type_id not in self._charts:
288 self.error("wrong chart type_id:", type_id)
293 self.error("malformed begin statement: microseconds are not a number:", microseconds)
296 self._line("BEGIN", type_id, str(microseconds))
299 def set(self, id, value):
301 Set value to dimension
303 :param value: int/float
306 if id not in self._dimensions:
307 self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
310 value = str(int(value))
312 self.error("cannot set non-numeric value:", str(value))
314 self._line("SET", id, "=", str(value))
315 self.__chart_set = True
321 self.__chart_set = False
323 pos = self._data_stream.rfind("BEGIN")
324 self._data_stream = self._data_stream[:pos]
328 Upload new data to netdata.
331 print(self._data_stream)
332 except Exception as e:
333 msg.fatal('cannot send data to netdata:', str(e))
334 self._data_stream = ""
336 # --- ERROR HANDLING ---
338 def error(self, *params):
340 Show error message on stderr
342 msg.error(self.chart_name, *params)
344 def alert(self, *params):
346 Show error message on stderr
348 msg.alert(self.chart_name, *params)
350 def debug(self, *params):
352 Show debug message on stderr
354 msg.debug(self.chart_name, *params)
356 def info(self, *params):
358 Show information message on stderr
360 msg.info(self.chart_name, *params)
362 # --- MAIN METHODS ---
376 self.debug("Module", str(self.__module__), "doesn't implement check() function. Using default.")
377 data = self._get_data()
380 self.debug("failed to receive data during check().")
384 self.debug("empty data during check().")
387 self.debug("successfully received data during check(): '" + str(data) + "'")
395 data = self._data_from_check or self._get_data()
397 self.debug("failed to receive data during create().")
401 for name in self.order:
402 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
403 self.chart(self.chart_name + "." + name, *options)
404 # check if server has this datapoint
405 for line in self.definitions[name]['lines']:
407 self.dimension(*line)
413 def update(self, interval):
419 data = self._get_data()
421 self.debug("failed to receive data during update().")
425 for chart in self.order:
426 if self.begin(self.chart_name + "." + chart, interval):
428 for dim in self.definitions[chart]['lines']:
430 self.set(dim[0], data[dim[0]])
437 self.error("no charts to update")
442 def find_binary(binary):
444 if isinstance(binary, str):
445 binary = os.path.basename(binary)
446 return next(('/'.join([p, binary]) for p in PATH
447 if os.path.isfile('/'.join([p, binary]))
448 and os.access('/'.join([p, binary]), os.X_OK)))
451 except StopIteration:
455 class UrlService(SimpleService):
456 # TODO add support for https connections
457 def __init__(self, configuration=None, name=None):
462 SimpleService.__init__(self, configuration=configuration, name=name)
464 def __add_openers(self):
465 # TODO add error handling
468 ctx = ssl.create_default_context()
469 ctx.check_hostname = False
470 ctx.verify_mode = ssl.CERT_NONE
471 self.opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))
472 except Exception as error:
473 self.error(str(error))
474 self.opener = urllib2.build_opener()
476 self.opener = urllib2.build_opener()
479 # TODO currently self.proxies isn't parsed from configuration file
480 # if len(self.proxies) > 0:
481 # for proxy in self.proxies:
484 # if "user" in proxy and "pass" in proxy:
485 # if url.lower().startswith('https://'):
486 # url = 'https://' + proxy['user'] + ':' + proxy['pass'] + '@' + url[8:]
488 # url = 'http://' + proxy['user'] + ':' + proxy['pass'] + '@' + url[7:]
489 # # FIXME move proxy auth to sth like this:
490 # # passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
491 # # passman.add_password(None, url, proxy['user'], proxy['password'])
492 # # opener.add_handler(urllib2.HTTPBasicAuthHandler(passman))
494 # if url.lower().startswith('https://'):
495 # opener.add_handler(urllib2.ProxyHandler({'https': url}))
497 # opener.add_handler(urllib2.ProxyHandler({'https': url}))
500 if self.user is not None and self.password is not None:
501 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
502 passman.add_password(None, self.url, self.user, self.password)
503 self.opener.add_handler(urllib2.HTTPBasicAuthHandler(passman))
504 self.debug("Enabling HTTP basic auth")
506 #urllib2.install_opener(opener)
508 def _get_raw_data(self):
510 Get raw data from http request
515 f = self.opener.open(self.url, timeout=self.update_every * 2)
516 # f = urllib2.urlopen(self.url, timeout=self.update_every * 2)
517 except Exception as e:
522 raw = f.read().decode('utf-8', 'ignore')
523 except Exception as e:
531 Format configuration data and try to connect to server
534 if self.name is None or self.name == str(None):
536 self.chart_name += "_" + self.name
538 self.name = str(self.name)
540 self.url = str(self.configuration['url'])
541 except (KeyError, TypeError):
544 self.user = str(self.configuration['user'])
545 except (KeyError, TypeError):
548 self.password = str(self.configuration['pass'])
549 except (KeyError, TypeError):
551 self.ss_cert = self.configuration.get('ss_cert')
554 test = self._get_data()
555 if test is None or len(test) == 0:
561 class SocketService(SimpleService):
562 def __init__(self, configuration=None, name=None):
564 self._keep_alive = False
565 self.host = "localhost"
567 self.unix_socket = None
569 self.__socket_config = None
570 self.__empty_request = "".encode()
571 SimpleService.__init__(self, configuration=configuration, name=name)
573 def _socketerror(self, message=None):
574 if self.unix_socket is not None:
575 self.error("unix socket '" + self.unix_socket + "':", message)
577 if self.__socket_config is not None:
578 af, socktype, proto, canonname, sa = self.__socket_config
579 self.error("socket to '" + str(sa[0]) + "' port " + str(sa[1]) + ":", message)
581 self.error("unknown socket:", message)
583 def _connect2socket(self, res=None):
585 Connect to a socket, passing the result of getaddrinfo()
589 res = self.__socket_config
591 self.error("Cannot create socket to 'None':")
594 af, socktype, proto, canonname, sa = res
596 self.debug("creating socket to '" + str(sa[0]) + "', port " + str(sa[1]))
597 self._sock = socket.socket(af, socktype, proto)
598 except socket.error as e:
599 self.error("Failed to create socket to '" + str(sa[0]) + "', port " + str(sa[1]) + ":", str(e))
601 self.__socket_config = None
605 self.debug("connecting socket to '" + str(sa[0]) + "', port " + str(sa[1]))
606 self._sock.connect(sa)
607 except socket.error as e:
608 self.error("Failed to connect to '" + str(sa[0]) + "', port " + str(sa[1]) + ":", str(e))
610 self.__socket_config = None
613 self.debug("connected to '" + str(sa[0]) + "', port " + str(sa[1]))
614 self.__socket_config = res
617 def _connect2unixsocket(self):
619 Connect to a unix socket, given its filename
622 if self.unix_socket is None:
623 self.error("cannot connect to unix socket 'None'")
627 self.debug("attempting DGRAM unix socket '" + str(self.unix_socket) + "'")
628 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
629 self._sock.connect(self.unix_socket)
630 self.debug("connected DGRAM unix socket '" + str(self.unix_socket) + "'")
632 except socket.error as e:
633 self.debug("Failed to connect DGRAM unix socket '" + str(self.unix_socket) + "':", str(e))
636 self.debug("attempting STREAM unix socket '" + str(self.unix_socket) + "'")
637 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
638 self._sock.connect(self.unix_socket)
639 self.debug("connected STREAM unix socket '" + str(self.unix_socket) + "'")
641 except socket.error as e:
642 self.debug("Failed to connect STREAM unix socket '" + str(self.unix_socket) + "':", str(e))
643 self.error("Failed to connect to unix socket '" + str(self.unix_socket) + "':", str(e))
649 Recreate socket and connect to it since sockets cannot be reused after closing
650 Available configurations are IPv6, IPv4 or UNIX socket
654 if self.unix_socket is not None:
655 self._connect2unixsocket()
658 if self.__socket_config is not None:
659 self._connect2socket()
661 for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
662 if self._connect2socket(res): break
664 except Exception as e:
666 self.__socket_config = None
668 if self._sock is not None:
669 self._sock.setblocking(0)
670 self._sock.settimeout(5)
671 self.debug("set socket timeout to: " + str(self._sock.gettimeout()))
673 def _disconnect(self):
675 Close socket connection
678 if self._sock is not None:
680 self.debug("closing socket")
681 self._sock.shutdown(2) # 0 - read, 1 - write, 2 - all
692 # Send request if it is needed
693 if self.request != self.__empty_request:
695 self.debug("sending request:", str(self.request))
696 self._sock.send(self.request)
697 except Exception as e:
698 self._socketerror("error sending request:" + str(e))
705 Receive data from socket
710 self.debug("receiving response")
712 buf = self._sock.recv(4096)
713 except Exception as e:
714 self._socketerror("failed to receive response:" + str(e))
718 if buf is None or len(buf) == 0: # handle server disconnect
720 self._socketerror("unexpectedly disconnected")
722 self.debug("server closed the connection")
726 self.debug("received data:", str(buf))
727 data += buf.decode('utf-8', 'ignore')
728 if self._check_raw_data(data):
731 self.debug("final response:", str(data))
734 def _get_raw_data(self):
736 Get raw data with low-level "socket" module.
739 if self._sock is None:
741 if self._sock is None:
744 # Send request if it is needed
748 data = self._receive()
750 if not self._keep_alive:
755 def _check_raw_data(self, data):
757 Check if all data has been gathered from socket
763 def _parse_config(self):
765 Parse configuration data
768 if self.name is None or self.name == str(None):
771 self.name = str(self.name)
774 self.unix_socket = str(self.configuration['socket'])
775 except (KeyError, TypeError):
776 self.debug("No unix socket specified. Trying TCP/IP socket.")
777 self.unix_socket = None
779 self.host = str(self.configuration['host'])
780 except (KeyError, TypeError):
781 self.debug("No host specified. Using: '" + self.host + "'")
783 self.port = int(self.configuration['port'])
784 except (KeyError, TypeError):
785 self.debug("No port specified. Using: '" + str(self.port) + "'")
788 self.request = str(self.configuration['request'])
789 except (KeyError, TypeError):
790 self.debug("No request specified. Using: '" + str(self.request) + "'")
792 self.request = self.request.encode()
796 return SimpleService.check(self)
799 class LogService(SimpleService):
800 def __init__(self, configuration=None, name=None):
802 self._last_position = 0
803 # self._log_reader = None
804 SimpleService.__init__(self, configuration=configuration, name=name)
805 self.retries = 100000 # basically always retry
807 def _get_raw_data(self):
809 Get log lines since last poll
814 if os.path.getsize(self.log_path) < self._last_position:
815 self._last_position = 0 # read from beginning if file has shrunk
816 elif os.path.getsize(self.log_path) == self._last_position:
817 self.debug("Log file hasn't changed. No new data.")
818 return [] # return empty list if nothing has changed
819 with open(self.log_path, "r") as fp:
820 fp.seek(self._last_position)
821 for i, line in enumerate(fp):
823 self._last_position = fp.tell()
824 except Exception as e:
830 self.error("No data collected.")
835 Parse basic configuration and check if log file exists
838 if self.name is not None or self.name != str(None):
841 self.name = str(self.name)
843 self.log_path = str(self.configuration['path'])
844 except (KeyError, TypeError):
845 self.info("No path to log specified. Using: '" + self.log_path + "'")
847 if os.access(self.log_path, os.R_OK):
850 self.error("Cannot access file: '" + self.log_path + "'")
854 # set cursor at last byte of log file
855 self._last_position = os.path.getsize(self.log_path)
856 status = SimpleService.create(self)
857 # self._last_position = 0
861 class ExecutableService(SimpleService):
863 def __init__(self, configuration=None, name=None):
864 SimpleService.__init__(self, configuration=configuration, name=name)
867 def _get_raw_data(self):
869 Get raw data from executed command
873 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
874 except Exception as error:
875 self.error("Executing command", self.command, "resulted in error:", str(error))
878 for line in p.stdout.readlines():
879 data.append(line.decode())
885 Parse basic configuration, check if command is whitelisted and is returning values
888 # Preference: 1. "command" from configuration file 2. "command" from plugin (if specified)
889 if 'command' in self.configuration:
890 self.command = self.configuration['command']
892 # "command" must be: 1.not None 2. type <str>
893 if not (self.command and isinstance(self.command, str)):
894 self.error('Command is not defined or command type is not <str>')
897 # Split "command" into: 1. command <str> 2. options <list>
898 command, opts = self.command.split()[0], self.command.split()[1:]
900 # Check for "bad" symbols in options. No pipes, redirects etc. TODO: what is missing?
901 bad_opts = set(''.join(opts)) & set(['&', '|', ';', '>', '<'])
903 self.error("Bad command argument(s): %s" % bad_opts)
906 # Find absolute path ('echo' => '/bin/echo')
907 if '/' not in command:
908 command = self.find_binary(command)
910 self.error('Can\'t locate "%s" binary in PATH(%s)' % (self.command, PATH))
912 # Check if binary exist and executable
914 if not (os.path.isfile(command) and os.access(command, os.X_OK)):
915 self.error('"%s" is not a file or not executable' % command)
918 self.command = [command] + opts if opts else [command]
921 data = self._get_data()
922 except Exception as error:
923 self.error('_get_data() failed. Command: %s. Error: %s' % (self.command, error))
926 if isinstance(data, dict) and data:
927 # We need this for create() method. No reason to execute get_data() again if result is not empty dict()
928 self._data_from_check = data
931 self.error("Command", str(self.command), "returned no data")