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)
210 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
212 Defines a new dimension for the chart
215 :param algorithm: str
216 :param multiplier: int/str
217 :param divisor: int/str
218 :param hidden: boolean
224 self.error("malformed dimension: multiplier is not a number:", multiplier)
229 self.error("malformed dimension: divisor is not a number:", divisor)
233 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
234 algorithm = "absolute"
236 self._dimensions.append(str(id))
238 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
239 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
241 p = self._format(id, name, algorithm, multiplier, divisor)
242 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
244 self._line("DIMENSION", *p)
246 def begin(self, type_id, microseconds=0):
250 :param microseconds: int
253 if type_id not in self._charts:
254 self.error("wrong chart type_id:", type_id)
259 self.error("malformed begin statement: microseconds are not a number:", microseconds)
262 self._line("BEGIN", type_id, str(microseconds))
265 def set(self, id, value):
267 Set value to dimension
269 :param value: int/float
272 if id not in self._dimensions:
273 self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
276 value = str(int(value))
278 self.error("cannot set non-numeric value:", value)
280 self._line("SET", id, "=", str(value))
288 Upload new data to netdata
290 print(self._data_stream)
291 self._data_stream = ""
293 def error(self, *params):
295 Show error message on stderr
297 msg.error(self.chart_name, *params)
299 def debug(self, *params):
301 Show debug message on stderr
303 msg.debug(self.chart_name, *params)
305 def info(self, *params):
307 Show information message on stderr
309 msg.info(self.chart_name, *params)
316 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
324 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
327 def update(self, interval):
333 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
337 class SimpleService(BaseService):
338 def __init__(self, configuration=None, name=None):
340 self.definitions = {}
341 BaseService.__init__(self, configuration=configuration, name=name)
361 data = self._get_data()
366 for name in self.order:
367 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
368 self.chart(self.chart_name + "." + name, *options)
369 # check if server has this datapoint
370 for line in self.definitions[name]['lines']:
372 self.dimension(*line)
378 def update(self, interval):
384 data = self._get_data()
389 for chart in self.order:
390 if self.begin(self.chart_name + "." + chart, interval):
392 for dim in self.definitions[chart]['lines']:
394 self.set(dim[0], data[dim[0]])
404 class UrlService(SimpleService):
405 def __init__(self, configuration=None, name=None):
409 SimpleService.__init__(self, configuration=configuration, name=name)
411 def __add_auth(self):
412 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
413 passman.add_password(None, self.url, self.user, self.password)
414 authhandler = urllib2.HTTPBasicAuthHandler(passman)
415 opener = urllib2.build_opener(authhandler)
416 urllib2.install_opener(opener)
418 def _get_raw_data(self):
420 Get raw data from http request
425 f = urllib2.urlopen(self.url, timeout=self.update_every)
426 except Exception as e:
427 msg.error(self.__module__, str(e))
431 raw = f.read().decode('utf-8')
432 except Exception as e:
433 msg.error(self.__module__, str(e))
440 Format configuration data and try to connect to server
443 if self.name is None or self.name == str(None):
445 self.chart_name += "_" + self.name
447 self.name = str(self.name)
449 self.url = str(self.configuration['url'])
450 except (KeyError, TypeError):
453 self.user = str(self.configuration['user'])
454 except (KeyError, TypeError):
457 self.password = str(self.configuration['pass'])
458 except (KeyError, TypeError):
461 if self.user is not None and self.password is not None:
464 if self._get_data() is not None:
470 class SocketService(SimpleService):
471 def __init__(self, configuration=None, name=None):
472 self.host = "localhost"
475 self.unix_socket = None
477 SimpleService.__init__(self, configuration=configuration, name=name)
479 def _get_raw_data(self):
481 Get raw data with low-level "socket" module.
484 if self.sock is None:
486 if self.unix_socket is None:
487 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
488 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
489 #sock.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
490 #sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
491 #sock.settimeout(self.update_every)
493 sock.connect((self.host, self.port))
494 sock.settimeout(0.5) # Just to be sure
496 sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
497 #sock.settimeout(self.update_every)
498 sock.settimeout(0.05)
499 sock.connect(self.unix_socket)
500 sock.settimeout(0.05) # Just to be sure
502 except Exception as e:
507 if self.request != "".encode():
509 sock.send(self.request)
521 data = sock.recv(size).decode()
522 except Exception as e:
528 # implement something like TCP Window Scaling
531 buf = sock.recv(size)
538 def _parse_config(self):
540 Parse configuration data
543 if self.name is not None or self.name != str(None):
546 self.name = str(self.name)
548 self.unix_socket = str(self.configuration['socket'])
549 except (KeyError, TypeError):
550 self.error("No unix socket specified. Trying TCP/IP socket.")
552 self.host = str(self.configuration['host'])
553 except (KeyError, TypeError):
554 self.error("No host specified. Using: '" + self.host + "'")
556 self.port = int(self.configuration['port'])
557 except (KeyError, TypeError):
558 self.error("No port specified. Using: '" + str(self.port) + "'")
560 self.request = str(self.configuration['request'])
561 except (KeyError, TypeError):
562 self.error("No request specified. Using: '" + str(self.request) + "'")
563 self.request = self.request.encode()
566 class LogService(SimpleService):
567 def __init__(self, configuration=None, name=None):
569 self._last_position = 0
570 # self._log_reader = None
571 SimpleService.__init__(self, configuration=configuration, name=name)
572 self.retries = 100000 # basically always retry
574 def _get_raw_data(self):
576 Get log lines since last poll
581 if os.path.getsize(self.log_path) < self._last_position:
582 self._last_position = 0
583 elif os.path.getsize(self.log_path) == self._last_position:
585 with open(self.log_path, "r") as fp:
586 fp.seek(self._last_position)
587 for i, line in enumerate(fp):
589 self._last_position = fp.tell()
590 except Exception as e:
591 self.error(self.__module__, str(e))
599 Parse basic configuration and check if log file exists
602 if self.name is not None or self.name != str(None):
605 self.name = str(self.name)
607 self.log_path = str(self.configuration['path'])
608 except (KeyError, TypeError):
609 self.error("No path to log specified. Using: '" + self.log_path + "'")
611 if os.access(self.log_path, os.R_OK):
614 self.error("Cannot access file: '" + self.log_path + "'")
618 status = SimpleService.create(self)
619 self._last_position = 0
623 class ExecutableService(SimpleService):
624 #command_whitelist = ['exim', 'postqueue']
625 bad_substrings = ('&', '|', ';', '>', '<')
627 def __init__(self, configuration=None, name=None):
629 SimpleService.__init__(self, configuration=configuration, name=name)
631 def _get_raw_data(self):
633 Get raw data from executed command
637 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
638 except Exception as e:
639 self.error(self.__module__, str(e))
642 for line in p.stdout.readlines():
643 data.append(str(line.decode()))
652 Parse basic configuration, check if command is whitelisted and is returning values
655 if self.name is not None or self.name != str(None):
658 self.name = str(self.name)
660 self.command = str(self.configuration['command'])
661 except (KeyError, TypeError):
662 self.error("No command specified. Using: '" + self.command + "'")
663 self.command = self.command.split(' ')
664 #if self.command[0] not in self.command_whitelist:
665 # self.error("Command is not whitelisted.")
668 for arg in self.command[1:]:
669 if any(st in arg for st in self.bad_substrings):
670 self.error("Bad command argument:" + " ".join(self.command[1:]))
672 # test command and search for it in /usr/sbin or /sbin when failed
673 base = self.command[0].split('/')[-1]
674 if self._get_raw_data() is None:
675 for prefix in ['/sbin/', '/usr/sbin/']:
676 self.command[0] = prefix + base
677 if os.path.isfile(self.command[0]):
679 #if self._get_raw_data() is not None:
682 if self._get_data() is None or len(self._get_data()) == 0: