]> arthur.barton.de Git - netdata.git/blob - plugins.d/python.d.plugin
preserve configs across installaitons
[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                     setattr(m, k, v)
104             else:
105                 debug(m.__name__ +
106                       ": configuration file '" +
107                       configfile +
108                       "' not found. Using defaults.")
109
110     def _disable_module(self, mod, reason=None):
111     # modifies self.modules
112         self.modules.remove(mod)
113         del self.timetable[mod.__name__]
114         if reason is None:
115             return
116         elif reason[:3] == "no ":
117             debug("chart '" +
118                   mod.__name__,
119                   "' does not seem to have " +
120                   reason[3:] +
121                   "() function. Disabling it.")
122         elif reason[:7] == "failed ":
123             debug("chart '" +
124                   mod.__name__ + "' " +
125                   reason[7:] +
126                   "() function reports failure.")
127         elif reason[:13] == "configuration":
128             debug(mod.__name__,
129                   "configuration file '" +
130                   self.configs +
131                   mod.__name__ +
132                   ".conf' not found. Using defaults.")
133         elif reason[:11] == "misbehaving":
134             debug(mod.__name__, "is "+reason)
135
136     def check(self):
137     # try to execute check() on every loaded module
138         for mod in self.modules:
139             try:
140                 if not mod.check():
141                     self._disable_module(mod, "failed check")
142             except AttributeError:
143                 self._disable_module(mod, "no check")
144             except (UnboundLocalError, Exception) as e:
145                 self._disable_module(mod, "misbehaving. Reason: " + str(e))
146
147     def create(self):
148     # try to execute create() on every loaded module
149         for mod in self.modules:
150             try:
151                 if not mod.create():
152                     self._disable_module(mod, "failed create")
153                 else:
154                     chart = mod.__name__
155                     sys.stdout.write(
156                         "CHART netdata.plugin_pythond_" +
157                         chart +
158                         " '' 'Execution time for " +
159                         chart +
160                         " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
161                         str(self.timetable[mod.__name__]['freq']) +
162                         '\n')
163                     sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
164                     sys.stdout.flush()
165             except AttributeError:
166                 self._disable_module(mod, "no create")
167             except (UnboundLocalError, Exception) as e:
168                 self._disable_module(mod, "misbehaving. Reason: " + str(e))
169
170     def _update_module(self, mod):
171     # try to execute update() on every module and draw run time graph 
172         t_start = time.time()
173         # check if it is time to execute module update() function
174         if self.timetable[mod.__name__]['next'] > t_start:
175             return
176         try:
177             if self.first_run:
178                 since_last = 0
179             else:
180                 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
181             if not mod.update(since_last):
182                 self._disable_module(mod, "update failed")
183                 return
184         except AttributeError:
185             self._disable_module(mod, "no update")
186             return
187         except (UnboundLocalError, Exception) as e:
188             self._disable_module(mod, "misbehaving. Reason: " + str(e))
189             return
190         t_end = time.time()
191         self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
192         # draw performance graph
193         if self.first_run:
194             dt = 0
195         else:
196             dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
197         sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
198         sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
199         sys.stdout.write("END\n")
200         sys.stdout.flush()
201         self.timetable[mod.__name__]['last'] = t_start
202         self.first_run = False
203
204     def update(self):
205     # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
206         self.first_run = True
207         while True:
208             t_begin = time.time()
209             next_runs = []
210             for mod in self.modules:
211                 self._update_module(mod)
212                 try:
213                     next_runs.append(self.timetable[mod.__name__]['next'])
214                 except KeyError:
215                     pass
216             if len(next_runs) == 0:
217                 debug("No plugins loaded")
218                 sys.stdout.write("DISABLE\n")
219                 sys.exit(1)
220             time.sleep(min(next_runs) - time.time())
221
222
223 def read_config(path):
224     config = configparser.ConfigParser()
225     config_str = ""
226     try:
227         with open(path, 'r', encoding="utf_8") as f:
228             config_str = '[config]\n' + f.read()
229     except IsADirectoryError:
230         debug(str(path), "is a directory")
231         return
232     try:
233         config.read_string(config_str)
234     except configparser.ParsingError as e:
235         debug("Malformed configuration file: "+str(e))
236         return
237     return dict(config.items('config'))
238
239
240 def debug(*args):
241     if not DEBUG_FLAG:
242         return
243     sys.stderr.write(PROGRAM + ":")
244     for i in args:
245         sys.stderr.write(" " + str(i))
246     sys.stderr.write("\n")
247     sys.stderr.flush()
248
249
250 def parse_cmdline(directory, *commands):
251     # TODO number -> interval
252     global DEBUG_FLAG
253     DEBUG_FLAG = False
254     interval = None
255
256     mods = []
257     for cmd in commands[1:]:
258         if cmd == "check":
259             pass
260         elif cmd == "debug" or cmd == "all":
261             DEBUG_FLAG = True
262             # redirect stderr to stdout?
263         elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
264             DEBUG_FLAG = True
265             mods.append(cmd.replace(".chart.py", ""))
266         else:
267             try:
268                 interval = int(cmd)
269             except ValueError:
270                 pass
271
272     debug("started from", commands[0], "with options:", *commands[1:])
273     if len(mods) == 0 and DEBUG_FLAG is False:
274         interval = None
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         config_dir += '/'
296     configfile = config_dir + "python.d.conf"
297
298     try:
299         conf = read_config(configfile)
300         try:
301             if str(conf['enable']) == "no":
302                 debug("disabled in configuration file")
303                 sys.stdout.write("DISABLE\n")
304                 sys.exit(1)
305         except (KeyError, TypeError):
306             pass
307         try:
308             modules_conf = conf['plugins_config_dir']
309         except (KeyError):
310             modules_conf = config_dir + "python.d/"  # default configuration directory
311         try:
312             modules_dir = conf['plugins_dir']
313         except (KeyError):
314             modules_dir = main_dir.replace("plugins.d", "python.d")
315         try:
316             interval = int(conf['interval'])
317         except (KeyError, TypeError):
318             pass  # use default interval from NETDATA_UPDATE_EVERY
319         try:
320             DEBUG_FLAG = bool(conf['debug'])
321         except (KeyError, TypeError):
322             pass
323         for k, v in conf.items():
324             if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
325                 continue
326             if v == 'no':
327                 disabled.append(k)
328     except FileNotFoundError:
329         modules_conf = config_dir
330         modules_dir = main_dir.replace("plugins.d", "python.d")
331
332     # directories should end with '/'
333     if modules_dir[-1] != '/':
334         modules_dir += "/"
335     if modules_conf[-1] != '/':
336         modules_conf += "/"
337
338     # parse passed command line arguments
339     out = parse_cmdline(modules_dir, *sys.argv)
340     modules = out['modules']
341     if out['interval'] is not None:
342         interval = out['interval']
343     
344     # configure environement to run modules
345     sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
346     
347     # run plugins
348     charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
349     charts.check()
350     charts.create()
351     charts.update()
352
353 if __name__ == '__main__':
354     run()