7 assert sys.version_info >= (3,1)
8 import importlib.machinery
10 sys.stderr.write('python.d.plugin: Not supported python version. Needed python >= 3.1\n')
11 sys.stdout.write('DISABLE\n')
16 sys.stderr.write('python.d.plugin: Cannot find yaml library\n')
17 sys.stdout.write('DISABLE\n')
20 BASE_CONFIG = {'update_every' : 10,
25 class PythonCharts(object):
30 modules_path='../python.d/',
31 modules_configs='../conf.d/',
34 # set configuration directory
35 self.configs = modules_configs
38 modules = self._load_modules(modules_path,modules)
40 # check if loaded modules are on disabled modules list
41 loaded_modules = [ m for m in modules if m.__name__ not in 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)
52 job._create_timetable(interval)
55 def _create_jobs(self,modules):
56 # module store a definition of Service class
57 # module store configuration in module.config
58 # configs are list of dicts or a dict
59 # one dict is one service
60 # iterate over list of modules and inside one loop iterate over configs
62 for module in modules:
63 for name in module.config:
65 conf = module.config[name]
67 job = module.Service(configuration=conf, name=name)
68 except Exception as e:
69 debug(module.__name__ +
70 ": Couldn't start job named " +
76 # set execution_name (needed to plot run time graphs)
77 job.execution_name = module.__name__
79 job.execution_name += "_" + name
82 return [j for j in jobs if j is not None]
84 def _import_module(self, path, name=None):
85 # try to import module using only its path
87 name = path.split('/')[-1]
88 if name[-9:] != ".chart.py":
92 return importlib.machinery.SourceFileLoader(name, path).load_module()
93 except Exception as e:
97 def _load_modules(self, path, modules):
98 # check if plugin directory exists
99 if not os.path.isdir(path):
100 debug("cannot find charts directory ", path)
101 sys.stdout.write("DISABLE\n")
108 mod = self._import_module(path + m + ".chart.py")
112 # scan directory specified in path and load all modules from there
113 names = os.listdir(path)
115 m = self._import_module(path + mod)
117 debug("loading chart: '" + path + mod + "'")
121 def _load_configs(self,modules):
122 # function loads configuration files to modules
124 configfile = self.configs + mod.__name__ + ".conf"
125 if os.path.isfile(configfile):
126 debug("loading chart options: '" + configfile + "'")
130 self._parse_config(mod,read_config(configfile)))
131 except Exception as e:
132 debug("something went wrong while loading configuration",e)
135 ": configuration file '" +
137 "' not found. Using defaults.")
140 def _parse_config(self,module,config):
143 for key in BASE_CONFIG:
145 # get defaults from module config
146 defaults[key] = int(config.pop(key))
147 except (KeyError,ValueError):
149 # get defaults from module source code
150 defaults[key] = getattr(module, key)
151 except (KeyError,ValueError):
152 # if above failed, get defaults from global dict
153 defaults[key] = BASE_CONFIG[key]
155 # check if there are dict in config dict
158 if type(config[name]) is dict:
162 # assign variables needed by supervisor to every job configuration
166 if key not in config[name]:
167 config[name][key] = defaults[key]
168 # if only one job is needed, values doesn't have to be in dict (in YAML)
170 config = {None: config.copy()}
171 config[None].update(defaults)
173 # return dictionary of jobs where every job has BASE_CONFIG variables
176 def _stop(self, job, reason=None): #FIXME test if Service has __name__
178 self.jobs.remove(job)
181 elif reason[:3] == "no ":
184 "' does not seem to have " +
186 "() function. Disabling it.")
187 elif reason[:7] == "failed ":
189 job.execution_name + "' " +
191 "() function reports failure.")
192 elif reason[:13] == "configuration":
193 debug(job.execution_name,
194 "configuration file '" +
197 ".conf' not found. Using defaults.")
198 elif reason[:11] == "misbehaving":
199 debug(job.execution_name, "is "+reason)
202 # try to execute check() on every job
203 for job in self.jobs:
206 self._stop(job, "failed check")
207 except AttributeError:
208 self._stop(job, "no check")
209 except (UnboundLocalError, Exception) as e:
210 self._stop(job, "misbehaving. Reason: " + str(e))
214 # try to execute create() on every job
215 for job in self.jobs:
218 self._stop(job, "failed create")
220 chart = job.execution_name
222 "CHART netdata.plugin_pythond_" +
224 " '' 'Execution time for " +
226 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
227 str(job.timetable['freq']) +
229 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
231 except AttributeError:
232 self._stop(job, "no create")
233 except (UnboundLocalError, Exception) as e:
234 self._stop(job, "misbehaving. Reason: " + str(e))
237 def _update_job(self, job):
238 # try to execute update() on every job and draw run time graph
239 t_start = time.time()
240 # check if it is time to execute job update() function
241 if job.timetable['next'] > t_start:
247 since_last = int((t_start - job.timetable['last']) * 1000000)
248 if not job.update(since_last):
249 self._stop(job, "update failed")
251 except AttributeError:
252 self._stop(job, "no update")
254 except (UnboundLocalError, Exception) as e:
255 self._stop(job, "misbehaving. Reason: " + str(e))
258 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
259 # draw performance graph
263 dt = int((t_end - job.timetable['last']) * 1000000)
264 sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
265 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
266 sys.stdout.write("END\n")
268 job.timetable['last'] = t_start
269 self.first_run = False
272 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
273 self.first_run = True
275 t_begin = time.time()
277 for job in self.jobs:
278 self._update_job(job)
280 next_runs.append(job.timetable['next'])
283 if len(next_runs) == 0:
284 debug("No plugins loaded")
285 sys.stdout.write("DISABLE\n")
287 time.sleep(min(next_runs) - time.time())
290 def read_config(path):
292 with open(path, 'r') as stream:
293 config = yaml.load(stream)
294 except IsADirectoryError:
295 debug(str(path), "is a directory")
297 except yaml.YAMLError as e:
298 debug(str(path), "is malformed:", e)
306 sys.stderr.write(PROGRAM + ":")
308 sys.stderr.write(" " + str(i))
309 sys.stderr.write("\n")
313 def parse_cmdline(directory, *commands):
314 # TODO number -> interval
320 for cmd in commands[1:]:
323 elif cmd == "debug" or cmd == "all":
325 # redirect stderr to stdout?
326 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
328 mods.append(cmd.replace(".chart.py", ""))
335 debug("started from", commands[0], "with options:", *commands[1:])
336 if len(mods) == 0 and DEBUG_FLAG is False:
339 return {'interval': interval,
343 # if __name__ == '__main__':
345 global DEBUG_FLAG, PROGRAM
347 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
348 # parse env variables
349 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
350 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
351 os.path.abspath(__file__).strip("python.d.plugin.py"))
352 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
353 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
355 # read configuration file
357 if config_dir[-1] != '/':
359 configfile = config_dir + "python.d.conf"
362 conf = read_config(configfile)
364 if str(conf['enable']) is False:
365 debug("disabled in configuration file")
366 sys.stdout.write("DISABLE\n")
368 except (KeyError, TypeError):
371 modules_conf = conf['plugins_config_dir']
373 modules_conf = config_dir + "python.d/" # default configuration directory
375 modules_dir = conf['plugins_dir']
377 modules_dir = main_dir.replace("plugins.d", "python.d")
379 interval = conf['interval']
381 pass # use default interval from NETDATA_UPDATE_EVERY
383 DEBUG_FLAG = conf['debug']
386 for k, v in conf.items():
387 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
391 except FileNotFoundError:
392 modules_conf = config_dir
393 modules_dir = main_dir.replace("plugins.d", "python.d")
395 # directories should end with '/'
396 if modules_dir[-1] != '/':
398 if modules_conf[-1] != '/':
401 # parse passed command line arguments
402 out = parse_cmdline(modules_dir, *sys.argv)
403 modules = out['modules']
404 if out['interval'] is not None:
405 interval = out['interval']
407 # configure environement to run modules
408 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
411 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
416 if __name__ == '__main__':