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/',
27 self.default_priority = 90000
28 # check if plugin directory exists
29 if not os.path.isdir(modules_path):
30 debug("cannot find charts directory ", modules_path)
31 sys.stdout.write("DISABLE\n")
33 # set configuration directory
34 self.configs = modules_configs
40 mod = self.import_plugin(modules_path + m + ".chart.py")
42 self.modules.append(mod)
44 self.autoload_modules(modules_path)
46 # check if there are any modules loaded
47 if len(self.modules) == 0:
48 debug("cannot find modules", modules_path)
49 sys.stdout.write("DISABLE\n")
52 # check if loaded modules is on disabled modules list
53 for mod in self.modules:
54 if mod.__name__ in modules_disabled:
55 self.modules.remove(mod)
57 # load configuration files
60 # set timetable dict (last execution, next execution and frequency)
63 for m in self.modules:
65 m.priority = int(m.priority)
66 except (AttributeError,ValueError):
67 m.priority = self.default_priority
71 interval = int(m.update_every)
72 except (AttributeError, ValueError):
76 self.timetable[m.__name__] = {'last' : now,
77 'next' : now - (now % interval) + interval,
80 def import_plugin(self, path, name=None):
81 # try to import module using only its path
83 name = path.split('/')[-1]
84 if name[-9:] != ".chart.py":
88 return importlib.machinery.SourceFileLoader(name, path).load_module()
89 except Exception as e:
93 def autoload_modules(self, path):
94 # scan directory specified in path and load all modules from there
95 # function modifies self.modules
96 names = os.listdir(path)
98 m = self.import_plugin(path + mod)
100 debug("loading chart: '" + path + mod + "'")
101 self.modules.append(m)
103 def load_configs(self):
104 # function modifies every loaded module in self.modules
105 for m in self.modules:
106 configfile = self.configs + m.__name__ + ".conf"
107 if os.path.isfile(configfile):
108 debug("loading chart options: '" + configfile + "'")
109 for k, v in read_config(configfile).items():
113 ": configuration file '" +
115 "' not found. Using defaults.")
117 def disable_module(self, mod, reason=None):
118 # modifies self.modules
119 self.modules.remove(mod)
120 del self.timetable[mod.__name__]
123 elif reason[:3] == "no ":
126 "' does not seem to have " +
128 "() function. Disabling it.")
129 elif reason[:7] == "failed ":
133 "() function. reports failure.")
134 elif reason[:13] == "configuration":
136 "configuration file '" +
139 ".conf' not found. Using defaults.")
140 elif reason[:11] == "misbehaving":
141 debug(mod.__name__, "is "+reason)
144 # try to execute check() on every loaded module
145 for mod in self.modules:
148 self.disable_module(mod, "failed check")
149 except AttributeError:
150 self.disable_module(mod, "no check")
151 except (UnboundLocalError, Exception) as e:
152 self.disable_module(mod, "misbehaving. Reason: " + str(e))
155 # try to execute create() on every loaded module
156 for mod in self.modules:
159 self.disable_module(mod, "failed create")
163 "CHART netdata.plugin_pythond_" +
165 " '' 'Execution time for " +
167 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
168 str(self.timetable[mod.__name__]['freq']) +
170 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
172 except AttributeError:
173 self.disable_module(mod, "no create")
174 except (UnboundLocalError, Exception) as e:
175 self.disable_module(mod, "misbehaving. Reason: " + str(e))
177 def update_module(self, mod):
178 # try to execute update() on every module and draw run time graph
179 t_start = time.time()
180 # check if it is time to execute module update() function
181 if self.timetable[mod.__name__]['next'] > t_start:
187 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
188 if not mod.update(since_last):
189 self.disable_module(mod, "update failed")
191 except AttributeError:
192 self.disable_module(mod, "no update")
194 except (UnboundLocalError, Exception) as e:
195 self.disable_module(mod, "misbehaving. Reason: " + str(e))
198 self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
199 # draw performance graph
203 dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
204 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
205 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
206 sys.stdout.write("END\n")
208 self.timetable[mod.__name__]['last'] = t_start
209 self.first_run = False
212 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
213 self.first_run = True
215 t_begin = time.time()
217 for mod in self.modules:
218 self.update_module(mod)
220 next_runs.append(self.timetable[mod.__name__]['next'])
223 if len(next_runs) == 0:
224 debug("No plugins loaded")
225 sys.stdout.write("DISABLE\n")
227 time.sleep(min(next_runs) - time.time())
230 def read_config(path):
231 config = configparser.ConfigParser()
234 with open(path, 'r', encoding="utf_8") as f:
235 config_str = '[config]\n' + f.read()
236 except IsADirectoryError:
237 debug(str(path), "is a directory")
240 config.read_string(config_str)
241 except configparser.ParsingError as e:
242 debug("Malformed configuration file: "+str(e))
244 return dict(config.items('config'))
250 sys.stderr.write(PROGRAM + ":")
252 sys.stderr.write(" " + str(i))
253 sys.stderr.write("\n")
257 def parse_cmdline(directory, *commands):
258 # TODO number -> interval
264 for cmd in commands[1:]:
267 elif cmd == "debug" or cmd == "all":
269 # redirect stderr to stdout?
270 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
272 mods.append(cmd.replace(".chart.py", ""))
279 debug("started from", commands[0], "with options:", *commands[1:])
281 return {'interval': interval,
285 # if __name__ == '__main__':
287 global DEBUG_FLAG, PROGRAM
289 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
290 # parse env variables
291 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
292 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
293 os.path.abspath(__file__).strip("python.d.plugin.py"))
294 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
295 interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
297 # read configuration file
299 if config_dir[-1] != '/':
300 configfile = config_dir + '/' + "python.d.conf"
302 configfile = config_dir + "python.d.conf"
305 conf = read_config(configfile)
307 if str(conf['enable']) == "no":
308 debug("disabled in configuration file")
309 sys.stdout.write("DISABLE\n")
311 except (KeyError, TypeError):
314 modules_conf = conf['plugins_config_dir']
316 modules_conf = config_dir + "python.d/" # default configuration directory
318 modules_dir = conf['plugins_dir']
320 modules_dir = main_dir.replace("plugins.d", "python.d")
322 interval = int(conf['interval'])
323 except (KeyError, TypeError):
324 pass # use default interval from NETDATA_UPDATE_EVERY
326 DEBUG_FLAG = bool(conf['debug'])
327 except (KeyError, TypeError):
329 for k, v in conf.items():
330 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
334 except FileNotFoundError:
335 modules_conf = config_dir
336 modules_dir = main_dir.replace("plugins.d", "python.d")
338 # directories should end with '/'
339 if modules_dir[-1] != '/':
341 if modules_conf[-1] != '/':
344 # parse passed command line arguments
345 out = parse_cmdline(modules_dir, *sys.argv)
346 modules = out['modules']
347 if out['interval'] is not None:
348 interval = out['interval']
350 # configure environement to run modules
351 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
354 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
359 if __name__ == '__main__':