1 # -*- coding: utf-8 -*-
2 # Description: prototypes for netdata python.d modules
3 # Author: Pawel Krupa (paulfantom)
10 # from urllib.request import urlopen, Request, HTTPPasswordMgrWithDefaultRealm
11 import urllib.request as urllib2
13 # from urllib2 import urlopen, Request, HTTPPasswordMgrWithDefaultRealm
16 # from subprocess import STDOUT, PIPE, Popen
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('override_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")
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 if not self.update(since_last):
109 self.timetable['next'] = t_end - (t_end % self.timetable['freq']) + self.timetable['freq']
111 # draw performance graph
112 run_time = str(int((t_end - t_start) * 1000))
113 run_time_chart = "BEGIN netdata.plugin_pythond_" + self.chart_name + " " + str(since_last) + '\n'
114 run_time_chart += "SET run_time = " + run_time + '\n'
115 run_time_chart += "END\n"
116 sys.stdout.write(run_time_chart)
117 msg.debug(self.chart_name + " updated in " + str(run_time) + " ms")
118 self.timetable['last'] = t_start
123 Runs job in thread. Handles retries.
124 Exits when job failed or timed out.
127 self.timetable['last'] = time.time()
130 status = self._run_once()
131 except Exception as e:
132 msg.error("Something wrong: " + str(e))
135 time.sleep(self.timetable['next'] - time.time())
136 self.retries_left = self.retries
138 self.retries_left -= 1
139 if self.retries_left <= 0:
140 msg.error("no more retries. Exiting")
143 time.sleep(self.timetable['freq'])
145 def _line(self, instruction, *params):
147 Converts *params to string and joins them with one space between every one.
148 :param params: str/int/float
150 self._data_stream += instruction
160 self._data_stream += " " + p
161 self._data_stream += "\n"
163 def chart(self, type_id, name="", title="", units="", family="",
164 category="", charttype="line", priority="", update_every=""):
173 :param charttype: str
174 :param priority: int/str
175 :param update_every: int/str
177 self._charts.append(type_id)
178 self._line("CHART", type_id, name, title, units, family, category, charttype, priority, update_every)
180 def dimension(self, id, name=None, algorithm="absolute", multiplier=1, divisor=1, hidden=False):
182 Defines a new dimension for the chart
185 :param algorithm: str
186 :param multiplier: int/str
187 :param divisor: int/str
188 :param hidden: boolean
194 self.error("malformed dimension: multiplier is not a number:", multiplier)
199 self.error("malformed dimension: divisor is not a number:", divisor)
203 if algorithm not in ("absolute", "incremental", "percentage-of-absolute-row", "percentage-of-incremental-row"):
204 algorithm = "absolute"
206 self._dimensions.append(id)
208 self._line("DIMENSION", id, name, algorithm, multiplier, divisor, "hidden")
210 self._line("DIMENSION", id, name, algorithm, multiplier, divisor)
212 def begin(self, type_id, microseconds=0):
216 :param microseconds: int
219 if type_id not in self._charts:
220 self.error("wrong chart type_id:", type_id)
225 self.error("malformed begin statement: microseconds are not a number:", microseconds)
228 self._line("BEGIN", type_id, microseconds)
231 def set(self, id, value):
233 Set value to dimension
235 :param value: int/float
238 if id not in self._dimensions:
239 self.error("wrong dimension id:", id)
242 value = str(int(value))
244 self.error("cannot set non-numeric value:", value)
246 self._line("SET", id, "=", value)
254 Upload new data to netdata
256 print(self._data_stream)
257 self._data_stream = ""
259 def error(self, *params):
261 Show error message on stderr
263 msg.error(self.chart_name, *params)
265 def debug(self, *params):
267 Show debug message on stderr
269 msg.debug(self.chart_name, *params)
271 def info(self, *params):
273 Show information message on stderr
275 msg.info(self.chart_name, *params)
282 msg.error("Service " + str(self.__module__) + "doesn't implement check() function")
290 msg.error("Service " + str(self.__module__) + "doesn't implement create() function?")
293 def update(self, interval):
299 msg.error("Service " + str(self.__module__) + "doesn't implement update() function")
303 class SimpleService(BaseService):
304 def __init__(self, configuration=None, name=None):
306 self.definitions = {}
307 BaseService.__init__(self, configuration=configuration, name=name)
327 data = self._get_data()
332 for name in self.order:
333 options = self.definitions[name]['options'] + [self.priority + idx, self.update_every]
334 self.chart(self.__module__ + "_" + self.name + "." + name, *options)
335 # check if server has this datapoint
336 for line in self.definitions[name]['lines']:
338 self.dimension(*line)
344 def update(self, interval):
350 data = self._get_data()
355 for chart in self.order:
356 if self.begin(self.__module__ + "_" + str(self.name) + "." + chart, interval):
358 for dim in self.definitions[chart]['lines']:
360 self.set(dim[0], data[dim[0]])
370 class UrlService(SimpleService):
371 def __init__(self, configuration=None, name=None):
375 SimpleService.__init__(self, configuration=configuration, name=name)
377 def __add_auth(self):
378 passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
379 passman.add_password(None, self.url, self.user, self.password)
380 authhandler = urllib2.HTTPBasicAuthHandler(passman)
381 opener = urllib2.build_opener(authhandler)
382 urllib2.install_opener(opener)
384 def _get_raw_data(self):
386 Get raw data from http request
391 f = urllib2.urlopen(self.url, timeout=self.update_every)
392 except Exception as e:
393 msg.error(self.__module__, str(e))
397 raw = f.read().decode('utf-8')
398 except Exception as e:
399 msg.error(self.__module__, str(e))
406 Format configuration data and try to connect to server
409 if self.name is None or self.name == str(None):
412 self.name = str(self.name)
414 self.url = str(self.configuration['url'])
415 except (KeyError, TypeError):
418 self.user = str(self.configuration['user'])
419 except (KeyError, TypeError):
422 self.password = str(self.configuration['password'])
423 except (KeyError, TypeError):
426 if self.user is not None and self.password is not None:
429 if self._get_data() is not None:
435 class NetSocketService(SimpleService):
436 def __init__(self, configuration=None, name=None):
437 self.host = "localhost"
441 SimpleService.__init__(self, configuration=configuration, name=name)
443 def _get_raw_data(self):
445 Get raw data with low-level "socket" module.
448 if self.sock is None:
450 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
451 sock.settimeout(self.update_every)
452 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
453 sock.connect((self.host, self.port))
454 except Exception as e:
459 sock.send(self.request)
469 data = sock.recv(1024)
472 buf = sock.recv(1024)
483 def _parse_config(self):
485 Parse configuration data
488 if self.name is not None or self.name != str(None):
491 self.name = str(self.name)
493 self.host = str(self.configuration['host'])
494 except (KeyError, TypeError):
495 self.error("No host specified. Using: '" + self.host + "'")
497 self.port = int(self.configuration['port'])
498 except (KeyError, TypeError):
499 self.error("No port specified. Using: '" + str(self.port) + "'")
501 self.port = int(self.configuration['request'])
502 except (KeyError, TypeError):
503 self.error("No request specified. Using: '" + str(self.request) + "'")
504 self.request = self.request.encode()
507 class LogService(SimpleService):
508 def __init__(self, configuration=None, name=None):
510 self._last_position = 0
511 # self._log_reader = None
512 SimpleService.__init__(self, configuration=configuration, name=name)
513 self.retries = 100000 # basically always retry
515 def _get_raw_data(self):
517 Get log lines since last poll
522 if os.path.getsize(self.log_path) < self._last_position:
523 self._last_position = 0
524 elif os.path.getsize(self.log_path) == self._last_position:
526 with open(self.log_path, "r") as fp:
527 fp.seek(self._last_position)
528 for i, line in enumerate(fp):
530 self._last_position = fp.tell()
531 except Exception as e:
532 msg.error(self.__module__, str(e))
540 Parse basic configuration and check if log file exists
543 if self.name is not None or self.name != str(None):
546 self.name = str(self.name)
548 self.log_path = str(self.configuration['path'])
549 except (KeyError, TypeError):
550 self.error("No path to log specified. Using: '" + self.log_path + "'")
552 if os.access(self.log_path, os.R_OK):
555 self.error("Cannot access file: '" + self.log_path + "'")
559 status = SimpleService.create(self)
560 self._last_position = 0