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))
211 # try to execute create() on every job
212 for job in self.jobs:
215 self._stop(job, "failed create")
217 chart = job.execution_name
219 "CHART netdata.plugin_pythond_" +
221 " '' 'Execution time for " +
223 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
224 str(job.timetable['freq']) +
226 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
228 except AttributeError:
229 self._stop(job, "no create")
230 except (UnboundLocalError, Exception) as e:
231 self._stop(job, "misbehaving. Reason: " + str(e))
233 def _update_job(self, job):
234 # try to execute update() on every job and draw run time graph
235 t_start = time.time()
236 # check if it is time to execute job update() function
237 if job.timetable['next'] > t_start:
243 since_last = int((t_start - job.timetable['last']) * 1000000)
244 if not job.update(since_last):
245 self._stop(job, "update failed")
247 except AttributeError:
248 self._stop(job, "no update")
250 except (UnboundLocalError, Exception) as e:
251 self._stop(job, "misbehaving. Reason: " + str(e))
254 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
255 # draw performance graph
259 dt = int((t_end - job.timetable['last']) * 1000000)
260 sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
261 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
262 sys.stdout.write("END\n")
264 job.timetable['last'] = t_start
265 self.first_run = False
268 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
269 self.first_run = True
271 t_begin = time.time()
273 for job in self.jobs:
274 self._update_job(job)
276 next_runs.append(job.timetable['next'])
279 if len(next_runs) == 0:
280 debug("No plugins loaded")
281 sys.stdout.write("DISABLE\n")
283 time.sleep(min(next_runs) - time.time())
286 def read_config(path):
288 with open(path, 'r') as stream:
289 config = yaml.load(stream)
290 except IsADirectoryError:
291 debug(str(path), "is a directory")
293 except yaml.YAMLError as e:
294 debug(str(path), "is malformed:", e)
302 sys.stderr.write(PROGRAM + ":")
304 sys.stderr.write(" " + str(i))
305 sys.stderr.write("\n")
309 def parse_cmdline(directory, *commands):
310 # TODO number -> interval
316 for cmd in commands[1:]:
319 elif cmd == "debug" or cmd == "all":
321 # redirect stderr to stdout?
322 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
324 mods.append(cmd.replace(".chart.py", ""))
331 debug("started from", commands[0], "with options:", *commands[1:])
332 if len(mods) == 0 and DEBUG_FLAG is False:
335 return {'interval': interval,
339 # if __name__ == '__main__':
341 global DEBUG_FLAG, PROGRAM
343 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
344 # parse env variables
345 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
346 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
347 os.path.abspath(__file__).strip("python.d.plugin.py"))
348 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
349 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
351 # read configuration file
353 if config_dir[-1] != '/':
355 configfile = config_dir + "python.d.conf"
358 conf = read_config(configfile)
360 if str(conf['enable']) is False:
361 debug("disabled in configuration file")
362 sys.stdout.write("DISABLE\n")
364 except (KeyError, TypeError):
367 modules_conf = conf['plugins_config_dir']
369 modules_conf = config_dir + "python.d/" # default configuration directory
371 modules_dir = conf['plugins_dir']
373 modules_dir = main_dir.replace("plugins.d", "python.d")
375 interval = conf['interval']
377 pass # use default interval from NETDATA_UPDATE_EVERY
379 DEBUG_FLAG = conf['debug']
382 for k, v in conf.items():
383 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
387 except FileNotFoundError:
388 modules_conf = config_dir
389 modules_dir = main_dir.replace("plugins.d", "python.d")
391 # directories should end with '/'
392 if modules_dir[-1] != '/':
394 if modules_conf[-1] != '/':
397 # parse passed command line arguments
398 out = parse_cmdline(modules_dir, *sys.argv)
399 modules = out['modules']
400 if out['interval'] is not None:
401 interval = out['interval']
403 # configure environement to run modules
404 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
407 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
412 if __name__ == '__main__':