8 assert sys.version_info >= (3, 1)
9 import importlib.machinery
10 except AssertionError:
11 sys.stderr.write('python.d.plugin: Not supported python version. Needed python >= 3.1\n')
12 sys.stdout.write('DISABLE\n')
17 sys.stderr.write('python.d.plugin: Cannot find yaml library\n')
18 sys.stdout.write('DISABLE\n')
22 PROGRAM = "python.d.plugin"
23 MODULE_EXTENSION = ".chart.py"
24 BASE_CONFIG = {'update_every': 10,
29 class PythonCharts(object):
33 modules_path='../python.d/',
34 modules_configs='../conf.d/',
37 # set configuration directory
38 self.configs = modules_configs
41 loaded_modules = self._load_modules(modules_path, modules, modules_disabled)
43 # load configuration files
44 configured_modules = self._load_configs(loaded_modules)
46 # good economy and prosperity:
47 self.jobs = self._create_jobs(configured_modules)
48 if DEBUG_FLAG and interval is not None:
50 job.create_timetable(interval)
53 def _create_jobs(modules):
54 # module store a definition of Service class
55 # module store configuration in module.config
56 # configs are list of dicts or a dict
57 # one dict is one service
58 # iterate over list of modules and inside one loop iterate over configs
60 for module in modules:
61 for name in module.config:
63 conf = module.config[name]
65 job = module.Service(configuration=conf, name=name)
66 except Exception as e:
67 debug(module.__name__ +
68 ": Couldn't start job named " +
74 # set execution_name (needed to plot run time graphs)
75 job.execution_name = module.__name__
77 job.execution_name += "_" + name
80 return [j for j in jobs if j is not None]
83 def _import_module(path, name=None):
84 # try to import module using only its path
86 name = path.split('/')[-1]
87 if name[-len(MODULE_EXTENSION):] != MODULE_EXTENSION:
89 name = name[:-len(MODULE_EXTENSION)]
91 return importlib.machinery.SourceFileLoader(name, path).load_module()
92 except Exception as e:
96 def _load_modules(self, path, modules, disabled):
97 # check if plugin directory exists
98 if not os.path.isdir(path):
99 debug("cannot find charts directory ", path)
100 sys.stdout.write("DISABLE\n")
109 mod = self._import_module(path + m + MODULE_EXTENSION)
113 # scan directory specified in path and load all modules from there
114 names = os.listdir(path)
116 if mod.strip(MODULE_EXTENSION) in disabled:
117 debug("disabling:", mod.strip(MODULE_EXTENSION))
119 m = self._import_module(path + mod)
121 debug("loading chart: '" + path + mod + "'")
125 def _load_configs(self, modules):
126 # function loads configuration files to modules
128 configfile = self.configs + mod.__name__ + ".conf"
129 if os.path.isfile(configfile):
130 debug("loading chart options: '" + configfile + "'")
134 self._parse_config(mod, read_config(configfile)))
135 except Exception as e:
136 debug("something went wrong while loading configuration", e)
139 ": configuration file '" +
141 "' not found. Using defaults.")
142 # set config if not found
143 if not hasattr(mod, 'config'):
144 mod.config = {None: {}}
145 for var in BASE_CONFIG:
147 mod.config[None][var] = getattr(mod, var)
148 except AttributeError:
149 mod.config[None][var] = BASE_CONFIG[var]
153 def _parse_config(module, config):
156 for key in BASE_CONFIG:
158 # get defaults from module config
159 defaults[key] = int(config.pop(key))
160 except (KeyError, ValueError):
162 # get defaults from module source code
163 defaults[key] = getattr(module, key)
164 except (KeyError, ValueError):
165 # if above failed, get defaults from global dict
166 defaults[key] = BASE_CONFIG[key]
168 # check if there are dict in config dict
171 if type(config[name]) is dict:
175 # assign variables needed by supervisor to every job configuration
179 if key not in config[name]:
180 config[name][key] = defaults[key]
181 # if only one job is needed, values doesn't have to be in dict (in YAML)
183 config = {None: config.copy()}
184 config[None].update(defaults)
186 # return dictionary of jobs where every job has BASE_CONFIG variables
189 def _stop(self, job, reason=None):
191 self.jobs.remove(job)
194 elif reason[:3] == "no ":
197 "' does not seem to have " +
199 "() function. Disabling it.")
200 elif reason[:7] == "failed ":
202 job.execution_name + "' " +
204 "() function reports failure.")
205 elif reason[:13] == "configuration":
206 debug(job.execution_name,
207 "configuration file '" +
210 ".conf' not found. Using defaults.")
211 elif reason[:11] == "misbehaving":
212 debug(job.execution_name, "is " + reason)
215 # try to execute check() on every job
216 for job in self.jobs:
219 self._stop(job, "failed check")
220 except AttributeError:
221 self._stop(job, "no check")
222 except (UnboundLocalError, Exception) as e:
223 self._stop(job, "misbehaving. Reason: " + str(e))
226 # try to execute create() on every job
227 for job in self.jobs:
230 self._stop(job, "failed create")
232 chart = job.execution_name
234 "CHART netdata.plugin_pythond_" +
236 " '' 'Execution time for " +
238 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
239 str(job.timetable['freq']) +
241 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
243 except AttributeError:
244 self._stop(job, "no create")
245 except (UnboundLocalError, Exception) as e:
246 self._stop(job, "misbehaving. Reason: " + str(e))
248 def _update_job(self, job):
249 # try to execute update() on every job and draw run time graph
250 t_start = time.time()
251 # check if it is time to execute job update() function
252 if job.timetable['next'] > t_start:
258 since_last = int((t_start - job.timetable['last']) * 1000000)
259 if not job.update(since_last):
260 self._stop(job, "update failed")
262 except AttributeError:
263 self._stop(job, "no update")
265 except (UnboundLocalError, Exception) as e:
266 self._stop(job, "misbehaving. Reason: " + str(e))
269 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
270 # draw performance graph
271 sys.stdout.write("BEGIN netdata.plugin_pythond_" + job.execution_name + " " + str(since_last) + '\n')
272 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
273 sys.stdout.write("END\n")
275 job.timetable['last'] = t_start
276 self.first_run = False
279 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
280 self.first_run = True
283 for job in self.jobs:
284 self._update_job(job)
286 next_runs.append(job.timetable['next'])
289 if len(next_runs) == 0:
290 debug("No plugins loaded")
291 sys.stdout.write("DISABLE\n")
293 time.sleep(min(next_runs) - time.time())
296 def read_config(path):
298 with open(path, 'r') as stream:
299 config = yaml.load(stream)
300 except IsADirectoryError:
301 debug(str(path), "is a directory")
303 except yaml.YAMLError as e:
304 debug(str(path), "is malformed:", e)
312 sys.stderr.write(PROGRAM + ":")
314 sys.stderr.write(" " + str(i))
315 sys.stderr.write("\n")
319 def parse_cmdline(directory, *commands):
324 for cmd in commands[1:]:
327 elif cmd == "debug" or cmd == "all":
329 # redirect stderr to stdout?
330 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
332 mods.append(cmd.replace(".chart.py", ""))
339 debug("started from", commands[0], "with options:", *commands[1:])
340 if len(mods) == 0 and DEBUG_FLAG is False:
343 return {'interval': interval,
347 # if __name__ == '__main__':
349 global DEBUG_FLAG, PROGRAM
351 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
352 # parse env variables
353 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
354 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
355 os.path.abspath(__file__).strip("python.d.plugin.py"))
356 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
357 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
359 # read configuration file
361 if config_dir[-1] != '/':
363 configfile = config_dir + "python.d.conf"
366 conf = read_config(configfile)
369 if str(conf['enable']) is False:
370 debug("disabled in configuration file")
371 sys.stdout.write("DISABLE\n")
373 except (KeyError, TypeError):
376 modules_conf = conf['plugins_config_dir']
378 modules_conf = config_dir + "python.d/" # default configuration directory
380 modules_dir = conf['plugins_dir']
382 modules_dir = main_dir.replace("plugins.d", "python.d")
384 interval = conf['interval']
386 pass # use default interval from NETDATA_UPDATE_EVERY
388 DEBUG_FLAG = conf['debug']
391 for k, v in conf.items():
392 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
396 except FileNotFoundError:
397 modules_conf = config_dir + "python.d/"
398 modules_dir = main_dir.replace("plugins.d", "python.d")
400 # directories should end with '/'
401 if modules_dir[-1] != '/':
403 if modules_conf[-1] != '/':
406 # parse passed command line arguments
407 out = parse_cmdline(modules_dir, *sys.argv)
408 modules = out['modules']
409 if out['interval'] is not None:
410 interval = out['interval']
412 # configure environment to run modules
413 sys.path.append(modules_dir + "python_modules") # append path to directory with modules dependencies
416 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
420 sys.stdout.write("DISABLE")
423 if __name__ == '__main__':