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/'):
28 self.default_priority = 90000
29 # check if plugin directory exists
30 if not os.path.isdir(modules_path):
31 debug("cannot find charts directory ", modules_path)
32 sys.stdout.write("DISABLE\n")
34 self.configs = modules_configs
39 mod = self.import_plugin(modules_path + m + ".chart.py")
41 self.modules.append(mod)
42 if len(self.modules) == 0:
43 debug("cannot find provided module(s)", modules_path)
44 sys.stdout.write("DISABLE\n")
47 self.load_modules(modules_path)
48 if len(self.modules) == 0:
49 debug("cannot find modules directory", modules_path)
50 sys.stdout.write("DISABLE\n")
55 # set timetable dict (last execution, next execution and frequency)
58 for m in self.modules:
60 m.priority = int(m.priority)
61 except (AttributeError,ValueError):
62 m.priority = self.default_priority
66 interval = int(m.update_every)
67 except (AttributeError, ValueError):
71 self.timetable[m.__name__] = {'last' : now,
72 'next' : now - (now % interval) + interval,
75 def import_plugin(self, path, name=None):
77 name = path.split('/')[-1]
78 if name[-9:] != ".chart.py":
82 return importlib.machinery.SourceFileLoader(name, path).load_module()
83 except Exception as e:
87 def load_modules(self, path):
88 names = os.listdir(path)
90 m = self.import_plugin(path + mod)
92 debug("loading chart: '" + path + mod + "'")
93 self.modules.append(m)
95 def load_configs(self):
96 for m in self.modules:
97 configfile = self.configs + m.__name__ + ".conf"
98 if os.path.isfile(configfile):
99 debug("loading chart options: '" + configfile + "'")
100 for k, v in read_config(configfile).items():
104 ": configuration file '" +
106 "' not found. Using defaults.")
108 def disable_module(self, mod, reason=None):
109 self.modules.remove(mod)
110 del self.timetable[mod.__name__]
113 elif reason[:3] == "no ":
116 "' does not seem to have " +
118 "() function. Disabling it.")
119 elif reason[:7] == "failed ":
123 "() function. reports failure.")
124 elif reason[:13] == "configuration":
126 "configuration file '" +
129 ".conf' not found. Using defaults.")
130 elif reason[:11] == "misbehaving":
131 debug(mod.__name__, "is "+reason)
134 for mod in self.modules:
137 self.disable_module(mod, "failed check")
138 except AttributeError:
139 self.disable_module(mod, "no check")
140 except UnboundLocalError:
141 self.disable_module(mod, "misbehaving")
144 for mod in self.modules:
147 self.disable_module(mod, "failed create")
151 "CHART netdata.plugin_pythond_" +
153 " '' 'Execution time for " +
155 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
156 str(self.timetable[mod.__name__]['freq']) +
158 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
160 except AttributeError:
161 self.disable_module(mod, "no create")
162 except UnboundLocalError:
163 self.disable_module(mod, "misbehaving")
165 def update_module(self, mod):
166 t_start = time.time()
167 # check if it is time to execute module update() function
168 if self.timetable[mod.__name__]['next'] > t_start:
174 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
175 if not mod.update(since_last):
176 self.disable_module(mod, "update failed")
178 except AttributeError:
179 self.disable_module(mod, "no update")
181 except (UnboundLocalError, Exception) as e:
182 self.disable_module(mod, "misbehaving. Reason: " + str(e))
185 self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
189 dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
190 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
191 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
192 sys.stdout.write("END\n")
194 self.timetable[mod.__name__]['last'] = t_start
195 self.first_run = False
198 self.first_run = True
200 t_begin = time.time()
202 for mod in self.modules:
203 self.update_module(mod)
205 next_runs.append(self.timetable[mod.__name__]['next'])
208 if len(next_runs) == 0:
209 debug("No plugins loaded")
210 sys.stdout.write("DISABLE\n")
212 time.sleep(min(next_runs) - time.time())
215 def read_config(path):
216 config = configparser.ConfigParser()
219 with open(path, 'r', encoding="utf_8") as f:
220 config_str = '[config]\n' + f.read()
221 except IsADirectoryError:
222 debug(str(path), "is a directory")
224 config.read_string(config_str)
225 return dict(config.items('config'))
231 sys.stderr.write(PROGRAM + ":")
233 sys.stderr.write(" " + str(i))
234 sys.stderr.write("\n")
238 def parse_cmdline(directory, *commands):
239 # TODO number -> interval
245 for cmd in commands[1:]:
248 elif cmd == "debug" or cmd == "all":
250 # redirect stderr to stdout?
251 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
253 mods.append(cmd.replace(".chart.py", ""))
260 debug("started from", commands[0], "with options:", *commands[1:])
262 return {'interval': interval,
266 # if __name__ == '__main__':
268 global DEBUG_FLAG, PROGRAM
270 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
271 # parse env variables
272 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
273 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
274 os.path.abspath(__file__).strip("python.d.plugin.py"))
275 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
276 interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
278 # read configuration file
279 if config_dir[-1] != '/':
280 configfile = config_dir + '/' + "python.d.conf"
282 configfile = config_dir + "python.d.conf"
285 conf = read_config(configfile)
287 if str(conf['enable']) == "no":
288 debug("disabled in configuration file")
289 sys.stdout.write("DISABLE\n")
291 except (KeyError, TypeError):
294 modules_conf = conf['plugins_config_dir']
295 except (KeyError, TypeError):
296 modules_conf = config_dir # default configuration directory
298 modules_dir = conf['plugins_dir']
299 except (KeyError, TypeError):
300 modules_dir = main_dir.replace("plugins.d", "python.d")
302 interval = int(conf['interval'])
303 except (KeyError, TypeError):
304 pass # default interval
306 DEBUG_FLAG = bool(conf['debug'])
307 except (KeyError, TypeError):
309 except FileNotFoundError:
310 modules_conf = config_dir
311 modules_dir = main_dir.replace("plugins.d", "python.d")
313 # directories should end with '/'
314 if modules_dir[-1] != '/':
316 if modules_conf[-1] != '/':
319 # parse passed command line arguments
320 out = parse_cmdline(modules_dir, *sys.argv)
321 modules = out['modules']
322 # if out['interval'] is not None:
323 # interval = out['interval']
325 # configure environement to run modules
326 #sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
329 # charts = PythonCharts(interval, modules, modules_dir, modules_conf)
330 charts = PythonCharts(out['interval'], modules, modules_dir, modules_conf)
335 if __name__ == '__main__':