8 assert sys.version_info >= (3,1)
9 import importlib.machinery
10 except AssertionError:
11 sys.stderr.write('Not supported python version. Needed python >= 3.1\n')
12 sys.stdout.write('DISABLE\n')
16 class PythonCharts(object):
21 modules_path='../python.d/',
22 modules_configs='../conf.d/',
25 # set configuration directory
26 self.configs = modules_configs
29 modules = self._load_modules(modules_path,modules)
31 # check if loaded modules are on disabled modules list
32 self.modules = [ m for m in modules if m.__name__ not in modules_disabled ]
34 # load configuration files
37 # good economy and prosperity:
38 self.jobs = self._create_jobs(self.modules)
41 def _create_jobs(self,modules):
42 # module store a definition of Service class
43 # module store configuration in module.config
44 # configs are list of dicts or a dict
45 # one dict is one service
46 # iterate over list of modules and inside one loop iterate over configs
48 for module in modules:
49 if type(module.config) is dict:
50 jobs.append(self._job(module,module.config))
51 elif type(module.config) is list:
52 for conf in module.config:
53 jobs.append(self._job(module,conf))
55 return [j for j in jobs if j is not None]
58 def _job(self,module,conf):
60 # default job settings:
61 settings = {'update_every' : 11,
64 # ensure job has basic variables
65 # first check in job config
66 # next check in module
67 # at last assign defaults
70 settings[key] = int(conf[key])
71 except (KeyError,ValueError):
73 settings[key] = int(getattr(module, key))
74 except (AttributeError,ValueError):
78 job = module.Service(configuration=conf)
79 except Exception as e:
80 sys.stderr.write(module.__name__ +
81 ": Couldn't start one of jobs " +
85 # set execution_name (needed to plot run time graphs)
87 job.execution_name = module.__name__ + \
91 job.execution_name = module.__name__
93 def _import_module(self, path, name=None):
94 # try to import module using only its path
96 name = path.split('/')[-1]
97 if name[-9:] != ".chart.py":
101 return importlib.machinery.SourceFileLoader(name, path).load_module()
102 except Exception as e:
106 def _load_modules(self, path, modules):
107 # check if plugin directory exists
108 if not os.path.isdir(path):
109 debug("cannot find charts directory ", path)
110 sys.stdout.write("DISABLE\n")
117 mod = self._import_module(path + m + ".chart.py")
121 # scan directory specified in path and load all modules from there
122 names = os.listdir(path)
124 m = self._import_module(path + mod)
126 debug("loading chart: '" + path + mod + "'")
130 def _load_configs(self):
131 # function modifies every loaded module in self.modules
132 for m in self.modules:
133 configfile = self.configs + m.__name__ + ".conf"
134 if os.path.isfile(configfile):
135 debug("loading chart options: '" + configfile + "'")
136 for k, v in read_config(configfile).items():
139 except AttributeError:
140 self._disable_module(m,"misbehaving having bad configuration")
143 ": configuration file '" +
145 "' not found. Using defaults.")
147 def _stop(self, job, reason=None): #FIXME test if Service has __name__
149 self.jobs.remove(job)
152 elif reason[:3] == "no ":
155 "' does not seem to have " +
157 "() function. Disabling it.")
158 elif reason[:7] == "failed ":
160 job.__name__ + "' " +
162 "() function reports failure.")
163 elif reason[:13] == "configuration":
165 "configuration file '" +
168 ".conf' not found. Using defaults.")
169 elif reason[:11] == "misbehaving":
170 debug(job.__name__, "is "+reason)
173 # try to execute check() on every job
174 for job in self.jobs:
177 self._stop(job, "failed check")
178 except AttributeError:
179 self._stop(job, "no check")
180 except (UnboundLocalError, Exception) as e:
181 self._stop(job, "misbehaving. Reason: " + str(e))
184 # try to execute create() on every job
185 for job in self.jobs:
188 self._stop(job, "failed create")
190 chart = job.execution_name
192 "CHART netdata.plugin_pythond_" +
194 " '' 'Execution time for " +
196 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
197 str(job.timetable['freq']) +
199 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
201 except AttributeError:
202 self._stop(job, "no create")
203 except (UnboundLocalError, Exception) as e:
204 self._stop(job, "misbehaving. Reason: " + str(e))
206 def _update_job(self, job):
207 # try to execute update() on every job and draw run time graph
208 t_start = time.time()
209 # check if it is time to execute job update() function
210 if job.timetable['next'] > t_start:
216 since_last = int((t_start - job.timetable['last']) * 1000000)
217 if not job.update(since_last):
218 self._stop(job, "update failed")
220 except AttributeError:
221 self._stop(job, "no update")
223 except (UnboundLocalError, Exception) as e:
224 self._stop(job, "misbehaving. Reason: " + str(e))
227 job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
228 # draw performance graph
232 dt = int((t_end - job.timetable['last']) * 1000000)
233 sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
234 sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
235 sys.stdout.write("END\n")
237 job.timetable['last'] = t_start
238 self.first_run = False
241 # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
242 self.first_run = True
244 t_begin = time.time()
246 for job in self.jobs:
247 self._update_job(job)
249 next_runs.append(job.timetable['next'])
252 if len(next_runs) == 0:
253 debug("No plugins loaded")
254 sys.stdout.write("DISABLE\n")
256 time.sleep(min(next_runs) - time.time())
259 def read_config(path):
260 # FIXME move to JSON configurations
262 # with open(path, 'r') as f:
263 # config_str = '[config]\n' + f.read()
264 # except IsADirectoryError:
265 # debug(str(path), "is a directory")
268 # debug("Malformed configuration file: "+str(e))
276 sys.stderr.write(PROGRAM + ":")
278 sys.stderr.write(" " + str(i))
279 sys.stderr.write("\n")
283 def parse_cmdline(directory, *commands):
284 # TODO number -> interval
290 for cmd in commands[1:]:
293 elif cmd == "debug" or cmd == "all":
295 # redirect stderr to stdout?
296 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
298 mods.append(cmd.replace(".chart.py", ""))
305 debug("started from", commands[0], "with options:", *commands[1:])
306 if len(mods) == 0 and DEBUG_FLAG is False:
309 return {'interval': interval,
313 # if __name__ == '__main__':
315 global DEBUG_FLAG, PROGRAM
317 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
318 # parse env variables
319 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
320 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
321 os.path.abspath(__file__).strip("python.d.plugin.py"))
322 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
323 interval = os.getenv('NETDATA_UPDATE_EVERY', None)
325 # read configuration file
327 if config_dir[-1] != '/':
329 configfile = config_dir + "python.d.conf"
332 conf = read_config(configfile)
334 if str(conf['enable']) == "no":
335 debug("disabled in configuration file")
336 sys.stdout.write("DISABLE\n")
338 except (KeyError, TypeError):
341 modules_conf = conf['plugins_config_dir']
343 modules_conf = config_dir + "python.d/" # default configuration directory
345 modules_dir = conf['plugins_dir']
347 modules_dir = main_dir.replace("plugins.d", "python.d")
349 interval = int(conf['interval'])
350 except (KeyError, TypeError):
351 pass # use default interval from NETDATA_UPDATE_EVERY
353 DEBUG_FLAG = bool(conf['debug'])
354 except (KeyError, TypeError):
356 for k, v in conf.items():
357 if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
361 except FileNotFoundError:
362 modules_conf = config_dir
363 modules_dir = main_dir.replace("plugins.d", "python.d")
365 # directories should end with '/'
366 if modules_dir[-1] != '/':
368 if modules_conf[-1] != '/':
371 # parse passed command line arguments
372 out = parse_cmdline(modules_dir, *sys.argv)
373 modules = out['modules']
374 if out['interval'] is not None:
375 interval = out['interval']
377 # configure environement to run modules
378 sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
381 charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
386 if __name__ == '__main__':