]> arthur.barton.de Git - netdata.git/blob - plugins.d/python.d.plugin
Merge pull request #555 from paulfantom/master
[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         self.default_priority = 90000
26         # set configuration directory
27         self.configs = modules_configs
28
29         # load modules
30         modules = self._load_modules(modules_path,modules)
31         
32         # check if loaded modules are on disabled modules list
33         self.modules = [ m for m in modules if m.__name__ not in modules_disabled ]
34         
35         # load configuration files
36         self._load_configs()
37
38         # set timetable dict (last execution, next execution and frequency)
39         # set priorities
40         self.timetable = {}
41         freq = 1
42         for m in self.modules:
43             try:
44                 m.priority = int(m.priority)
45             except (AttributeError,ValueError):
46                 m.priority = self.default_priority
47              
48             if interval is None:
49                 try:
50                     freq = int(m.update_every)
51                 except (AttributeError, ValueError):
52                     freq = 1
53             
54             now = time.time()
55             self.timetable[m.__name__] = {'last' : now,
56                                           'next' : now - (now % freq) + freq,
57                                           'freq' : freq}
58
59     def _import_plugin(self, path, name=None):
60     # try to import module using only its path
61         if name is None:
62             name = path.split('/')[-1]
63             if name[-9:] != ".chart.py":
64                 return None
65             name = name[:-9]
66         try:
67             return importlib.machinery.SourceFileLoader(name, path).load_module()
68         except Exception as e:
69             debug(str(e))
70             return None
71
72     def _load_modules(self, path, modules):
73         # check if plugin directory exists
74         if not os.path.isdir(path):
75             debug("cannot find charts directory ", path)
76             sys.stdout.write("DISABLE\n")
77             sys.exit(1)
78
79         # load modules
80         loaded = []
81         if len(modules) > 0:
82             for m in modules:
83                 mod = self._import_plugin(path + m + ".chart.py")
84                 if mod is not None:
85                     loaded.append(mod)
86         else:
87             # scan directory specified in path and load all modules from there
88             names = os.listdir(path)
89             for mod in names:
90                 m = self._import_plugin(path + mod)
91                 if m is not None:
92                     debug("loading chart: '" + path + mod + "'")
93                     loaded.append(m)
94         return loaded
95
96     def _load_configs(self):
97     # function modifies every loaded module in self.modules
98         for m in self.modules:
99             configfile = self.configs + m.__name__ + ".conf"
100             if os.path.isfile(configfile):
101                 debug("loading chart options: '" + configfile + "'")
102                 for k, v in read_config(configfile).items():
103                     try:
104                         setattr(m, k, v)
105                     except AttributeError:
106                         self._disable_module(m,"misbehaving having bad configuration")
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[7:] +
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     if len(mods) == 0 and DEBUG_FLAG is False:
277         interval = None
278
279     return {'interval': interval,
280             'modules': mods}
281
282
283 # if __name__ == '__main__':
284 def run():
285     global DEBUG_FLAG, PROGRAM
286     DEBUG_FLAG = True
287     PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
288     # parse env variables
289     # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
290     main_dir = os.getenv('NETDATA_PLUGINS_DIR',
291                          os.path.abspath(__file__).strip("python.d.plugin.py"))
292     config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
293     interval = os.getenv('NETDATA_UPDATE_EVERY', None)
294
295     # read configuration file
296     disabled = []
297     if config_dir[-1] != '/':
298         config_dir += '/'
299     configfile = config_dir + "python.d.conf"
300
301     try:
302         conf = read_config(configfile)
303         try:
304             if str(conf['enable']) == "no":
305                 debug("disabled in configuration file")
306                 sys.stdout.write("DISABLE\n")
307                 sys.exit(1)
308         except (KeyError, TypeError):
309             pass
310         try:
311             modules_conf = conf['plugins_config_dir']
312         except (KeyError):
313             modules_conf = config_dir + "python.d/"  # default configuration directory
314         try:
315             modules_dir = conf['plugins_dir']
316         except (KeyError):
317             modules_dir = main_dir.replace("plugins.d", "python.d")
318         try:
319             interval = int(conf['interval'])
320         except (KeyError, TypeError):
321             pass  # use default interval from NETDATA_UPDATE_EVERY
322         try:
323             DEBUG_FLAG = bool(conf['debug'])
324         except (KeyError, TypeError):
325             pass
326         for k, v in conf.items():
327             if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
328                 continue
329             if v == 'no':
330                 disabled.append(k)
331     except FileNotFoundError:
332         modules_conf = config_dir
333         modules_dir = main_dir.replace("plugins.d", "python.d")
334
335     # directories should end with '/'
336     if modules_dir[-1] != '/':
337         modules_dir += "/"
338     if modules_conf[-1] != '/':
339         modules_conf += "/"
340
341     # parse passed command line arguments
342     out = parse_cmdline(modules_dir, *sys.argv)
343     modules = out['modules']
344     if out['interval'] is not None:
345         interval = out['interval']
346     
347     # configure environement to run modules
348     sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
349     
350     # run plugins
351     charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
352     charts.check()
353     charts.create()
354     charts.update()
355
356 if __name__ == '__main__':
357     run()