]> arthur.barton.de Git - netdata.git/blob - plugins.d/python.d.plugin
better timing
[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             self.interval = 1
28         else:
29             self.interval = interval
30         self.default_priority = 90000
31         # check if plugin directory exists
32         if not os.path.isdir(modules_path):
33             debug("cannot find charts directory ", modules_path)
34             sys.stdout.write("DISABLE\n")
35             sys.exit(1)
36         self.configs = modules_configs
37
38         self.modules = []
39         if len(modules) > 0:
40             for m in modules:
41                 mod = self.import_plugin(modules_path + m + ".chart.py")
42                 if mod is not None:
43                     self.modules.append(mod)
44             if len(self.modules) == 0:
45                 debug("cannot find provided module(s)", modules_path)
46                 sys.stdout.write("DISABLE\n")
47                 sys.exit(1)
48         else:
49             self.load_modules(modules_path)
50             if len(self.modules) == 0:
51                 debug("cannot find modules directory", modules_path)
52                 sys.stdout.write("DISABLE\n")
53                 sys.exit(1)
54
55         self.load_configs()
56
57         # set last execution and execution frequency dict
58         self.timetable = {}
59         for m in self.modules:
60             if self.interval is not None:
61                 interval = self.interval
62             else:
63                 try:
64                     interval = int(m.update_every)
65                 except (AttributeError, ValueError):
66                     interval = 1
67             
68             now = time.time()
69             self.timetable[m.__name__] = {'last' : 0,
70                                           'next' : now,
71                                           'freq' : interval}
72         # set priorities
73         for m in self.modules:
74             try:
75                 m.priority = int(m.priority)
76             except (AttributeError,ValueError):
77                 m.priority = self.default_priority
78                 
79
80     def import_plugin(self, path, name=None):
81         if name is None:
82             name = path.split('/')[-1]
83             if name[-9:] != ".chart.py":
84                 return None
85             name = name[:-9]
86         try:
87             return importlib.machinery.SourceFileLoader(name, path).load_module()
88         except Exception as e:
89             debug(str(e))
90             return None
91
92     def load_modules(self, path):
93         names = os.listdir(path)
94         for mod in names:
95             m = self.import_plugin(path + mod)
96             if m is not None:
97                 debug("loading chart: '" + path + mod + "'")
98                 self.modules.append(m)
99
100     def load_configs(self):
101         for m in self.modules:
102             configfile = self.configs + m.__name__ + ".conf"
103             if os.path.isfile(configfile):
104                 debug("loading chart options: '" + configfile + "'")
105                 for k, v in read_config(configfile).items():
106                     setattr(m, k, v)
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         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 misbeaving. Disabling it")
137
138     def check(self):
139         for mod in self.modules:
140             try:
141                 if not mod.check():
142                     self.disable_module(mod, "failed check")
143             except AttributeError:
144                 self.disable_module(mod, "no check")
145             except UnboundLocalError:
146                 self.disable_module(mod, "misbehaving")
147
148     def create(self):
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:
168                 self.disable_module(mod, "misbehaving")
169
170     def update_module(self, mod):
171         t_start = time.time()
172         # check if it is time to execute module update() function
173         if self.timetable[mod.__name__]['next'] > t_start:
174             return
175         try:
176             if self.first_run:
177                 since_last = 0
178             else:
179                 since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
180             if not mod.update(since_last):
181                 self.disable_module(mod, "update failed")
182                 return
183         except AttributeError:
184             self.disable_module(mod, "no update")
185             return
186         except UnboundLocalError:
187             self.disable_module(mod, "misbehaving")
188             return
189         t_end = time.time()
190         self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
191         if self.first_run:
192             dt = 0
193         else:
194             dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
195         sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
196         sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
197         sys.stdout.write("END\n")
198         sys.stdout.flush()
199         self.timetable[mod.__name__]['last'] = t_start
200
201     def update(self):
202         self.first_run = True
203         while True:
204             t_begin = time.time()
205             next_runs = []
206             for mod in self.modules:
207                 self.update_module(mod)
208                 next_runs.append(self.timetable[mod.__name__]['next'])
209             time.sleep(min(next_runs) - time.time())
210             self.first_run = False
211
212
213 def read_config(path):
214     config = configparser.ConfigParser()
215     config_str = ""
216     try:
217         with open(path, 'r', encoding="utf_8") as f:
218             config_str = '[config]\n' + f.read()
219     except IsADirectoryError:
220         debug(str(path), "is a directory")
221         return
222     config.read_string(config_str)
223     return dict(config.items('config'))
224
225
226 def debug(*args):
227     if not DEBUG_FLAG:
228         return
229     sys.stderr.write(PROGRAM + ":")
230     for i in args:
231         sys.stderr.write(" " + str(i))
232     sys.stderr.write("\n")
233     sys.stderr.flush()
234
235
236 def parse_cmdline(directory, *commands):
237     # TODO number -> interval
238     global DEBUG_FLAG
239     DEBUG_FLAG = False
240     interval = None
241
242     mods = []
243     for cmd in commands[1:]:
244         if cmd == "check":
245             pass
246         elif cmd == "debug" or cmd == "all":
247             DEBUG_FLAG = True
248             # redirect stderr to stdout?
249         elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
250             DEBUG_FLAG = True
251             mods.append(cmd.replace(".chart.py", ""))
252         else:
253             try:
254                 interval = int(cmd)
255             except ValueError:
256                 pass
257
258     debug("started from", commands[0], "with options:", *commands[1:])
259
260     return {'interval': interval,
261             'modules': mods}
262
263
264 # if __name__ == '__main__':
265 def run():
266     global DEBUG_FLAG, PROGRAM
267     DEBUG_FLAG = True
268     PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
269     # parse env variables
270     # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
271     main_dir = os.getenv('NETDATA_PLUGINS_DIR',
272                          os.path.abspath(__file__).strip("python.d.plugin.py"))
273     config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
274     interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
275
276     # read configuration file
277     if config_dir[-1] != '/':
278         configfile = config_dir + '/' + "python.d.conf"
279     else:
280         configfile = config_dir + "python.d.conf"
281
282     try:
283         conf = read_config(configfile)
284         try:
285             if str(conf['enable']) == "no":
286                 debug("disabled in configuration file")
287                 sys.stdout.write("DISABLE\n")
288                 sys.exit(1)
289         except (KeyError, TypeError):
290             pass
291         try:
292             modules_conf = conf['plugins_config_dir']
293         except (KeyError, TypeError):
294             modules_conf = config_dir  # default configuration directory
295         try:
296             modules_dir = conf['plugins_dir']
297         except (KeyError, TypeError):
298             modules_dir = main_dir.replace("plugins.d", "python.d")
299         try:
300             interval = int(conf['interval'])
301         except (KeyError, TypeError):
302             pass  # default interval
303         try:
304             DEBUG_FLAG = bool(conf['debug'])
305         except (KeyError, TypeError):
306             pass
307     except FileNotFoundError:
308         modules_conf = config_dir
309         modules_dir = main_dir.replace("plugins.d", "python.d")
310
311     # directories should end with '/'
312     if modules_dir[-1] != '/':
313         modules_dir += "/"
314     if modules_conf[-1] != '/':
315         modules_conf += "/"
316
317     # parse passed command line arguments
318     out = parse_cmdline(modules_dir, *sys.argv)
319     modules = out['modules']
320 #    if out['interval'] is not None:
321 #        interval = out['interval']
322
323     # configure environement to run modules
324     #sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
325
326     # run plugins
327 #    charts = PythonCharts(interval, modules, modules_dir, modules_conf)
328     charts = PythonCharts(out['interval'], modules, modules_dir, modules_conf)
329     charts.check()
330     charts.create()
331     charts.update()
332
333 if __name__ == '__main__':
334     run()