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 # set configuration directory
29 self.configs = modules_configs
32 self.modules = self.load_modules(modules_path,modules)
34 # check if loaded modules are on disabled modules list
35 for mod in self.modules:
36 if mod.__name__ in modules_disabled:
37 self.modules.remove(mod)
39 # load configuration files
42 # set timetable dict (last execution, next execution and frequency)
45 for m in self.modules:
47 m.priority = int(m.priority)
48 except (AttributeError,ValueError):
49 m.priority = self.default_priority
53 interval = int(m.update_every)
54 except (AttributeError, ValueError):
58 self.timetable[m.__name__] = {'last' : now,
59 'next' : now - (now % interval) + interval,
62 def import_plugin(self, path, name=None):
63 # try to import module using only its path
65 name = path.split('/')[-1]
66 if name[-9:] != ".chart.py":
70 return importlib.machinery.SourceFileLoader(name, path).load_module()
71 except Exception as e:
75 def load_modules(self, path, modules):
76 # check if plugin directory exists
77 if not os.path.isdir(path):
78 debug("cannot find charts directory ", path)
79 sys.stdout.write("DISABLE\n")
86 mod = self.import_plugin(path + m + ".chart.py")
90 # scan directory specified in path and load all modules from there
91 names = os.listdir(path)
93 m = self.import_plugin(path + mod)
95 debug("loading chart: '" + path + mod + "'")
99 def load_configs(self):
100 # function modifies every loaded module in self.modules
101 for m in self.modules:
102 configfile = self.configs + m.__name__ + ".conf"
103 if os.path.isfile(configfile):
104 debug("loading chart options: '" + configfile + "'")
105 for k, v in read_config(configfile).items():
109 ": configuration file '" +
111 "' not found. Using defaults.")
113 def disable_module(self, mod, reason=None):
114 # modifies self.modules
115 self.modules.remove(mod)
116 del self.timetable[mod.__name__]
119 elif reason[:3] == "no ":
122 "' does not seem to have " +
124 "() function. Disabling it.")
125 elif reason[:7] == "failed ":
129 "() function. reports failure.")
130 elif reason[:13] == "configuration":
132 "configuration file '" +
135 ".conf' not found. Using defaults.")
136 elif reason[:11] == "misbehaving":
137 debug(mod.__name__, "is "+reason)
140 # try to execute check() on every loaded module
141 for mod in self.modules:
144 self.disable_module(mod, "failed check")
145 except AttributeError:
146 self.disable_module(mod, "no check")
147 except (UnboundLocalError, Exception) as e:
148 self.disable_module(mod, "misbehaving. Reason: " + str(e))
151 # try to execute create() on every loaded module
152 for mod in self.modules:
155 self.disable_module(mod, "failed create")
159 "CHART netdata.plugin_pythond_" +
161 " '' 'Execution time for " +
163 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
164 str(self.timetable[mod.__name__]['freq']) +
166 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
168 except AttributeError:
169 self.disable_module(mod, "no create")
170 except (UnboundLocalError, Exception) as e:
171 self.disable_module(mod, "misbehaving. Reason: " + str(e))
173 def update_module(self, mod):
174 # try to execute update() on every module and draw run time graph
175 t_start = time.time()
176 # check if it is time to execute module update() function
177 if self.timetable[mod.__name__]['next'] > t_start:
183 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
184 if not mod.update(since_last):
185 self.disable_module(mod, "update failed")
187 except AttributeError:
188 self.disable_module(mod, "no update")
190 except (UnboundLocalError, Exception) as e:
191 self.disable_module(mod, "misbehaving. Reason: " + str(e))
194 self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
195 # draw performance graph
199 dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
200 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
201 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
202 sys.stdout.write("END\n")
204 self.timetable[mod.__name__]['last'] = t_start
205 self.first_run = False
208 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
209 self.first_run = True
211 t_begin = time.time()
213 for mod in self.modules:
214 self.update_module(mod)
216 next_runs.append(self.timetable[mod.__name__]['next'])
219 if len(next_runs) == 0:
220 debug("No plugins loaded")
221 sys.stdout.write("DISABLE\n")
223 time.sleep(min(next_runs) - time.time())
226 def read_config(path):
227 config = configparser.ConfigParser()
230 with open(path, 'r', encoding="utf_8") as f:
231 config_str = '[config]\n' + f.read()
232 except IsADirectoryError:
233 debug(str(path), "is a directory")
236 config.read_string(config_str)
237 except configparser.ParsingError as e:
238 debug("Malformed configuration file: "+str(e))
240 return dict(config.items('config'))
246 sys.stderr.write(PROGRAM + ":")
248 sys.stderr.write(" " + str(i))
249 sys.stderr.write("\n")
253 def parse_cmdline(directory, *commands):
254 # TODO number -> interval
260 for cmd in commands[1:]:
263 elif cmd == "debug" or cmd == "all":
265 # redirect stderr to stdout?
266 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
268 mods.append(cmd.replace(".chart.py", ""))
275 debug("started from", commands[0], "with options:", *commands[1:])
277 return {'interval': interval,
281 # if __name__ == '__main__':
283 global DEBUG_FLAG, PROGRAM
285 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
286 # parse env variables
287 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
288 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
289 os.path.abspath(__file__).strip("python.d.plugin.py"))
290 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
291 interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
293 # read configuration file
295 if config_dir[-1] != '/':
296 configfile = config_dir + '/' + "python.d.conf"
298 configfile = config_dir + "python.d.conf"
301 conf = read_config(configfile)
303 if str(conf['enable']) == "no":
304 debug("disabled in configuration file")
305 sys.stdout.write("DISABLE\n")
307 except (KeyError, TypeError):
310 modules_conf = conf['plugins_config_dir']
312 modules_conf = config_dir + "python.d/" # default configuration directory
314 modules_dir = conf['plugins_dir']
316 modules_dir = main_dir.replace("plugins.d", "python.d")
318 interval = int(conf['interval'])
319 except (KeyError, TypeError):
320 pass # use default interval from NETDATA_UPDATE_EVERY
322 DEBUG_FLAG = bool(conf['debug'])
323 except (KeyError, TypeError):
325 for k, v in conf.items():
326 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
330 except FileNotFoundError:
331 modules_conf = config_dir
332 modules_dir = main_dir.replace("plugins.d", "python.d")
334 # directories should end with '/'
335 if modules_dir[-1] != '/':
337 if modules_conf[-1] != '/':
340 # parse passed command line arguments
341 out = parse_cmdline(modules_dir, *sys.argv)
342 modules = out['modules']
343 if out['interval'] is not None:
344 interval = out['interval']
346 # configure environement to run modules
347 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
350 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
355 if __name__ == '__main__':