]> arthur.barton.de Git - netdata.git/blob - plugins.d/python.d.plugin
350e56790a2cb15b6c51669b686f3b1bb6fdc99d
[netdata.git] / plugins.d / python.d.plugin
1 #!/usr/bin/python3 -u
2
3 import os
4 import sys
5 import time
6 try:
7     assert sys.version_info >= (3,1)
8     import configparser
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')
13     sys.exit(1)
14
15
16 class PythonCharts(object):
17     
18     def __init__(self,
19                  interval=None,
20                  modules=[],
21                  modules_path='../python.d/',
22                  modules_configs='../conf.d/',
23                  modules_disabled=[]):
24         self.first_run = True
25         if interval is None:
26             interval = 1
27         self.default_priority = 90000
28         # set configuration directory
29         self.configs = modules_configs
30
31         # load modules
32         self.modules = self._load_modules(modules_path,modules)
33         
34         # check if loaded modules are on disabled modules list
35         for mod in self.modules:
36             if mod.__name__ in modules_disabled:
37                 self.modules.remove(mod)
38         
39         # load configuration files
40         self._load_configs()
41
42         # set timetable dict (last execution, next execution and frequency)
43         # set priorities
44         self.timetable = {}
45         for m in self.modules:
46             try:
47                 m.priority = int(m.priority)
48             except (AttributeError,ValueError):
49                 m.priority = self.default_priority
50              
51             if interval is None:
52                 try:
53                     interval = int(m.update_every)
54                 except (AttributeError, ValueError):
55                     interval = 1
56             
57             now = time.time()
58             self.timetable[m.__name__] = {'last' : now,
59                                           'next' : now - (now % interval) + interval,
60                                           'freq' : interval}
61
62     def _import_plugin(self, path, name=None):
63     # try to import module using only its path
64         if name is None:
65             name = path.split('/')[-1]
66             if name[-9:] != ".chart.py":
67                 return None
68             name = name[:-9]
69         try:
70             return importlib.machinery.SourceFileLoader(name, path).load_module()
71         except Exception as e:
72             debug(str(e))
73             return None
74
75     def _load_modules(self, path, modules):
76         # check if plugin directory exists
77         if not os.path.isdir(path):
78             debug("cannot find charts directory ", path)
79             sys.stdout.write("DISABLE\n")
80             sys.exit(1)
81
82         # load modules
83         loaded = []
84         if len(modules) > 0:
85             for m in modules:
86                 mod = self._import_plugin(path + m + ".chart.py")
87                 if mod is not None:
88                     loaded.append(mod)
89         else:
90             # scan directory specified in path and load all modules from there
91             names = os.listdir(path)
92             for mod in names:
93                 m = self._import_plugin(path + mod)
94                 if m is not None:
95                     debug("loading chart: '" + path + mod + "'")
96                     loaded.append(m)
97         return loaded
98
99     def _load_configs(self):
100     # function modifies every loaded module in self.modules
101         for m in self.modules:
102             configfile = self.configs + m.__name__ + ".conf"
103             if os.path.isfile(configfile):
104                 debug("loading chart options: '" + configfile + "'")
105                 for k, v in read_config(configfile).items():
106                     setattr(m, k, v)
107             else:
108                 debug(m.__name__ +
109                       ": configuration file '" +
110                       configfile +
111                       "' not found. Using defaults.")
112
113     def _disable_module(self, mod, reason=None):
114     # modifies self.modules
115         self.modules.remove(mod)
116         del self.timetable[mod.__name__]
117         if reason is None:
118             return
119         elif reason[:3] == "no ":
120             debug("chart '" +
121                   mod.__name__,
122                   "' does not seem to have " +
123                   reason[3:] +
124                   "() function. Disabling it.")
125         elif reason[:7] == "failed ":
126             debug("chart '" +
127                   mod.__name__ +
128                   reason[3:] +
129                   "() function. reports failure.")
130         elif reason[:13] == "configuration":
131             debug(mod.__name__,
132                   "configuration file '" +
133                   self.configs +
134                   mod.__name__ +
135                   ".conf' not found. Using defaults.")
136         elif reason[:11] == "misbehaving":
137             debug(mod.__name__, "is "+reason)
138
139     def check(self):
140     # try to execute check() on every loaded module
141         for mod in self.modules:
142             try:
143                 if not mod.check():
144                     self._disable_module(mod, "failed check")
145             except AttributeError:
146                 self._disable_module(mod, "no check")
147             except (UnboundLocalError, Exception) as e:
148                 self._disable_module(mod, "misbehaving. Reason: " + str(e))
149
150     def create(self):
151     # try to execute create() on every loaded module
152         for mod in self.modules:
153             try:
154                 if not mod.create():
155                     self._disable_module(mod, "failed create")
156                 else:
157                     chart = mod.__name__
158                     sys.stdout.write(
159                         "CHART netdata.plugin_pythond_" +
160                         chart +
161                         " '' 'Execution time for " +
162                         chart +
163                         " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
164                         str(self.timetable[mod.__name__]['freq']) +
165                         '\n')
166                     sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
167                     sys.stdout.flush()
168             except AttributeError:
169                 self._disable_module(mod, "no create")
170             except (UnboundLocalError, Exception) as e:
171                 self._disable_module(mod, "misbehaving. Reason: " + str(e))
172
173     def _update_module(self, mod):
174     # try to execute update() on every module and draw run time graph 
175         t_start = time.time()
176         # check if it is time to execute module update() function
177         if self.timetable[mod.__name__]['next'] > t_start:
178             return
179         try:
180             if self.first_run:
181                 since_last = 0
182             else:
183                 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
184             if not mod.update(since_last):
185                 self._disable_module(mod, "update failed")
186                 return
187         except AttributeError:
188             self._disable_module(mod, "no update")
189             return
190         except (UnboundLocalError, Exception) as e:
191             self._disable_module(mod, "misbehaving. Reason: " + str(e))
192             return
193         t_end = time.time()
194         self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
195         # draw performance graph
196         if self.first_run:
197             dt = 0
198         else:
199             dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
200         sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
201         sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
202         sys.stdout.write("END\n")
203         sys.stdout.flush()
204         self.timetable[mod.__name__]['last'] = t_start
205         self.first_run = False
206
207     def update(self):
208     # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
209         self.first_run = True
210         while True:
211             t_begin = time.time()
212             next_runs = []
213             for mod in self.modules:
214                 self._update_module(mod)
215                 try:
216                     next_runs.append(self.timetable[mod.__name__]['next'])
217                 except KeyError:
218                     pass
219             if len(next_runs) == 0:
220                 debug("No plugins loaded")
221                 sys.stdout.write("DISABLE\n")
222                 sys.exit(1)
223             time.sleep(min(next_runs) - time.time())
224
225
226 def read_config(path):
227     config = configparser.ConfigParser()
228     config_str = ""
229     try:
230         with open(path, 'r', encoding="utf_8") as f:
231             config_str = '[config]\n' + f.read()
232     except IsADirectoryError:
233         debug(str(path), "is a directory")
234         return
235     try:
236         config.read_string(config_str)
237     except configparser.ParsingError as e:
238         debug("Malformed configuration file: "+str(e))
239         return
240     return dict(config.items('config'))
241
242
243 def debug(*args):
244     if not DEBUG_FLAG:
245         return
246     sys.stderr.write(PROGRAM + ":")
247     for i in args:
248         sys.stderr.write(" " + str(i))
249     sys.stderr.write("\n")
250     sys.stderr.flush()
251
252
253 def parse_cmdline(directory, *commands):
254     # TODO number -> interval
255     global DEBUG_FLAG
256     DEBUG_FLAG = False
257     interval = None
258
259     mods = []
260     for cmd in commands[1:]:
261         if cmd == "check":
262             pass
263         elif cmd == "debug" or cmd == "all":
264             DEBUG_FLAG = True
265             # redirect stderr to stdout?
266         elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
267             DEBUG_FLAG = True
268             mods.append(cmd.replace(".chart.py", ""))
269         else:
270             try:
271                 interval = int(cmd)
272             except ValueError:
273                 pass
274
275     debug("started from", commands[0], "with options:", *commands[1:])
276
277     return {'interval': interval,
278             'modules': mods}
279
280
281 # if __name__ == '__main__':
282 def run():
283     global DEBUG_FLAG, PROGRAM
284     DEBUG_FLAG = True
285     PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
286     # parse env variables
287     # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
288     main_dir = os.getenv('NETDATA_PLUGINS_DIR',
289                          os.path.abspath(__file__).strip("python.d.plugin.py"))
290     config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
291     interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
292
293     # read configuration file
294     disabled = []
295     if config_dir[-1] != '/':
296         configfile = config_dir + '/' + "python.d.conf"
297     else:
298         configfile = config_dir + "python.d.conf"
299
300     try:
301         conf = read_config(configfile)
302         try:
303             if str(conf['enable']) == "no":
304                 debug("disabled in configuration file")
305                 sys.stdout.write("DISABLE\n")
306                 sys.exit(1)
307         except (KeyError, TypeError):
308             pass
309         try:
310             modules_conf = conf['plugins_config_dir']
311         except (KeyError):
312             modules_conf = config_dir + "python.d/"  # default configuration directory
313         try:
314             modules_dir = conf['plugins_dir']
315         except (KeyError):
316             modules_dir = main_dir.replace("plugins.d", "python.d")
317         try:
318             interval = int(conf['interval'])
319         except (KeyError, TypeError):
320             pass  # use default interval from NETDATA_UPDATE_EVERY
321         try:
322             DEBUG_FLAG = bool(conf['debug'])
323         except (KeyError, TypeError):
324             pass
325         for k, v in conf.items():
326             if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
327                 continue
328             if v == 'no':
329                 disabled.append(k)
330     except FileNotFoundError:
331         modules_conf = config_dir
332         modules_dir = main_dir.replace("plugins.d", "python.d")
333
334     # directories should end with '/'
335     if modules_dir[-1] != '/':
336         modules_dir += "/"
337     if modules_conf[-1] != '/':
338         modules_conf += "/"
339
340     # parse passed command line arguments
341     out = parse_cmdline(modules_dir, *sys.argv)
342     modules = out['modules']
343     if out['interval'] is not None:
344         interval = out['interval']
345     
346     # configure environement to run modules
347     sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
348     
349     # run plugins
350     charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
351     charts.check()
352     charts.create()
353     charts.update()
354
355 if __name__ == '__main__':
356     run()