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