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