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 modules = self._load_modules(modules_path,modules)
32 # check if loaded modules are on disabled modules list
33 self.modules = [ m for m in modules if m.__name__ not in modules_disabled ]
35 # load configuration files
38 # set timetable dict (last execution, next execution and frequency)
42 for m in self.modules:
44 m.priority = int(m.priority)
45 except (AttributeError,ValueError):
46 m.priority = self.default_priority
50 freq = int(m.update_every)
51 except (AttributeError, ValueError):
55 self.timetable[m.__name__] = {'last' : now,
56 'next' : now - (now % freq) + freq,
59 def _import_plugin(self, path, name=None):
60 # try to import module using only its path
62 name = path.split('/')[-1]
63 if name[-9:] != ".chart.py":
67 return importlib.machinery.SourceFileLoader(name, path).load_module()
68 except Exception as e:
72 def _load_modules(self, path, modules):
73 # check if plugin directory exists
74 if not os.path.isdir(path):
75 debug("cannot find charts directory ", path)
76 sys.stdout.write("DISABLE\n")
83 mod = self._import_plugin(path + m + ".chart.py")
87 # scan directory specified in path and load all modules from there
88 names = os.listdir(path)
90 m = self._import_plugin(path + mod)
92 debug("loading chart: '" + path + mod + "'")
96 def _load_configs(self):
97 # function modifies every loaded module in self.modules
98 for m in self.modules:
99 configfile = self.configs + m.__name__ + ".conf"
100 if os.path.isfile(configfile):
101 debug("loading chart options: '" + configfile + "'")
102 for k, v in read_config(configfile).items():
106 ": configuration file '" +
108 "' not found. Using defaults.")
110 def _disable_module(self, mod, reason=None):
111 # modifies self.modules
112 self.modules.remove(mod)
113 del self.timetable[mod.__name__]
116 elif reason[:3] == "no ":
119 "' does not seem to have " +
121 "() function. Disabling it.")
122 elif reason[:7] == "failed ":
124 mod.__name__ + "' " +
126 "() function reports failure.")
127 elif reason[:13] == "configuration":
129 "configuration file '" +
132 ".conf' not found. Using defaults.")
133 elif reason[:11] == "misbehaving":
134 debug(mod.__name__, "is "+reason)
137 # try to execute check() on every loaded module
138 for mod in self.modules:
141 self._disable_module(mod, "failed check")
142 except AttributeError:
143 self._disable_module(mod, "no check")
144 except (UnboundLocalError, Exception) as e:
145 self._disable_module(mod, "misbehaving. Reason: " + str(e))
148 # try to execute create() on every loaded module
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, Exception) as e:
168 self._disable_module(mod, "misbehaving. Reason: " + str(e))
170 def _update_module(self, mod):
171 # try to execute update() on every module and draw run time graph
172 t_start = time.time()
173 # check if it is time to execute module update() function
174 if self.timetable[mod.__name__]['next'] > t_start:
180 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
181 if not mod.update(since_last):
182 self._disable_module(mod, "update failed")
184 except AttributeError:
185 self._disable_module(mod, "no update")
187 except (UnboundLocalError, Exception) as e:
188 self._disable_module(mod, "misbehaving. Reason: " + str(e))
191 self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
192 # draw performance graph
196 dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
197 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
198 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
199 sys.stdout.write("END\n")
201 self.timetable[mod.__name__]['last'] = t_start
202 self.first_run = False
205 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
206 self.first_run = True
208 t_begin = time.time()
210 for mod in self.modules:
211 self._update_module(mod)
213 next_runs.append(self.timetable[mod.__name__]['next'])
216 if len(next_runs) == 0:
217 debug("No plugins loaded")
218 sys.stdout.write("DISABLE\n")
220 time.sleep(min(next_runs) - time.time())
223 def read_config(path):
224 config = configparser.ConfigParser()
227 with open(path, 'r', encoding="utf_8") as f:
228 config_str = '[config]\n' + f.read()
229 except IsADirectoryError:
230 debug(str(path), "is a directory")
233 config.read_string(config_str)
234 except configparser.ParsingError as e:
235 debug("Malformed configuration file: "+str(e))
237 return dict(config.items('config'))
243 sys.stderr.write(PROGRAM + ":")
245 sys.stderr.write(" " + str(i))
246 sys.stderr.write("\n")
250 def parse_cmdline(directory, *commands):
251 # TODO number -> interval
257 for cmd in commands[1:]:
260 elif cmd == "debug" or cmd == "all":
262 # redirect stderr to stdout?
263 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
265 mods.append(cmd.replace(".chart.py", ""))
272 debug("started from", commands[0], "with options:", *commands[1:])
273 if len(mods) == 0 and DEBUG_FLAG is False:
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] != '/':
296 configfile = config_dir + "python.d.conf"
299 conf = read_config(configfile)
301 if str(conf['enable']) == "no":
302 debug("disabled in configuration file")
303 sys.stdout.write("DISABLE\n")
305 except (KeyError, TypeError):
308 modules_conf = conf['plugins_config_dir']
310 modules_conf = config_dir + "python.d/" # default configuration directory
312 modules_dir = conf['plugins_dir']
314 modules_dir = main_dir.replace("plugins.d", "python.d")
316 interval = int(conf['interval'])
317 except (KeyError, TypeError):
318 pass # use default interval from NETDATA_UPDATE_EVERY
320 DEBUG_FLAG = bool(conf['debug'])
321 except (KeyError, TypeError):
323 for k, v in conf.items():
324 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
328 except FileNotFoundError:
329 modules_conf = config_dir
330 modules_dir = main_dir.replace("plugins.d", "python.d")
332 # directories should end with '/'
333 if modules_dir[-1] != '/':
335 if modules_conf[-1] != '/':
338 # parse passed command line arguments
339 out = parse_cmdline(modules_dir, *sys.argv)
340 modules = out['modules']
341 if out['interval'] is not None:
342 interval = out['interval']
344 # configure environement to run modules
345 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
348 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
353 if __name__ == '__main__':