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