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