]> arthur.barton.de Git - netdata.git/blob - plugins.d/python.d.plugin
proper time alignement
[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 misbeaving. Disabling it")
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:
182             self.disable_module(mod, "misbehaving")
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                 next_runs.append(self.timetable[mod.__name__]['next'])
205             time.sleep(min(next_runs) - time.time())
206
207
208 def read_config(path):
209     config = configparser.ConfigParser()
210     config_str = ""
211     try:
212         with open(path, 'r', encoding="utf_8") as f:
213             config_str = '[config]\n' + f.read()
214     except IsADirectoryError:
215         debug(str(path), "is a directory")
216         return
217     config.read_string(config_str)
218     return dict(config.items('config'))
219
220
221 def debug(*args):
222     if not DEBUG_FLAG:
223         return
224     sys.stderr.write(PROGRAM + ":")
225     for i in args:
226         sys.stderr.write(" " + str(i))
227     sys.stderr.write("\n")
228     sys.stderr.flush()
229
230
231 def parse_cmdline(directory, *commands):
232     # TODO number -> interval
233     global DEBUG_FLAG
234     DEBUG_FLAG = False
235     interval = None
236
237     mods = []
238     for cmd in commands[1:]:
239         if cmd == "check":
240             pass
241         elif cmd == "debug" or cmd == "all":
242             DEBUG_FLAG = True
243             # redirect stderr to stdout?
244         elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
245             DEBUG_FLAG = True
246             mods.append(cmd.replace(".chart.py", ""))
247         else:
248             try:
249                 interval = int(cmd)
250             except ValueError:
251                 pass
252
253     debug("started from", commands[0], "with options:", *commands[1:])
254
255     return {'interval': interval,
256             'modules': mods}
257
258
259 # if __name__ == '__main__':
260 def run():
261     global DEBUG_FLAG, PROGRAM
262     DEBUG_FLAG = True
263     PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
264     # parse env variables
265     # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
266     main_dir = os.getenv('NETDATA_PLUGINS_DIR',
267                          os.path.abspath(__file__).strip("python.d.plugin.py"))
268     config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
269     interval = int(os.getenv('NETDATA_UPDATE_EVERY', 1))
270
271     # read configuration file
272     if config_dir[-1] != '/':
273         configfile = config_dir + '/' + "python.d.conf"
274     else:
275         configfile = config_dir + "python.d.conf"
276
277     try:
278         conf = read_config(configfile)
279         try:
280             if str(conf['enable']) == "no":
281                 debug("disabled in configuration file")
282                 sys.stdout.write("DISABLE\n")
283                 sys.exit(1)
284         except (KeyError, TypeError):
285             pass
286         try:
287             modules_conf = conf['plugins_config_dir']
288         except (KeyError, TypeError):
289             modules_conf = config_dir  # default configuration directory
290         try:
291             modules_dir = conf['plugins_dir']
292         except (KeyError, TypeError):
293             modules_dir = main_dir.replace("plugins.d", "python.d")
294         try:
295             interval = int(conf['interval'])
296         except (KeyError, TypeError):
297             pass  # default interval
298         try:
299             DEBUG_FLAG = bool(conf['debug'])
300         except (KeyError, TypeError):
301             pass
302     except FileNotFoundError:
303         modules_conf = config_dir
304         modules_dir = main_dir.replace("plugins.d", "python.d")
305
306     # directories should end with '/'
307     if modules_dir[-1] != '/':
308         modules_dir += "/"
309     if modules_conf[-1] != '/':
310         modules_conf += "/"
311
312     # parse passed command line arguments
313     out = parse_cmdline(modules_dir, *sys.argv)
314     modules = out['modules']
315 #    if out['interval'] is not None:
316 #        interval = out['interval']
317
318     # configure environement to run modules
319     #sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
320
321     # run plugins
322 #    charts = PythonCharts(interval, modules, modules_dir, modules_conf)
323     charts = PythonCharts(out['interval'], modules, modules_dir, modules_conf)
324     charts.check()
325     charts.create()
326     charts.update()
327
328 if __name__ == '__main__':
329     run()