1 # -*- coding: utf-8 -*-
2 # Description: prototypes for netdata python.d modules
3 # Author: Pawel Krupa (paulfantom)
10 import urllib.request as urllib2
14 from subprocess import Popen, PIPE
20 class BaseService(threading.Thread):
22 Prototype of Service class.
23 Implemented basic functionality to run jobs by `python.d.plugin`
25 def __init__(self, configuration=None, name=None):
27 This needs to be initialized in child classes
28 :param configuration: dict
31 threading.Thread.__init__(self)
32 self._data_stream = ""
36 self.priority = 140000
39 self.override_name = None
43 if configuration is None:
44 self.error("BaseService: no configuration parameters supplied. Cannot create Service.")
47 self._extract_base_config(configuration)
49 self.create_timetable()
51 def _extract_base_config(self, config):
53 Get basic parameters to run service
55 config = {'update_every':1,
61 self.override_name = config.pop('name')
64 self.update_every = int(config.pop('update_every'))
65 self.priority = int(config.pop('priority'))
66 self.retries = int(config.pop('retries'))
67 self.retries_left = self.retries
68 self.configuration = config
70 def create_timetable(self, freq=None):
72 Create service timetable.
75 timetable = {'last': 1466370091.3767564,
81 freq = self.update_every
83 self.timetable = {'last': now,
84 'next': now - (now % freq) + freq,
89 Executes self.update(interval) and draws run time chart.
90 Return value presents exit status of update()
94 # check if it is time to execute job update() function
95 if self.timetable['next'] > t_start:
96 #msg.debug(self.chart_name + " will be run in " +
97 # str(int((self.timetable['next'] - t_start) * 1000)) + " ms")
98 msg.debug(self.chart_name, "will be run in", str(int((self.timetable['next'] - t_start) * 1000)), "ms")
101 since_last = int((t_start - self.timetable['last']) * 1000000)
102 #msg.debug(self.chart_name +
103 # " ready to run, after " + str(int((t_start - self.timetable['last']) * 1000)) +
104 # " ms (update_every: " + str(self.timetable['freq'] * 1000) +
105 # " ms, latency: " + str(int((t_start - self.timetable['next']) * 1000)) + " ms)")
106 msg.debug(self.chart_name,
107 "ready to run, after", str(int((t_start - self.timetable['last']) * 1000)),
108 "ms (update_every:", str(self.timetable['freq'] * 1000),
109 "ms, latency:", str(int((t_start - self.timetable['next']) * 1000)), "ms")
110 if not self.update(since_last):
111 self.error("update function failed.")
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'])
156 append = params.append
161 if type(p) is not str:
168 def _line(self, instruction, *params):
170 Converts *params to string and joins them with one space between every one.
171 :param params: str/int/float
173 #self._data_stream += instruction
174 tmp = list(map((lambda x: "''" if x is None or len(x) == 0 else x), params))
176 self._data_stream += "%s %s\n" % (instruction, str(" ".join(tmp)))
178 # self.error(str(" ".join(tmp)))
188 # self._data_stream += " " + p
189 #self._data_stream += "\n"
191 def chart(self, type_id, name="", title="", units="", family="",
192 category="", charttype="line", priority="", update_every=""):
201 :param charttype: str
202 :param priority: int/str
203 :param update_every: int/str
205 self._charts.append(type_id)
206 #self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
208 p = self._format(type_id, name, title, units, family, category, charttype, priority, update_every)
209 self._line("CHART", *p)
211 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
213 Defines a new dimension for the chart
216 :param algorithm: str
217 :param multiplier: int/str
218 :param divisor: int/str
219 :param hidden: boolean
225 self.error("malformed dimension: multiplier is not a number:", multiplier)
230 self.error("malformed dimension: divisor is not a number:", divisor)
234 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
235 algorithm = "absolute"
237 self._dimensions.append(str(id))
239 p = self._format(id, name, algorithm, multiplier, divisor, "hidden")
240 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor), "hidden")
242 p = self._format(id, name, algorithm, multiplier, divisor)
243 #self._line("DIMENSION", id, name, algorithm, str(multiplier), str(divisor))
245 self._line("DIMENSION", *p)
247 def begin(self, type_id, microseconds=0):
251 :param microseconds: int
254 if type_id not in self._charts:
255 self.error("wrong chart type_id:", type_id)
260 self.error("malformed begin statement: microseconds are not a number:", microseconds)
263 self._line("BEGIN", type_id, str(microseconds))
266 def set(self, id, value):
268 Set value to dimension
270 :param value: int/float
273 if id not in self._dimensions:
274 self.error("wrong dimension id:", id, "Available dimensions are:", *self._dimensions)
277 value = str(int(value))
279 self.error("cannot set non-numeric value:", value)
281 self._line("SET", id, "=", str(value))
289 Upload new data to netdata
291 print(self._data_stream)
292 self._data_stream = ""
294 def error(self, *params):
296 Show error message on stderr
298 msg.error(self.chart_name, *params)
300 def debug(self, *params):
302 Show debug message on stderr
304 msg.debug(self.chart_name, *params)
306 def info(self, *params):
308 Show information message on stderr
310 msg.info(self.chart_name, *params)
317 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
325 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
328 def update(self, interval):
334 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
338 class SimpleService(BaseService):
339 def __init__(self, configuration=None, name=None):
341 self.definitions = {}
342 BaseService.__init__(self, configuration=configuration, name=name)
362 data = self._get_data()
367 for name in self.order:
368 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
369 self.chart(self.chart_name + "." + name, *options)
370 # check if server has this datapoint
371 for line in self.definitions[name]['lines']:
373 self.dimension(*line)
379 def update(self, interval):
385 data = self._get_data()
390 for chart in self.order:
391 if self.begin(self.chart_name + "." + chart, interval):
393 for dim in self.definitions[chart]['lines']:
395 self.set(dim[0], data[dim[0]])
405 class UrlService(SimpleService):
406 def __init__(self, configuration=None, name=None):
410 SimpleService.__init__(self, configuration=configuration, name=name)
412 def __add_auth(self):
413 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
414 passman.add_password(None, self.url, self.user, self.password)
415 authhandler = urllib2.HTTPBasicAuthHandler(passman)
416 opener = urllib2.build_opener(authhandler)
417 urllib2.install_opener(opener)
419 def _get_raw_data(self):
421 Get raw data from http request
426 f = urllib2.urlopen(self.url, timeout=self.update_every)
427 except Exception as e:
432 raw = f.read().decode('utf-8')
433 except Exception as e:
441 Format configuration data and try to connect to server
444 if self.name is None or self.name == str(None):
446 self.chart_name += "_" + self.name
448 self.name = str(self.name)
450 self.url = str(self.configuration['url'])
451 except (KeyError, TypeError):
454 self.user = str(self.configuration['user'])
455 except (KeyError, TypeError):
458 self.password = str(self.configuration['pass'])
459 except (KeyError, TypeError):
462 if self.user is not None and self.password is not None:
465 if self._get_data() is not None:
471 class SocketService(SimpleService):
472 def __init__(self, configuration=None, name=None):
473 self.host = "localhost"
476 self.unix_socket = None
478 SimpleService.__init__(self, configuration=configuration, name=name)
480 def _get_raw_data(self):
482 Get raw data with low-level "socket" module.
485 if self.sock is None:
487 if self.unix_socket is None:
488 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
489 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
490 #sock.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
491 #sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
492 #sock.settimeout(self.update_every)
494 sock.connect((self.host, self.port))
495 sock.settimeout(0.5) # Just to be sure
497 sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
498 #sock.settimeout(self.update_every)
499 sock.settimeout(0.05)
500 sock.connect(self.unix_socket)
501 sock.settimeout(0.05) # Just to be sure
503 except Exception as e:
508 if self.request != "".encode():
510 sock.send(self.request)
511 except Exception as e:
523 data = sock.recv(size).decode()
524 except Exception as e:
530 # implement something like TCP Window Scaling
533 buf = sock.recv(size)
540 def _parse_config(self):
542 Parse configuration data
545 if self.name is None or self.name == str(None):
548 self.name = str(self.name)
550 self.unix_socket = str(self.configuration['socket'])
551 except (KeyError, TypeError):
552 self.error("No unix socket specified. Trying TCP/IP socket.")
554 self.host = str(self.configuration['host'])
555 except (KeyError, TypeError):
556 self.error("No host specified. Using: '" + self.host + "'")
558 self.port = int(self.configuration['port'])
559 except (KeyError, TypeError):
560 self.error("No port specified. Using: '" + str(self.port) + "'")
562 self.request = str(self.configuration['request'])
563 except (KeyError, TypeError):
564 self.error("No request specified. Using: '" + str(self.request) + "'")
565 self.request = self.request.encode()
568 class LogService(SimpleService):
569 def __init__(self, configuration=None, name=None):
571 self._last_position = 0
572 # self._log_reader = None
573 SimpleService.__init__(self, configuration=configuration, name=name)
574 self.retries = 100000 # basically always retry
576 def _get_raw_data(self):
578 Get log lines since last poll
583 if os.path.getsize(self.log_path) < self._last_position:
584 self._last_position = 0
585 elif os.path.getsize(self.log_path) == self._last_position:
586 self.debug("Log file hasn't changed. No new data.")
588 with open(self.log_path, "r") as fp:
589 fp.seek(self._last_position)
590 for i, line in enumerate(fp):
592 self._last_position = fp.tell()
593 except Exception as e:
599 self.error("No data collected.")
604 Parse basic configuration and check if log file exists
607 if self.name is not None or self.name != str(None):
610 self.name = str(self.name)
612 self.log_path = str(self.configuration['path'])
613 except (KeyError, TypeError):
614 self.error("No path to log specified. Using: '" + self.log_path + "'")
616 if os.access(self.log_path, os.R_OK):
619 self.error("Cannot access file: '" + self.log_path + "'")
623 status = SimpleService.create(self)
624 self._last_position = 0
628 class ExecutableService(SimpleService):
629 #command_whitelist = ['exim', 'postqueue']
630 bad_substrings = ('&', '|', ';', '>', '<')
632 def __init__(self, configuration=None, name=None):
634 SimpleService.__init__(self, configuration=configuration, name=name)
636 def _get_raw_data(self):
638 Get raw data from executed command
642 p = Popen(self.command, stdout=PIPE, stderr=PIPE)
643 except Exception as e:
647 for line in p.stdout.readlines():
648 data.append(str(line.decode()))
651 self.error("No data collected.")
658 Parse basic configuration, check if command is whitelisted and is returning values
661 if self.name is not None or self.name != str(None):
664 self.name = str(self.name)
666 self.command = str(self.configuration['command'])
667 except (KeyError, TypeError):
668 self.error("No command specified. Using: '" + self.command + "'")
669 self.command = self.command.split(' ')
670 #if self.command[0] not in self.command_whitelist:
671 # self.error("Command is not whitelisted.")
674 for arg in self.command[1:]:
675 if any(st in arg for st in self.bad_substrings):
676 self.error("Bad command argument:" + " ".join(self.command[1:]))
678 # test command and search for it in /usr/sbin or /sbin when failed
679 base = self.command[0].split('/')[-1]
680 if self._get_raw_data() is None:
681 for prefix in ['/sbin/', '/usr/sbin/']:
682 self.command[0] = prefix + base
683 if os.path.isfile(self.command[0]):
685 #if self._get_raw_data() is not None:
688 if self._get_data() is None or len(self._get_data()) == 0: