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