7 #import importlib.machinery
9 assert sys.version_info >= (3,1)
11 import importlib.machinery
12 except AssertionError:
13 sys.stderr.write('Not supported python version. Needed python >= 3.1\n')
14 sys.stdout.write('DISABLE\n')
18 class PythonCharts(object):
23 modules_path='../python.d/',
24 modules_configs='../conf.d/'):
29 self.interval = interval
30 self.default_priority = 90000
31 # check if plugin directory exists
32 if not os.path.isdir(modules_path):
33 debug("cannot find charts directory ", modules_path)
34 sys.stdout.write("DISABLE\n")
36 self.configs = modules_configs
41 mod = self.import_plugin(modules_path + m + ".chart.py")
43 self.modules.append(mod)
44 if len(self.modules) == 0:
45 debug("cannot find provided module(s)", modules_path)
46 sys.stdout.write("DISABLE\n")
49 self.load_modules(modules_path)
50 if len(self.modules) == 0:
51 debug("cannot find modules directory", modules_path)
52 sys.stdout.write("DISABLE\n")
57 # set last execution and execution frequency dict
59 for m in self.modules:
60 if self.interval is not None:
61 interval = self.interval
64 interval = int(m.update_every)
65 except (AttributeError, ValueError):
69 self.timetable[m.__name__] = {'last' : 0,
73 for m in self.modules:
75 m.priority = int(m.priority)
76 except (AttributeError,ValueError):
77 m.priority = self.default_priority
80 def import_plugin(self, path, name=None):
82 name = path.split('/')[-1]
83 if name[-9:] != ".chart.py":
87 return importlib.machinery.SourceFileLoader(name, path).load_module()
88 except Exception as e:
92 def load_modules(self, path):
93 names = os.listdir(path)
95 m = self.import_plugin(path + mod)
97 debug("loading chart: '" + path + mod + "'")
98 self.modules.append(m)
100 def load_configs(self):
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 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 misbeaving. Disabling it")
139 for mod in self.modules:
142 self.disable_module(mod, "failed check")
143 except AttributeError:
144 self.disable_module(mod, "no check")
145 except UnboundLocalError:
146 self.disable_module(mod, "misbehaving")
149 for mod in self.modules:
152 self.disable_module(mod, "failed create")
156 "CHART netdata.plugin_pythond_" +
158 " '' 'Execution time for " +
160 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
161 str(self.timetable[mod.__name__]['freq']) +
163 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
165 except AttributeError:
166 self.disable_module(mod, "no create")
167 except UnboundLocalError:
168 self.disable_module(mod, "misbehaving")
170 def update_module(self, mod):
171 t_start = time.time()
172 # check if it is time to execute module update() function
173 if self.timetable[mod.__name__]['next'] > t_start:
179 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
180 if not mod.update(since_last):
181 self.disable_module(mod, "update failed")
183 except AttributeError:
184 self.disable_module(mod, "no update")
186 except UnboundLocalError:
187 self.disable_module(mod, "misbehaving")
190 self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
194 dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
195 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
196 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
197 sys.stdout.write("END\n")
199 self.timetable[mod.__name__]['last'] = t_start
202 self.first_run = True
204 t_begin = time.time()
206 for mod in self.modules:
207 self.update_module(mod)
208 next_runs.append(self.timetable[mod.__name__]['next'])
209 time.sleep(min(next_runs) - time.time())
210 self.first_run = False
213 def read_config(path):
214 config = configparser.ConfigParser()
217 with open(path, 'r', encoding="utf_8") as f:
218 config_str = '[config]\n' + f.read()
219 except IsADirectoryError:
220 debug(str(path), "is a directory")
222 config.read_string(config_str)
223 return dict(config.items('config'))
229 sys.stderr.write(PROGRAM + ":")
231 sys.stderr.write(" " + str(i))
232 sys.stderr.write("\n")
236 def parse_cmdline(directory, *commands):
237 # TODO number -> interval
243 for cmd in commands[1:]:
246 elif cmd == "debug" or cmd == "all":
248 # redirect stderr to stdout?
249 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
251 mods.append(cmd.replace(".chart.py", ""))
258 debug("started from", commands[0], "with options:", *commands[1:])
260 return {'interval': interval,
264 # if __name__ == '__main__':
266 global DEBUG_FLAG, PROGRAM
268 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
269 # parse env variables
270 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
271 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
272 os.path.abspath(__file__).strip("python.d.plugin.py"))
273 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
274 interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
276 # read configuration file
277 if config_dir[-1] != '/':
278 configfile = config_dir + '/' + "python.d.conf"
280 configfile = config_dir + "python.d.conf"
283 conf = read_config(configfile)
285 if str(conf['enable']) == "no":
286 debug("disabled in configuration file")
287 sys.stdout.write("DISABLE\n")
289 except (KeyError, TypeError):
292 modules_conf = conf['plugins_config_dir']
293 except (KeyError, TypeError):
294 modules_conf = config_dir # default configuration directory
296 modules_dir = conf['plugins_dir']
297 except (KeyError, TypeError):
298 modules_dir = main_dir.replace("plugins.d", "python.d")
300 interval = int(conf['interval'])
301 except (KeyError, TypeError):
302 pass # default interval
304 DEBUG_FLAG = bool(conf['debug'])
305 except (KeyError, TypeError):
307 except FileNotFoundError:
308 modules_conf = config_dir
309 modules_dir = main_dir.replace("plugins.d", "python.d")
311 # directories should end with '/'
312 if modules_dir[-1] != '/':
314 if modules_conf[-1] != '/':
317 # parse passed command line arguments
318 out = parse_cmdline(modules_dir, *sys.argv)
319 modules = out['modules']
320 # if out['interval'] is not None:
321 # interval = out['interval']
323 # configure environement to run modules
324 #sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
327 # charts = PythonCharts(interval, modules, modules_dir, modules_conf)
328 charts = PythonCharts(out['interval'], modules, modules_dir, modules_conf)
333 if __name__ == '__main__':