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
36 # class BaseService(threading.Thread):
37 class SimpleService(threading.Thread):
39 Prototype of Service class.
40 Implemented basic functionality to run jobs by `python.d.plugin`
42 def __init__(self, configuration=None, name=None):
44 This needs to be initialized in child classes
45 :param configuration: dict
48 threading.Thread.__init__(self)
49 self._data_stream = ""
53 self.priority = 140000
56 self.override_name = None
60 self.__chart_set = False
61 self.__first_run = True
64 if configuration is None:
65 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
68 self._extract_base_config(configuration)
70 self.create_timetable()
72 # --- BASIC SERVICE CONFIGURATION ---
74 def _extract_base_config(self, config):
76 Get basic parameters to run service
78 config = {'update_every':1,
85 self.override_name = pop('name')
88 self.update_every = int(pop('update_every'))
89 self.priority = int(pop('priority'))
90 self.retries = int(pop('retries'))
91 self.retries_left = self.retries
92 self.configuration = config
94 def create_timetable(self, freq=None):
96 Create service timetable.
99 timetable = {'last': 1466370091.3767564,
105 freq = self.update_every
107 self.timetable = {'last': now,
108 'next': now - (now % freq) + freq,
111 # --- THREAD CONFIGURATION ---
115 Executes self.update(interval) and draws run time chart.
116 Return value presents exit status of update()
119 t_start = float(time.time())
120 chart_name = self.chart_name
122 since_last = int((t_start - self.timetable['last']) * 1000000)
126 if not self.update(since_last):
127 self.error("update function failed.")
130 # draw performance graph
131 run_time = int((time.time() - t_start) * 1000)
132 print("BEGIN netdata.plugin_pythond_%s %s\nSET run_time = %s\nEND\n" %
133 (self.chart_name, str(since_last), str(run_time)))
135 self.debug(chart_name, "updated in", str(run_time), "ms")
136 self.timetable['last'] = t_start
137 self.__first_run = False
142 Runs job in thread. Handles retries.
143 Exits when job failed or timed out.
146 step = float(self.timetable['freq'])
147 self.timetable['last'] = float(time.time() - step)
148 self.debug("starting data collection - update frequency:", str(step), ", retries allowed:", str(self.retries))
149 while True: # run forever, unless something is wrong
150 now = float(time.time())
151 next = self.timetable['next'] = now - (now % step) + step + (step / 3) # add 1/3 into the iteration to sync with netdata
153 # it is important to do this in a loop
154 # sleep() is interruptable
156 self.debug("sleeping for", str(next - now), "secs to reach frequency of", str(step), "secs, now:", str(now), ", next:", str(next))
157 time.sleep(next - now)
158 now = float(time.time())
162 status = self._run_once()
163 except Exception as e:
164 self.alert("internal error - aborting data collection: " + str(e))
169 self.retries_left = self.retries
172 self.retries_left -= 1
173 if self.retries_left <= 0:
174 self.alert("failed to collect data - no more retries allowed - aborting data collection")
177 self.error("failed to collect data. " + str(self.retries_left) + " retries left.")
184 Escape and convert passed arguments.
185 :param args: anything
189 append = params.append
194 if type(p) is not str:
201 def _line(self, instruction, *params):
203 Converts *params to string and joins them with one space between every one.
204 Result is appended to self._data_stream
205 :param params: str/int/float
207 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
208 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
210 def chart(self, type_id, name="", title="", units="", family="",
211 category="", chart_type="line", priority="", update_every=""):
220 :param chart_type: str
221 :param priority: int/str
222 :param update_every: int/str
224 self._charts.append(type_id)
226 p = self._format(type_id, name, title, units, family, category, chart_type, priority, update_every)
227 self._line("CHART", *p)
229 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
231 Defines a new dimension for the chart
234 :param algorithm: str
235 :param multiplier: int/str
236 :param divisor: int/str
237 :param hidden: boolean
243 self.error("malformed dimension: multiplier is not a number:", multiplier)
248 self.error("malformed dimension: divisor is not a number:", divisor)
252 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
253 algorithm = "absolute"
255 self._dimensions.append(str(id))
257 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
259 p = self._format(id, name, algorithm, multiplier, divisor)
261 self._line("DIMENSION", *p)
263 def begin(self, type_id, microseconds=0):
267 :param microseconds: int
270 if type_id not in self._charts:
271 self.error("wrong chart type_id:", type_id)
276 self.error("malformed begin statement: microseconds are not a number:", microseconds)
279 self._line("BEGIN", type_id, str(microseconds))
282 def set(self, id, value):
284 Set value to dimension
286 :param value: int/float
289 if id not in self._dimensions:
290 self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
293 value = str(int(value))
295 self.error("cannot set non-numeric value:", str(value))
297 self._line("SET", id, "=", str(value))
298 self.__chart_set = True
304 self.__chart_set = False
306 pos = self._data_stream.rfind("BEGIN")
307 self._data_stream = self._data_stream[:pos]
311 Upload new data to netdata.
313 print(self._data_stream)
314 self._data_stream = ""
316 # --- ERROR HANDLING ---
318 def error(self, *params):
320 Show error message on stderr
322 msg.error(self.chart_name, *params)
324 def alert(self, *params):
326 Show error message on stderr
328 msg.alert(self.chart_name, *params)
330 def debug(self, *params):
332 Show debug message on stderr
334 msg.debug(self.chart_name, *params)
336 def info(self, *params):
338 Show information message on stderr
340 msg.info(self.chart_name, *params)
342 # --- MAIN METHODS ---
356 self.debug("Module", str(self.__module__), "doesn't implement check() function. Using default.")
357 data = self._get_data()
360 self.debug("failed to receive data during check().")
364 self.debug("empty data during check().")
367 self.debug("successfully received data during check(): '" + str(data) + "'")
375 data = self._get_data()
377 self.debug("failed to receive data during create().")
381 for name in self.order:
382 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
383 self.chart(self.chart_name + "." + name, *options)
384 # check if server has this datapoint
385 for line in self.definitions[name]['lines']:
387 self.dimension(*line)
393 def update(self, interval):
399 data = self._get_data()
401 self.debug("failed to receive data during update().")
405 for chart in self.order:
406 if self.begin(self.chart_name + "." + chart, interval):
408 for dim in self.definitions[chart]['lines']:
410 self.set(dim[0], data[dim[0]])
417 self.error("no charts to update")
422 class UrlService(SimpleService):
423 # TODO add support for https connections
424 def __init__(self, configuration=None, name=None):
429 SimpleService.__init__(self, configuration=configuration, name=name)
431 def __add_openers(self):
432 # TODO add error handling
433 self.opener = urllib2.build_opener()
436 # TODO currently self.proxies isn't parsed from configuration file
437 # if len(self.proxies) > 0:
438 # for proxy in self.proxies:
441 # if "user" in proxy and "pass" in proxy:
442 # if url.lower().startswith('https://'):
443 # url = 'https://' + proxy['user'] + ':' + proxy['pass'] + '@' + url[8:]
445 # url = 'http://' + proxy['user'] + ':' + proxy['pass'] + '@' + url[7:]
446 # # FIXME move proxy auth to sth like this:
447 # # passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
448 # # passman.add_password(None, url, proxy['user'], proxy['password'])
449 # # opener.add_handler(urllib2.HTTPBasicAuthHandler(passman))
451 # if url.lower().startswith('https://'):
452 # opener.add_handler(urllib2.ProxyHandler({'https': url}))
454 # opener.add_handler(urllib2.ProxyHandler({'https': url}))
457 if self.user is not None and self.password is not None:
458 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
459 passman.add_password(None, self.url, self.user, self.password)
460 self.opener.add_handler(urllib2.HTTPBasicAuthHandler(passman))
461 self.debug("Enabling HTTP basic auth")
463 #urllib2.install_opener(opener)
465 def _get_raw_data(self):
467 Get raw data from http request
472 f = self.opener.open(self.url, timeout=self.update_every * 2)
473 # f = urllib2.urlopen(self.url, timeout=self.update_every * 2)
474 except Exception as e:
479 raw = f.read().decode('utf-8')
480 except Exception as e:
488 Format configuration data and try to connect to server
491 if self.name is None or self.name == str(None):
493 self.chart_name += "_" + self.name
495 self.name = str(self.name)
497 self.url = str(self.configuration['url'])
498 except (KeyError, TypeError):
501 self.user = str(self.configuration['user'])
502 except (KeyError, TypeError):
505 self.password = str(self.configuration['pass'])
506 except (KeyError, TypeError):
511 test = self._get_data()
512 if test is None or len(test) == 0:
518 class SocketService(SimpleService):
519 def __init__(self, configuration=None, name=None):
521 self._keep_alive = False
522 self.host = "localhost"
524 self.unix_socket = None
526 self.__socket_config = None
527 self.__empty_request = "".encode()
528 SimpleService.__init__(self, configuration=configuration, name=name)
530 def _socketerror(self, message=None):
531 if self.unix_socket is not None:
532 self.error("unix socket '" + self.unix_socket + "':", message)
534 if self.__socket_config is not None:
535 af, socktype, proto, canonname, sa = self.__socket_config
536 self.error("socket to '" + str(sa[0]) + "' port " + str(sa[1]) + ":", message)
538 self.error("unknown socket:", message)
540 def _connect2socket(self, res=None):
542 Connect to a socket, passing the result of getaddrinfo()
546 res = self.__socket_config
548 self.error("Cannot create socket to 'None':")
551 af, socktype, proto, canonname, sa = res
553 self.debug("creating socket to '" + str(sa[0]) + "', port " + str(sa[1]))
554 self._sock = socket.socket(af, socktype, proto)
555 except socket.error as e:
556 self.error("Failed to create socket to '" + str(sa[0]) + "', port " + str(sa[1]) + ":", str(e))
558 self.__socket_config = None
562 self.debug("connecting socket to '" + str(sa[0]) + "', port " + str(sa[1]))
563 self._sock.connect(sa)
564 except socket.error as e:
565 self.error("Failed to connect to '" + str(sa[0]) + "', port " + str(sa[1]) + ":", str(e))
567 self.__socket_config = None
570 self.debug("connected to '" + str(sa[0]) + "', port " + str(sa[1]))
571 self.__socket_config = res
574 def _connect2unixsocket(self):
576 Connect to a unix socket, given its filename
579 if self.unix_socket is None:
580 self.error("cannot connect to unix socket 'None'")
584 self.debug("attempting DGRAM unix socket '" + str(self.unix_socket) + "'")
585 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
586 self._sock.connect(self.unix_socket)
587 self.debug("connected DGRAM unix socket '" + str(self.unix_socket) + "'")
589 except socket.error as e:
590 self.debug("Failed to connect DGRAM unix socket '" + str(self.unix_socket) + "':", str(e))
593 self.debug("attempting STREAM unix socket '" + str(self.unix_socket) + "'")
594 self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
595 self._sock.connect(self.unix_socket)
596 self.debug("connected STREAM unix socket '" + str(self.unix_socket) + "'")
598 except socket.error as e:
599 self.debug("Failed to connect STREAM unix socket '" + str(self.unix_socket) + "':", str(e))
600 self.error("Failed to connect to unix socket '" + str(self.unix_socket) + "':", str(e))
606 Recreate socket and connect to it since sockets cannot be reused after closing
607 Available configurations are IPv6, IPv4 or UNIX socket
611 if self.unix_socket is not None:
612 self._connect2unixsocket()
615 if self.__socket_config is not None:
616 self._connect2socket()
618 for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
619 if self._connect2socket(res): break
621 except Exception as e:
623 self.__socket_config = None
625 if self._sock is not None:
626 self._sock.setblocking(0)
627 self._sock.settimeout(5)
628 self.debug("set socket timeout to: " + str(self._sock.gettimeout()))
630 def _disconnect(self):
632 Close socket connection
635 if self._sock is not None:
637 self.debug("closing socket")
638 self._sock.shutdown(2) # 0 - read, 1 - write, 2 - all
649 # Send request if it is needed
650 if self.request != self.__empty_request:
652 self.debug("sending request:", str(self.request))
653 self._sock.send(self.request)
654 except Exception as e:
655 self._socketerror("error sending request:" + str(e))
662 Receive data from socket
667 self.debug("receiving response")
669 buf = self._sock.recv(4096)
670 except Exception as e:
671 self._socketerror("failed to receive response:" + str(e))
675 if buf is None or len(buf) == 0: # handle server disconnect
677 self._socketerror("unexpectedly disconnected")
679 self.debug("server closed the connection")
683 self.debug("received data:", str(buf))
684 data += buf.decode(errors='ignore')
685 if self._check_raw_data(data):
688 self.debug("final response:", str(data))
691 def _get_raw_data(self):
693 Get raw data with low-level "socket" module.
696 if self._sock is None:
698 if self._sock is None:
701 # Send request if it is needed
705 data = self._receive()
707 if not self._keep_alive:
712 def _check_raw_data(self, data):
714 Check if all data has been gathered from socket
720 def _parse_config(self):
722 Parse configuration data
725 if self.name is None or self.name == str(None):
728 self.name = str(self.name)
731 self.unix_socket = str(self.configuration['socket'])
732 except (KeyError, TypeError):
733 self.debug("No unix socket specified. Trying TCP/IP socket.")
734 self.unix_socket = None
736 self.host = str(self.configuration['host'])
737 except (KeyError, TypeError):
738 self.debug("No host specified. Using: '" + self.host + "'")
740 self.port = int(self.configuration['port'])
741 except (KeyError, TypeError):
742 self.debug("No port specified. Using: '" + str(self.port) + "'")
745 self.request = str(self.configuration['request'])
746 except (KeyError, TypeError):
747 self.debug("No request specified. Using: '" + str(self.request) + "'")
749 self.request = self.request.encode()
753 return SimpleService.check(self)
756 class LogService(SimpleService):
757 def __init__(self, configuration=None, name=None):
759 self._last_position = 0
760 # self._log_reader = None
761 SimpleService.__init__(self, configuration=configuration, name=name)
762 self.retries = 100000 # basically always retry
764 def _get_raw_data(self):
766 Get log lines since last poll
771 if os.path.getsize(self.log_path) < self._last_position:
772 self._last_position = 0 # read from beginning if file has shrunk
773 elif os.path.getsize(self.log_path) == self._last_position:
774 self.debug("Log file hasn't changed. No new data.")
775 return [] # return empty list if nothing has changed
776 with open(self.log_path, "r") as fp:
777 fp.seek(self._last_position)
778 for i, line in enumerate(fp):
780 self._last_position = fp.tell()
781 except Exception as e:
787 self.error("No data collected.")
792 Parse basic configuration and check if log file exists
795 if self.name is not None or self.name != str(None):
798 self.name = str(self.name)
800 self.log_path = str(self.configuration['path'])
801 except (KeyError, TypeError):
802 self.info("No path to log specified. Using: '" + self.log_path + "'")
804 if os.access(self.log_path, os.R_OK):
807 self.error("Cannot access file: '" + self.log_path + "'")
811 # set cursor at last byte of log file
812 self._last_position = os.path.getsize(self.log_path)
813 status = SimpleService.create(self)
814 # self._last_position = 0
818 class ExecutableService(SimpleService):
819 bad_substrings = ('&', '|', ';', '>', '<')
821 def __init__(self, configuration=None, name=None):
823 SimpleService.__init__(self, configuration=configuration, name=name)
825 def _get_raw_data(self):
827 Get raw data from executed command
831 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
832 except Exception as e:
833 self.error("Executing command", self.command, "resulted in error:", str(e))
836 for line in p.stdout.readlines():
837 data.append(str(line.decode()))
840 self.error("No data collected.")
847 Parse basic configuration, check if command is whitelisted and is returning values
850 if self.name is not None or self.name != str(None):
853 self.name = str(self.name)
855 self.command = str(self.configuration['command'])
856 except (KeyError, TypeError):
857 self.info("No command specified. Using: '" + self.command + "'")
858 command = self.command.split(' ')
860 for arg in command[1:]:
861 if any(st in arg for st in self.bad_substrings):
862 self.error("Bad command argument:" + " ".join(self.command[1:]))
865 # test command and search for it in /usr/sbin or /sbin when failed
866 base = command[0].split('/')[-1]
867 if self._get_raw_data() is None:
868 for prefix in ['/sbin/', '/usr/sbin/']:
869 command[0] = prefix + base
870 if os.path.isfile(command[0]):
873 self.command = command
874 if self._get_data() is None or len(self._get_data()) == 0:
875 self.error("Command", self.command, "returned no data")