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)
50 def _create_jobs(self,modules):
51 # module store a definition of Service class
52 # module store configuration in module.config
53 # configs are list of dicts or a dict
54 # one dict is one service
55 # iterate over list of modules and inside one loop iterate over configs
57 for module in modules:
58 for name in module.config:
60 conf = module.config[name]
62 job = module.Service(configuration=conf, name=name)
63 except Exception as e:
64 debug(module.__name__ +
65 ": Couldn't start job named " +
71 # set execution_name (needed to plot run time graphs)
72 job.execution_name = module.__name__
74 job.execution_name += "_" + name
77 return [j for j in jobs if j is not None]
79 def _import_module(self, path, name=None):
80 # try to import module using only its path
82 name = path.split('/')[-1]
83 if name[-9:] != ".chart.py":
87 return importlib.machinery.SourceFileLoader(name, path).load_module()
88 except Exception as e:
92 def _load_modules(self, path, modules):
93 # check if plugin directory exists
94 if not os.path.isdir(path):
95 debug("cannot find charts directory ", path)
96 sys.stdout.write("DISABLE\n")
103 mod = self._import_module(path + m + ".chart.py")
107 # scan directory specified in path and load all modules from there
108 names = os.listdir(path)
110 m = self._import_module(path + mod)
112 debug("loading chart: '" + path + mod + "'")
116 def _load_configs(self,modules):
117 # function loads configuration files to modules
119 configfile = self.configs + mod.__name__ + ".conf"
120 if os.path.isfile(configfile):
121 debug("loading chart options: '" + configfile + "'")
125 self._parse_config(mod,read_config(configfile)))
126 except Exception as e:
127 debug("something went wrong while loading configuration",e)
130 ": configuration file '" +
132 "' not found. Using defaults.")
135 def _parse_config(self,module,config):
138 for key in BASE_CONFIG:
140 # get defaults from module config
141 defaults[key] = int(config.pop(key))
142 except (KeyError,ValueError):
144 # get defaults from module source code
145 defaults[key] = getattr(module, key)
146 except (KeyError,ValueError):
147 # if above failed, get defaults from global dict
148 defaults[key] = BASE_CONFIG[key]
150 # check if there are dict in config dict
153 if type(config[name]) is dict:
157 # assign variables needed by supervisor to every job configuration
161 if key not in config[name]:
162 config[name][key] = defaults[key]
163 # if only one job is needed, values doesn't have to be in dict (in YAML)
165 config = {None: config.copy()}
166 config[None].update(defaults)
168 # return dictionary of jobs where every job has BASE_CONFIG variables
171 def _stop(self, job, reason=None): #FIXME test if Service has __name__
173 self.jobs.remove(job)
176 elif reason[:3] == "no ":
179 "' does not seem to have " +
181 "() function. Disabling it.")
182 elif reason[:7] == "failed ":
184 job.execution_name + "' " +
186 "() function reports failure.")
187 elif reason[:13] == "configuration":
188 debug(job.execution_name,
189 "configuration file '" +
192 ".conf' not found. Using defaults.")
193 elif reason[:11] == "misbehaving":
194 debug(job.execution_name, "is "+reason)
197 # try to execute check() on every job
198 for job in self.jobs:
201 self._stop(job, "failed check")
202 except AttributeError:
203 self._stop(job, "no check")
204 except (UnboundLocalError, Exception) as e:
205 self._stop(job, "misbehaving. Reason: " + str(e))
209 # try to execute create() on every job
210 for job in self.jobs:
213 self._stop(job, "failed create")
215 chart = job.execution_name
217 "CHART netdata.plugin_pythond_" +
219 " '' 'Execution time for " +
221 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
222 str(job.timetable['freq']) +
224 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
226 except AttributeError:
227 self._stop(job, "no create")
228 except (UnboundLocalError, Exception) as e:
229 self._stop(job, "misbehaving. Reason: " + str(e))
232 def _update_job(self, job):
233 # try to execute update() on every job and draw run time graph
234 t_start = time.time()
235 # check if it is time to execute job update() function
236 if job.timetable['next'] > t_start:
242 since_last = int((t_start - job.timetable['last']) * 1000000)
243 if not job.update(since_last):
244 self._stop(job, "update failed")
246 except AttributeError:
247 self._stop(job, "no update")
249 except (UnboundLocalError, Exception) as e:
250 self._stop(job, "misbehaving. Reason: " + str(e))
253 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
254 # draw performance graph
258 dt = int((t_end - job.timetable['last']) * 1000000)
259 sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
260 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
261 sys.stdout.write("END\n")
263 job.timetable['last'] = t_start
264 self.first_run = False
267 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
268 self.first_run = True
270 t_begin = time.time()
272 for job in self.jobs:
273 self._update_job(job)
275 next_runs.append(job.timetable['next'])
278 if len(next_runs) == 0:
279 debug("No plugins loaded")
280 sys.stdout.write("DISABLE\n")
282 time.sleep(min(next_runs) - time.time())
285 def read_config(path):
287 with open(path, 'r') as stream:
288 config = yaml.load(stream)
289 except IsADirectoryError:
290 debug(str(path), "is a directory")
292 except yaml.YAMLError as e:
293 debug(str(path), "is malformed:", e)
301 sys.stderr.write(PROGRAM + ":")
303 sys.stderr.write(" " + str(i))
304 sys.stderr.write("\n")
308 def parse_cmdline(directory, *commands):
309 # TODO number -> interval
315 for cmd in commands[1:]:
318 elif cmd == "debug" or cmd == "all":
320 # redirect stderr to stdout?
321 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
323 mods.append(cmd.replace(".chart.py", ""))
330 debug("started from", commands[0], "with options:", *commands[1:])
331 if len(mods) == 0 and DEBUG_FLAG is False:
334 return {'interval': interval,
338 # if __name__ == '__main__':
340 global DEBUG_FLAG, PROGRAM
342 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
343 # parse env variables
344 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
345 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
346 os.path.abspath(__file__).strip("python.d.plugin.py"))
347 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
348 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
350 # read configuration file
352 if config_dir[-1] != '/':
354 configfile = config_dir + "python.d.conf"
357 conf = read_config(configfile)
359 if str(conf['enable']) is False:
360 debug("disabled in configuration file")
361 sys.stdout.write("DISABLE\n")
363 except (KeyError, TypeError):
366 modules_conf = conf['plugins_config_dir']
368 modules_conf = config_dir + "python.d/" # default configuration directory
370 modules_dir = conf['plugins_dir']
372 modules_dir = main_dir.replace("plugins.d", "python.d")
374 interval = conf['interval']
376 pass # use default interval from NETDATA_UPDATE_EVERY
378 DEBUG_FLAG = conf['debug']
381 for k, v in conf.items():
382 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
386 except FileNotFoundError:
387 modules_conf = config_dir
388 modules_dir = main_dir.replace("plugins.d", "python.d")
390 # directories should end with '/'
391 if modules_dir[-1] != '/':
393 if modules_conf[-1] != '/':
396 # parse passed command line arguments
397 out = parse_cmdline(modules_dir, *sys.argv)
398 modules = out['modules']
399 if out['interval'] is not None:
400 interval = out['interval']
402 # configure environement to run modules
403 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
406 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
411 if __name__ == '__main__':