7 #import importlib.machinery
9 assert sys.version_info >= (3,1)
11 import importlib.machinery
12 except AssertionError:
13 sys.stderr.write('Not supported python version. Needed python >= 3.1\n')
14 sys.stdout.write('DISABLE\n')
18 class PythonCharts(object):
23 modules_path='../python.d/',
24 modules_configs='../conf.d/'):
26 self.interval = interval
27 # check if plugin directory exists
28 if not os.path.isdir(modules_path):
29 debug("cannot find charts directory ", modules_path)
30 sys.stdout.write("DISABLE\n")
32 self.configs = modules_configs
39 modules_path + m + ".chart.py"))
41 self.load_modules(modules_path)
42 if len(self.modules) == 0:
43 debug("cannot find modules directory", modules_path)
44 sys.stdout.write("DISABLE\n")
49 # set last execution and execution frequency dict
51 for m in self.modules:
53 interval = m.update_every
54 interval = int(interval)
55 except AttributeError:
56 interval = self.interval
58 interval = self.interval
60 ": wrong value of 'update_every' setting to " +
62 # ensure module update frequency is not less than execution of this program
63 if interval < self.interval:
64 interval = self.interval
65 # charts updates are twice as frequent as user specified
66 self.timetable[m.__name__] = [0, interval/2.0]
68 def import_plugin(self, path, name=None):
70 name = path.split('/')[-1]
71 if name[-9:] != ".chart.py":
75 return importlib.machinery.SourceFileLoader(name, path).load_module()
76 except Exception as e:
80 def load_modules(self, path):
81 names = os.listdir(path)
83 m = self.import_plugin(path + mod)
85 debug("loading chart: '" + path + mod + "'")
86 self.modules.append(m)
88 def load_configs(self):
89 for m in self.modules:
90 configfile = self.configs + m.__name__ + ".conf"
91 if os.path.isfile(configfile):
92 debug("loading chart options: '" + configfile + "'")
93 for k, v in read_config(configfile).items():
97 ": configuration file '" +
99 "' not found. Using defaults.")
101 def disable_module(self, mod, reason=None):
102 self.modules.remove(mod)
103 del self.timetable[mod.__name__]
106 elif reason[:3] == "no ":
109 "' does not seem to have " +
111 "() function. Disabling it.")
112 elif reason[:7] == "failed ":
116 "() function. reports failure.")
117 elif reason[:13] == "configuration":
119 "configuration file '" +
122 ".conf' not found. Using defaults.")
123 elif reason[:11] == "misbehaving":
124 debug(mod.__name__, "is misbeaving. Disabling it")
127 for mod in self.modules:
130 self.disable_module(mod, "failed check")
131 except AttributeError:
132 self.disable_module(mod, "no check")
133 except UnboundLocalError:
134 self.disable_module(mod, "misbehaving")
137 for mod in self.modules:
140 self.disable_module(mod, "failed create")
144 "CHART netdata.plugin_pythond_" +
146 " '' 'Execution time for " +
148 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
149 str(self.timetable[mod.__name__][1]) +
151 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
153 except AttributeError:
154 self.disable_module(mod, "no create")
155 except UnboundLocalError:
156 self.disable_module(mod, "misbehaving")
158 def update_module(self, mod):
160 # check if it is time to execute module update() function
161 if (t1 - self.timetable[mod.__name__][0]) < self.timetable[mod.__name__][1]:
164 if not self.first_run:
167 t=int((t1- self.timetable[mod.__name__][0]) * 1000000)
168 if not mod.update(t):
169 self.disable_module(mod, "update failed")
171 except AttributeError:
172 self.disable_module(mod, "no update")
174 except UnboundLocalError:
175 self.disable_module(mod, "misbehaving")
181 dt = int((t2 - self.timetable[mod.__name__][0]) * 1000000)
182 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(dt)+'\n')
183 sys.stdout.write("SET run_time = " + str(int((t2 - t1) * 1000)) + '\n')
184 sys.stdout.write("END\n")
186 self.timetable[mod.__name__][0] = t1
190 t_begin = time.time()
191 for mod in self.modules:
192 self.update_module(mod)
193 time.sleep((self.interval - (time.time() - t_begin)) / 2)
194 self.first_run = False
197 def read_config(path):
198 config = configparser.ConfigParser()
201 with open(path, 'r', encoding="utf_8") as f:
202 config_str = '[config]\n' + f.read()
203 except IsADirectoryError:
204 debug(str(path), "is a directory")
206 config.read_string(config_str)
207 return dict(config.items('config'))
213 sys.stderr.write(PROGRAM + ":")
215 sys.stderr.write(" " + str(i))
216 sys.stderr.write("\n")
220 def parse_cmdline(directory, *commands):
221 # TODO number -> interval
227 for cmd in commands[1:]:
230 elif cmd == "debug" or cmd == "all":
232 # redirect stderr to stdout?
233 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
235 mods.append(cmd.replace(".chart.py", ""))
242 debug("started from", commands[0], "with options:", *commands[1:])
244 return {'interval': interval,
248 # if __name__ == '__main__':
250 global DEBUG_FLAG, PROGRAM
252 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
253 # parse env variables
254 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
255 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
256 os.path.abspath(__file__).strip("python.d.plugin.py"))
257 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
258 interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
260 # read configuration file
261 if config_dir[-1] != '/':
262 configfile = config_dir + '/' + "python.d.conf"
264 configfile = config_dir + "python.d.conf"
267 conf = read_config(configfile)
269 if str(conf['enable']) == "no":
270 debug("disabled in configuration file")
271 sys.stdout.write("DISABLE\n")
273 except (KeyError, TypeError):
276 modules_conf = conf['plugins_config_dir']
277 except (KeyError, TypeError):
278 modules_conf = config_dir # default configuration directory
280 modules_dir = conf['plugins_dir']
281 except (KeyError, TypeError):
282 modules_dir = main_dir.replace("plugins.d", "python.d")
284 interval = int(conf['interval'])
285 except (KeyError, TypeError):
286 pass # default interval
288 DEBUG_FLAG = bool(conf['debug'])
289 except (KeyError, TypeError):
291 except FileNotFoundError:
292 modules_conf = config_dir
293 modules_dir = main_dir.replace("plugins.d", "python.d")
295 # directories should end with '/'
296 if modules_dir[-1] != '/':
298 if modules_conf[-1] != '/':
301 # parse passed command line arguments
302 out = parse_cmdline(modules_dir, *sys.argv)
303 modules = out['modules']
304 if out['interval'] is not None:
305 interval = out['interval']
308 charts = PythonCharts(interval, modules, modules_dir, modules_conf)
313 if __name__ == '__main__':