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)
48 if DEBUG_FLAG and interval is not None:
50 job._create_timetable(interval)
53 def _create_jobs(self,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]
82 def _import_module(self, path, name=None):
83 # try to import module using only its path
85 name = path.split('/')[-1]
86 if name[-9:] != ".chart.py":
90 return importlib.machinery.SourceFileLoader(name, path).load_module()
91 except Exception as e:
95 def _load_modules(self, path, modules):
96 # check if plugin directory exists
97 if not os.path.isdir(path):
98 debug("cannot find charts directory ", path)
99 sys.stdout.write("DISABLE\n")
106 mod = self._import_module(path + m + ".chart.py")
110 # scan directory specified in path and load all modules from there
111 names = os.listdir(path)
113 m = self._import_module(path + mod)
115 debug("loading chart: '" + path + mod + "'")
119 def _load_configs(self,modules):
120 # function loads configuration files to modules
122 configfile = self.configs + mod.__name__ + ".conf"
123 if os.path.isfile(configfile):
124 debug("loading chart options: '" + configfile + "'")
128 self._parse_config(mod,read_config(configfile)))
129 except Exception as e:
130 debug("something went wrong while loading configuration",e)
133 ": configuration file '" +
135 "' not found. Using defaults.")
138 def _parse_config(self,module,config):
141 for key in BASE_CONFIG:
143 # get defaults from module config
144 defaults[key] = int(config.pop(key))
145 except (KeyError,ValueError):
147 # get defaults from module source code
148 defaults[key] = getattr(module, key)
149 except (KeyError,ValueError):
150 # if above failed, get defaults from global dict
151 defaults[key] = BASE_CONFIG[key]
153 # check if there are dict in config dict
156 if type(config[name]) is dict:
160 # assign variables needed by supervisor to every job configuration
164 if key not in config[name]:
165 config[name][key] = defaults[key]
166 # if only one job is needed, values doesn't have to be in dict (in YAML)
168 config = {None: config.copy()}
169 config[None].update(defaults)
171 # return dictionary of jobs where every job has BASE_CONFIG variables
174 def _stop(self, job, reason=None): #FIXME test if Service has __name__
176 self.jobs.remove(job)
179 elif reason[:3] == "no ":
182 "' does not seem to have " +
184 "() function. Disabling it.")
185 elif reason[:7] == "failed ":
187 job.execution_name + "' " +
189 "() function reports failure.")
190 elif reason[:13] == "configuration":
191 debug(job.execution_name,
192 "configuration file '" +
195 ".conf' not found. Using defaults.")
196 elif reason[:11] == "misbehaving":
197 debug(job.execution_name, "is "+reason)
200 # try to execute check() on every job
201 for job in self.jobs:
204 self._stop(job, "failed check")
205 except AttributeError:
206 self._stop(job, "no check")
207 except (UnboundLocalError, Exception) as e:
208 self._stop(job, "misbehaving. Reason: " + str(e))
212 # try to execute create() on every job
213 for job in self.jobs:
216 self._stop(job, "failed create")
218 chart = job.execution_name
220 "CHART netdata.plugin_pythond_" +
222 " '' 'Execution time for " +
224 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
225 str(job.timetable['freq']) +
227 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
229 except AttributeError:
230 self._stop(job, "no create")
231 except (UnboundLocalError, Exception) as e:
232 self._stop(job, "misbehaving. Reason: " + str(e))
235 def _update_job(self, job):
236 # try to execute update() on every job and draw run time graph
237 t_start = time.time()
238 # check if it is time to execute job update() function
239 if job.timetable['next'] > t_start:
245 since_last = int((t_start - job.timetable['last']) * 1000000)
246 if not job.update(since_last):
247 self._stop(job, "update failed")
249 except AttributeError:
250 self._stop(job, "no update")
252 except (UnboundLocalError, Exception) as e:
253 self._stop(job, "misbehaving. Reason: " + str(e))
256 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
257 # draw performance graph
261 dt = int((t_end - job.timetable['last']) * 1000000)
262 sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
263 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
264 sys.stdout.write("END\n")
266 job.timetable['last'] = t_start
267 self.first_run = False
270 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
271 self.first_run = True
273 t_begin = time.time()
275 for job in self.jobs:
276 self._update_job(job)
278 next_runs.append(job.timetable['next'])
281 if len(next_runs) == 0:
282 debug("No plugins loaded")
283 sys.stdout.write("DISABLE\n")
285 time.sleep(min(next_runs) - time.time())
288 def read_config(path):
290 with open(path, 'r') as stream:
291 config = yaml.load(stream)
292 except IsADirectoryError:
293 debug(str(path), "is a directory")
295 except yaml.YAMLError as e:
296 debug(str(path), "is malformed:", e)
304 sys.stderr.write(PROGRAM + ":")
306 sys.stderr.write(" " + str(i))
307 sys.stderr.write("\n")
311 def parse_cmdline(directory, *commands):
312 # TODO number -> interval
318 for cmd in commands[1:]:
321 elif cmd == "debug" or cmd == "all":
323 # redirect stderr to stdout?
324 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
326 mods.append(cmd.replace(".chart.py", ""))
333 debug("started from", commands[0], "with options:", *commands[1:])
334 if len(mods) == 0 and DEBUG_FLAG is False:
337 return {'interval': interval,
341 # if __name__ == '__main__':
343 global DEBUG_FLAG, PROGRAM
345 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
346 # parse env variables
347 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
348 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
349 os.path.abspath(__file__).strip("python.d.plugin.py"))
350 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
351 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
353 # read configuration file
355 if config_dir[-1] != '/':
357 configfile = config_dir + "python.d.conf"
360 conf = read_config(configfile)
362 if str(conf['enable']) is False:
363 debug("disabled in configuration file")
364 sys.stdout.write("DISABLE\n")
366 except (KeyError, TypeError):
369 modules_conf = conf['plugins_config_dir']
371 modules_conf = config_dir + "python.d/" # default configuration directory
373 modules_dir = conf['plugins_dir']
375 modules_dir = main_dir.replace("plugins.d", "python.d")
377 interval = conf['interval']
379 pass # use default interval from NETDATA_UPDATE_EVERY
381 DEBUG_FLAG = conf['debug']
384 for k, v in conf.items():
385 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
389 except FileNotFoundError:
390 modules_conf = config_dir
391 modules_dir = main_dir.replace("plugins.d", "python.d")
393 # directories should end with '/'
394 if modules_dir[-1] != '/':
396 if modules_conf[-1] != '/':
399 # parse passed command line arguments
400 out = parse_cmdline(modules_dir, *sys.argv)
401 modules = out['modules']
402 if out['interval'] is not None:
403 interval = out['interval']
405 # configure environement to run modules
406 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
409 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
414 if __name__ == '__main__':