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 self.default_priority = 60000
28 # check if plugin directory exists
29 if not os.path.isdir(modules_path):
30 debug("cannot find charts directory ", modules_path)
31 sys.stdout.write("DISABLE\n")
33 self.configs = modules_configs
40 modules_path + m + ".chart.py"))
42 self.load_modules(modules_path)
43 if len(self.modules) == 0:
44 debug("cannot find modules directory", modules_path)
45 sys.stdout.write("DISABLE\n")
50 # set last execution and execution frequency dict
52 for m in self.modules:
54 interval = m.update_every
55 interval = int(interval)
56 except AttributeError:
57 interval = self.interval
59 interval = self.interval
61 ": wrong value of 'update_every' setting to " +
63 # ensure module update frequency is not less than execution of this program
64 if interval < self.interval:
65 interval = self.interval
66 # charts updates are twice as frequent as user specified
67 self.timetable[m.__name__] = [0, interval/2.0]
70 for m in self.modules:
73 m.priority = int(m.priority)
74 except (AttributeError,ValueError):
75 m.priority = self.default_priority
78 def import_plugin(self, path, name=None):
80 name = path.split('/')[-1]
81 if name[-9:] != ".chart.py":
85 return importlib.machinery.SourceFileLoader(name, path).load_module()
86 except Exception as e:
90 def load_modules(self, path):
91 names = os.listdir(path)
93 m = self.import_plugin(path + mod)
95 debug("loading chart: '" + path + mod + "'")
96 self.modules.append(m)
98 def load_configs(self):
99 for m in self.modules:
100 configfile = self.configs + m.__name__ + ".conf"
101 if os.path.isfile(configfile):
102 debug("loading chart options: '" + configfile + "'")
103 for k, v in read_config(configfile).items():
107 ": configuration file '" +
109 "' not found. Using defaults.")
111 def disable_module(self, mod, reason=None):
112 self.modules.remove(mod)
113 del self.timetable[mod.__name__]
116 elif reason[:3] == "no ":
119 "' does not seem to have " +
121 "() function. Disabling it.")
122 elif reason[:7] == "failed ":
126 "() function. reports failure.")
127 elif reason[:13] == "configuration":
129 "configuration file '" +
132 ".conf' not found. Using defaults.")
133 elif reason[:11] == "misbehaving":
134 debug(mod.__name__, "is misbeaving. Disabling it")
137 for mod in self.modules:
140 self.disable_module(mod, "failed check")
141 except AttributeError:
142 self.disable_module(mod, "no check")
143 except UnboundLocalError:
144 self.disable_module(mod, "misbehaving")
147 for mod in self.modules:
150 self.disable_module(mod, "failed create")
154 "CHART netdata.plugin_pythond_" +
156 " '' 'Execution time for " +
158 " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
159 str(self.timetable[mod.__name__][1]) +
161 sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
163 except AttributeError:
164 self.disable_module(mod, "no create")
165 except UnboundLocalError:
166 self.disable_module(mod, "misbehaving")
168 def update_module(self, mod):
170 # check if it is time to execute module update() function
171 if (t1 - self.timetable[mod.__name__][0]) < self.timetable[mod.__name__][1]:
174 if not self.first_run:
177 t=int((t1- self.timetable[mod.__name__][0]) * 1000000)
178 if not mod.update(t):
179 self.disable_module(mod, "update failed")
181 except AttributeError:
182 self.disable_module(mod, "no update")
184 except UnboundLocalError:
185 self.disable_module(mod, "misbehaving")
191 dt = int((t2 - self.timetable[mod.__name__][0]) * 1000000)
192 sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(dt)+'\n')
193 sys.stdout.write("SET run_time = " + str(int((t2 - t1) * 1000)) + '\n')
194 sys.stdout.write("END\n")
196 self.timetable[mod.__name__][0] = t1
200 t_begin = time.time()
201 for mod in self.modules:
202 self.update_module(mod)
203 time.sleep((self.interval - (time.time() - t_begin)) / 2)
204 self.first_run = False
207 def read_config(path):
208 config = configparser.ConfigParser()
211 with open(path, 'r', encoding="utf_8") as f:
212 config_str = '[config]\n' + f.read()
213 except IsADirectoryError:
214 debug(str(path), "is a directory")
216 config.read_string(config_str)
217 return dict(config.items('config'))
223 sys.stderr.write(PROGRAM + ":")
225 sys.stderr.write(" " + str(i))
226 sys.stderr.write("\n")
230 def parse_cmdline(directory, *commands):
231 # TODO number -> interval
237 for cmd in commands[1:]:
240 elif cmd == "debug" or cmd == "all":
242 # redirect stderr to stdout?
243 elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
245 mods.append(cmd.replace(".chart.py", ""))
252 debug("started from", commands[0], "with options:", *commands[1:])
254 return {'interval': interval,
258 # if __name__ == '__main__':
260 global DEBUG_FLAG, PROGRAM
262 PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
263 # parse env variables
264 # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
265 main_dir = os.getenv('NETDATA_PLUGINS_DIR',
266 os.path.abspath(__file__).strip("python.d.plugin.py"))
267 config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
268 interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
270 # read configuration file
271 if config_dir[-1] != '/':
272 configfile = config_dir + '/' + "python.d.conf"
274 configfile = config_dir + "python.d.conf"
277 conf = read_config(configfile)
279 if str(conf['enable']) == "no":
280 debug("disabled in configuration file")
281 sys.stdout.write("DISABLE\n")
283 except (KeyError, TypeError):
286 modules_conf = conf['plugins_config_dir']
287 except (KeyError, TypeError):
288 modules_conf = config_dir # default configuration directory
290 modules_dir = conf['plugins_dir']
291 except (KeyError, TypeError):
292 modules_dir = main_dir.replace("plugins.d", "python.d")
294 interval = int(conf['interval'])
295 except (KeyError, TypeError):
296 pass # default interval
298 DEBUG_FLAG = bool(conf['debug'])
299 except (KeyError, TypeError):
301 except FileNotFoundError:
302 modules_conf = config_dir
303 modules_dir = main_dir.replace("plugins.d", "python.d")
305 # directories should end with '/'
306 if modules_dir[-1] != '/':
308 if modules_conf[-1] != '/':
311 # parse passed command line arguments
312 out = parse_cmdline(modules_dir, *sys.argv)
313 modules = out['modules']
314 if out['interval'] is not None:
315 interval = out['interval']
318 charts = PythonCharts(interval, modules, modules_dir, modules_conf)
323 if __name__ == '__main__':