7 assert sys.version_info >= (3,1)
9 import importlib.machinery
10 except AssertionError:
11 sys.stderr.write('Not supported python version. Needed python >= 3.1\n')
12 sys.stdout.write('DISABLE\n')
16 class PythonCharts(object):
21 modules_path='../python.d/',
22 modules_configs='../conf.d/',
25 self.default_priority = 90000
26 # set configuration directory
27 self.configs = modules_configs
30 self.modules = self._load_modules(modules_path,modules)
32 # check if loaded modules are on disabled modules list
33 for mod in self.modules:
34 if mod.__name__ in modules_disabled:
35 self.modules.remove(mod)
37 # load configuration files
40 # set timetable dict (last execution, next execution and frequency)
44 for m in self.modules:
46 m.priority = int(m.priority)
47 except (AttributeError,ValueError):
48 m.priority = self.default_priority
52 freq = int(m.update_every)
53 except (AttributeError, ValueError):
57 self.timetable[m.__name__] = {'last' : now,
58 'next' : now - (now % freq) + freq,
61 def _import_plugin(self, path, name=None):
62 # try to import module using only its path
64 name = path.split('/')[-1]
65 if name[-9:] != ".chart.py":
69 return importlib.machinery.SourceFileLoader(name, path).load_module()
70 except Exception as e:
74 def _load_modules(self, path, modules):
75 # check if plugin directory exists
76 if not os.path.isdir(path):
77 debug("cannot find charts directory ", path)
78 sys.stdout.write("DISABLE\n")
85 mod = self._import_plugin(path + m + ".chart.py")
89 # scan directory specified in path and load all modules from there
90 names = os.listdir(path)
92 m = self._import_plugin(path + mod)
94 debug("loading chart: '" + path + mod + "'")
98 def _load_configs(self):
99 # function modifies every loaded module in self.modules
100 for m in self.modules:
101 configfile = self.configs + m.__name__ + ".conf"
102 if os.path.isfile(configfile):
103 debug("loading chart options: '" + configfile + "'")
104 for k, v in read_config(configfile).items():
108 ": configuration file '" +
110 "' not found. Using defaults.")
112 def _disable_module(self, mod, reason=None):
113 # modifies self.modules
114 self.modules.remove(mod)
115 del self.timetable[mod.__name__]
118 elif reason[:3] == "no ":
121 "' does not seem to have " +
123 "() function. Disabling it.")
124 elif reason[:7] == "failed ":
128 "() function. reports failure.")
129 elif reason[:13] == "configuration":
131 "configuration file '" +
134 ".conf' not found. Using defaults.")
135 elif reason[:11] == "misbehaving":
136 debug(mod.__name__, "is "+reason)
139 # try to execute check() on every loaded module
140 for mod in self.modules:
143 self._disable_module(mod, "failed check")
144 except AttributeError:
145 self._disable_module(mod, "no check")
146 except (UnboundLocalError, Exception) as e:
147 self._disable_module(mod, "misbehaving. Reason: " + str(e))
150 # try to execute create() on every loaded module
151 for mod in self.modules:
154 self._disable_module(mod, "failed create")
158 "CHART netdata.plugin_pythond_" +
160 " '' 'Execution time for " +
162 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
163 str(self.timetable[mod.__name__]['freq']) +
165 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
167 except AttributeError:
168 self._disable_module(mod, "no create")
169 except (UnboundLocalError, Exception) as e:
170 self._disable_module(mod, "misbehaving. Reason: " + str(e))
172 def _update_module(self, mod):
173 # try to execute update() on every module and draw run time graph
174 t_start = time.time()
175 # check if it is time to execute module update() function
176 if self.timetable[mod.__name__]['next'] > t_start:
182 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
183 if not mod.update(since_last):
184 self._disable_module(mod, "update failed")
186 except AttributeError:
187 self._disable_module(mod, "no update")
189 except (UnboundLocalError, Exception) as e:
190 self._disable_module(mod, "misbehaving. Reason: " + str(e))
193 self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
194 # draw performance graph
198 dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
199 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
200 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
201 sys.stdout.write("END\n")
203 self.timetable[mod.__name__]['last'] = t_start
204 self.first_run = False
207 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
208 self.first_run = True
210 t_begin = time.time()
212 for mod in self.modules:
213 self._update_module(mod)
215 next_runs.append(self.timetable[mod.__name__]['next'])
218 if len(next_runs) == 0:
219 debug("No plugins loaded")
220 sys.stdout.write("DISABLE\n")
222 time.sleep(min(next_runs) - time.time())
225 def read_config(path):
226 config = configparser.ConfigParser()
229 with open(path, 'r', encoding="utf_8") as f:
230 config_str = '[config]\n' + f.read()
231 except IsADirectoryError:
232 debug(str(path), "is a directory")
235 config.read_string(config_str)
236 except configparser.ParsingError as e:
237 debug("Malformed configuration file: "+str(e))
239 return dict(config.items('config'))
245 sys.stderr.write(PROGRAM + ":")
247 sys.stderr.write(" " + str(i))
248 sys.stderr.write("\n")
252 def parse_cmdline(directory, *commands):
253 # TODO number -> interval
259 for cmd in commands[1:]:
262 elif cmd == "debug" or cmd == "all":
264 # redirect stderr to stdout?
265 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
267 mods.append(cmd.replace(".chart.py", ""))
274 debug("started from", commands[0], "with options:", *commands[1:])
276 return {'interval': interval,
280 # if __name__ == '__main__':
282 global DEBUG_FLAG, PROGRAM
284 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
285 # parse env variables
286 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
287 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
288 os.path.abspath(__file__).strip("python.d.plugin.py"))
289 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
290 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
292 # read configuration file
294 if config_dir[-1] != '/':
295 configfile = config_dir + '/' + "python.d.conf"
297 configfile = config_dir + "python.d.conf"
300 conf = read_config(configfile)
302 if str(conf['enable']) == "no":
303 debug("disabled in configuration file")
304 sys.stdout.write("DISABLE\n")
306 except (KeyError, TypeError):
309 modules_conf = conf['plugins_config_dir']
311 modules_conf = config_dir + "python.d/" # default configuration directory
313 modules_dir = conf['plugins_dir']
315 modules_dir = main_dir.replace("plugins.d", "python.d")
317 interval = int(conf['interval'])
318 except (KeyError, TypeError):
319 pass # use default interval from NETDATA_UPDATE_EVERY
321 DEBUG_FLAG = bool(conf['debug'])
322 except (KeyError, TypeError):
324 for k, v in conf.items():
325 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
329 except FileNotFoundError:
330 modules_conf = config_dir
331 modules_dir = main_dir.replace("plugins.d", "python.d")
333 # directories should end with '/'
334 if modules_dir[-1] != '/':
336 if modules_conf[-1] != '/':
339 # parse passed command line arguments
340 out = parse_cmdline(modules_dir, *sys.argv)
341 modules = out['modules']
342 if out['interval'] is not None:
343 interval = out['interval']
345 # configure environement to run modules
346 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
349 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
354 if __name__ == '__main__':