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)
51 def _create_jobs(self,modules):
52 # module store a definition of Service class
53 # module store configuration in module.config
54 # configs are list of dicts or a dict
55 # one dict is one service
56 # iterate over list of modules and inside one loop iterate over configs
58 for module in modules:
59 for name in module.config:
61 conf = module.config[name]
63 job = module.Service(configuration=conf, name=name)
64 except Exception as e:
65 debug(module.__name__ +
66 ": Couldn't start job named " +
72 # set execution_name (needed to plot run time graphs)
73 job.execution_name = module.__name__ + "_" + name
76 return [j for j in jobs if j is not None]
78 def _import_module(self, path, name=None):
79 # try to import module using only its path
81 name = path.split('/')[-1]
82 if name[-9:] != ".chart.py":
86 return importlib.machinery.SourceFileLoader(name, path).load_module()
87 except Exception as e:
91 def _load_modules(self, path, modules):
92 # check if plugin directory exists
93 if not os.path.isdir(path):
94 debug("cannot find charts directory ", path)
95 sys.stdout.write("DISABLE\n")
102 mod = self._import_module(path + m + ".chart.py")
106 # scan directory specified in path and load all modules from there
107 names = os.listdir(path)
109 m = self._import_module(path + mod)
111 debug("loading chart: '" + path + mod + "'")
115 def _load_configs(self,modules):
116 # function loads configuration files to modules
118 configfile = self.configs + mod.__name__ + ".conf"
119 if os.path.isfile(configfile):
120 debug("loading chart options: '" + configfile + "'")
124 self._parse_config(mod,read_config(configfile)))
125 except Exception as e:
126 debug("something went wrong while loading configuration",e)
129 ": configuration file '" +
131 "' not found. Using defaults.")
134 def _parse_config(self,module,config):
137 for key in BASE_CONFIG:
139 # get defaults from module config
140 defaults[key] = int(config.pop(key))
141 except (KeyError,ValueError):
143 # get defaults from module source code
144 defaults[key] = getattr(module, key)
145 except (KeyError,ValueError):
146 # if above failed, get defaults from global dict
147 defaults[key] = BASE_CONFIG[key]
149 # assign variables needed by supervisor to every job configuration
151 for key in BASE_CONFIG:
152 if key not in config[name]:
153 config[name][key] = defaults[key]
155 # return dictionary of jobs where every job has BASE_CONFIG variables
158 def _stop(self, job, reason=None): #FIXME test if Service has __name__
160 self.jobs.remove(job)
163 elif reason[:3] == "no ":
166 "' does not seem to have " +
168 "() function. Disabling it.")
169 elif reason[:7] == "failed ":
171 job.execution_name + "' " +
173 "() function reports failure.")
174 elif reason[:13] == "configuration":
175 debug(job.execution_name,
176 "configuration file '" +
179 ".conf' not found. Using defaults.")
180 elif reason[:11] == "misbehaving":
181 debug(job.execution_name, "is "+reason)
184 # try to execute check() on every job
185 for job in self.jobs:
188 self._stop(job, "failed check")
189 except AttributeError:
190 self._stop(job, "no check")
191 except (UnboundLocalError, Exception) as e:
192 self._stop(job, "misbehaving. Reason: " + str(e))
195 # try to execute create() on every job
196 for job in self.jobs:
199 self._stop(job, "failed create")
201 chart = job.execution_name
203 "CHART netdata.plugin_pythond_" +
205 " '' 'Execution time for " +
207 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
208 str(job.timetable['freq']) +
210 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
212 except AttributeError:
213 self._stop(job, "no create")
214 except (UnboundLocalError, Exception) as e:
215 self._stop(job, "misbehaving. Reason: " + str(e))
217 def _update_job(self, job):
218 # try to execute update() on every job and draw run time graph
219 t_start = time.time()
220 # check if it is time to execute job update() function
221 if job.timetable['next'] > t_start:
227 since_last = int((t_start - job.timetable['last']) * 1000000)
228 if not job.update(since_last):
229 self._stop(job, "update failed")
231 except AttributeError:
232 self._stop(job, "no update")
234 except (UnboundLocalError, Exception) as e:
235 self._stop(job, "misbehaving. Reason: " + str(e))
238 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
239 # draw performance graph
243 dt = int((t_end - job.timetable['last']) * 1000000)
244 sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
245 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
246 sys.stdout.write("END\n")
248 job.timetable['last'] = t_start
249 self.first_run = False
252 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
253 self.first_run = True
255 t_begin = time.time()
257 for job in self.jobs:
258 self._update_job(job)
260 next_runs.append(job.timetable['next'])
263 if len(next_runs) == 0:
264 debug("No plugins loaded")
265 sys.stdout.write("DISABLE\n")
267 time.sleep(min(next_runs) - time.time())
270 def read_config(path):
272 with open(path, 'r') as stream:
273 config = yaml.load(stream)
274 except IsADirectoryError:
275 debug(str(path), "is a directory")
277 except yaml.YAMLError as e:
278 debug(str(path), "is malformed:", e)
286 sys.stderr.write(PROGRAM + ":")
288 sys.stderr.write(" " + str(i))
289 sys.stderr.write("\n")
293 def parse_cmdline(directory, *commands):
294 # TODO number -> interval
300 for cmd in commands[1:]:
303 elif cmd == "debug" or cmd == "all":
305 # redirect stderr to stdout?
306 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
308 mods.append(cmd.replace(".chart.py", ""))
315 debug("started from", commands[0], "with options:", *commands[1:])
316 if len(mods) == 0 and DEBUG_FLAG is False:
319 return {'interval': interval,
323 # if __name__ == '__main__':
325 global DEBUG_FLAG, PROGRAM
327 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
328 # parse env variables
329 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
330 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
331 os.path.abspath(__file__).strip("python.d.plugin.py"))
332 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
333 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
335 # read configuration file
337 if config_dir[-1] != '/':
339 configfile = config_dir + "python.d.conf"
342 conf = read_config(configfile)
344 if str(conf['enable']) == "no":
345 debug("disabled in configuration file")
346 sys.stdout.write("DISABLE\n")
348 except (KeyError, TypeError):
351 modules_conf = conf['plugins_config_dir']
353 modules_conf = config_dir + "python.d/" # default configuration directory
355 modules_dir = conf['plugins_dir']
357 modules_dir = main_dir.replace("plugins.d", "python.d")
359 interval = int(conf['interval'])
360 except (KeyError, TypeError):
361 pass # use default interval from NETDATA_UPDATE_EVERY
363 DEBUG_FLAG = bool(conf['debug'])
364 except (KeyError, TypeError):
366 for k, v in conf.items():
367 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
371 except FileNotFoundError:
372 modules_conf = config_dir
373 modules_dir = main_dir.replace("plugins.d", "python.d")
375 # directories should end with '/'
376 if modules_dir[-1] != '/':
378 if modules_conf[-1] != '/':
381 # parse passed command line arguments
382 out = parse_cmdline(modules_dir, *sys.argv)
383 modules = out['modules']
384 if out['interval'] is not None:
385 interval = out['interval']
387 # configure environement to run modules
388 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
391 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
396 if __name__ == '__main__':