]> arthur.barton.de Git - netdata.git/blob - plugins.d/python.d.plugin
plugins.d/python.d.plugin
[netdata.git] / plugins.d / python.d.plugin
1 #!/usr/bin/env python3
2
3 import os
4 import sys
5 import time
6 try:
7     assert sys.version_info >= (3,1)
8     import importlib.machinery
9 except AssertionError:
10     sys.stderr.write('python.d.plugin: Not supported python version. Needed python >= 3.1\n')
11     sys.stdout.write('DISABLE\n')
12     sys.exit(1)
13 try:
14     import yaml
15 except ImportError:
16     sys.stderr.write('python.d.plugin: Cannot find yaml library\n')
17     sys.stdout.write('DISABLE\n')
18     sys.exit(1)
19
20 MODULE_EXTENSION = ".chart.py"
21 BASE_CONFIG = {'update_every' : 10,
22                'priority': 12345,
23                'retries' : 0}
24
25
26 class PythonCharts(object):
27     
28     def __init__(self,
29                  interval=None,
30                  modules=[],
31                  modules_path='../python.d/',
32                  modules_configs='../conf.d/',
33                  modules_disabled=[]):
34         self.first_run = True
35         # set configuration directory
36         self.configs = modules_configs
37
38         # load modules
39         loaded_modules = self._load_modules(modules_path,modules, modules_disabled)
40
41         # load configuration files
42         configured_modules = self._load_configs(loaded_modules)
43
44         # good economy and prosperity:
45         self.jobs = self._create_jobs(configured_modules)
46         if DEBUG_FLAG and interval is not None:
47             for job in self.jobs:
48                 job._create_timetable(interval)
49
50
51     def _create_jobs(self,modules):
52     # module store a definition of Service class
53     # module store configuration in module.config
54     # configs are list of dicts or a dict
55     # one dict is one service
56     # iterate over list of modules and inside one loop iterate over configs
57         jobs = []
58         for module in modules:
59             for name in module.config:
60                 # register a new job
61                 conf = module.config[name]
62                 try:
63                     job = module.Service(configuration=conf, name=name)
64                 except Exception as e:
65                     debug(module.__name__ +
66                           ": Couldn't start job named " +
67                           str(name) + 
68                           ": " +
69                           str(e))
70                     return None
71                 else:
72                     # set execution_name (needed to plot run time graphs)
73                     job.execution_name = module.__name__
74                     if name is not None:
75                         job.execution_name += "_" + name
76                 jobs.append(job)
77         
78         return [j for j in jobs if j is not None]
79
80     def _import_module(self, path, name=None):
81     # try to import module using only its path
82         if name is None:
83             name = path.split('/')[-1]
84             if name[-len(MODULE_EXTENSION):] != MODULE_EXTENSION:
85                 return None
86             name = name[:-len(MODULE_EXTENSION)]
87         try:
88             return importlib.machinery.SourceFileLoader(name, path).load_module()
89         except Exception as e:
90             debug(str(e))
91             return None
92
93     def _load_modules(self, path, modules, disabled):
94         # check if plugin directory exists
95         if not os.path.isdir(path):
96             debug("cannot find charts directory ", path)
97             sys.stdout.write("DISABLE\n")
98             sys.exit(1)
99
100         # load modules
101         loaded = []
102         if len(modules) > 0:
103             for m in modules:
104                 if m in disabled:
105                     continue
106                 mod = self._import_module(path + m + MODULE_EXTENSION)
107                 if mod is not None:
108                     loaded.append(mod)
109         else:
110             # scan directory specified in path and load all modules from there
111             names = os.listdir(path)
112             for mod in names:
113                 if mod.strip(MODULE_EXTENSION) in disabled:
114                     debug("disabling:",mod.strip(MODULE_EXTENSION))
115                     continue
116                 m = self._import_module(path + mod)
117                 if m is not None:
118                     debug("loading chart: '" + path + mod + "'")
119                     loaded.append(m)
120         return loaded
121
122     def _load_configs(self,modules):
123     # function loads configuration files to modules
124         for mod in modules:
125             configfile = self.configs + mod.__name__ + ".conf"
126             if os.path.isfile(configfile):
127                 debug("loading chart options: '" + configfile + "'")
128                 try:
129                     setattr(mod,
130                             'config',
131                             self._parse_config(mod,read_config(configfile)))
132                 except Exception as e:
133                     debug("something went wrong while loading configuration",e)
134             else:
135                 debug(mod.__name__ +
136                       ": configuration file '" +
137                       configfile +
138                       "' not found. Using defaults.")
139                 # set config if not found
140                 if not hasattr(mod, 'config'):
141                     mod.config = {None:{}}
142                     for var in BASE_CONFIG:
143                         try:
144                             mod.config[None][var] = getattr(var, mod)
145                         except Exception:
146                             mod.config[None][var] = BASE_CONFIG[var]
147         return modules
148
149     def _parse_config(self,module,config):
150         # get default values
151         defaults = {}
152         for key in BASE_CONFIG:
153             try:
154                 # get defaults from module config
155                 defaults[key] = int(config.pop(key))
156             except (KeyError,ValueError):
157                 try:
158                     # get defaults from module source code
159                     defaults[key] = getattr(module, key)
160                 except (KeyError,ValueError):
161                     # if above failed, get defaults from global dict
162                     defaults[key] = BASE_CONFIG[key]
163       
164         # check if there are dict in config dict
165         many_jobs = False
166         for name in config:
167             if type(config[name]) is dict:
168                 many_jobs = True
169                 break
170         
171         # assign variables needed by supervisor to every job configuration
172         if many_jobs:
173             for name in config:
174                 for key in defaults:
175                     if key not in config[name]:
176                         config[name][key] = defaults[key]
177         # if only one job is needed, values doesn't have to be in dict (in YAML)
178         else:
179             config = {None: config.copy()}
180             config[None].update(defaults)
181             
182         # return dictionary of jobs where every job has BASE_CONFIG variables
183         return config
184
185     def _stop(self, job, reason=None):
186     # modifies self.jobs
187         self.jobs.remove(job)
188         if reason is None:
189             return
190         elif reason[:3] == "no ":
191             debug("chart '" +
192                   job.execution_name,
193                   "' does not seem to have " +
194                   reason[3:] +
195                   "() function. Disabling it.")
196         elif reason[:7] == "failed ":
197             debug("chart '" +
198                   job.execution_name + "' " +
199                   reason[7:] +
200                   "() function reports failure.")
201         elif reason[:13] == "configuration":
202             debug(job.execution_name,
203                   "configuration file '" +
204                   self.configs +
205                   job.execution_name +
206                   ".conf' not found. Using defaults.")
207         elif reason[:11] == "misbehaving":
208             debug(job.execution_name, "is "+reason)
209
210     def check(self):
211     # try to execute check() on every job
212         for job in self.jobs:
213             try:
214                 if not job.check():
215                     self._stop(job, "failed check")
216             except AttributeError:
217                 self._stop(job, "no check")
218             except (UnboundLocalError, Exception) as e:
219                 self._stop(job, "misbehaving. Reason: " + str(e))
220
221     def create(self):
222     # try to execute create() on every job
223         for job in self.jobs:
224             try:
225                 if not job.create():
226                     self._stop(job, "failed create")
227                 else:
228                     chart = job.execution_name
229                     sys.stdout.write(
230                         "CHART netdata.plugin_pythond_" +
231                         chart +
232                         " '' 'Execution time for " +
233                         chart +
234                         " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
235                         str(job.timetable['freq']) +
236                         '\n')
237                     sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
238                     sys.stdout.flush()
239             except AttributeError:
240                 self._stop(job, "no create")
241             except (UnboundLocalError, Exception) as e:
242                 self._stop(job, "misbehaving. Reason: " + str(e))
243
244     def _update_job(self, job):
245     # try to execute update() on every job and draw run time graph 
246         t_start = time.time()
247         # check if it is time to execute job update() function
248         if job.timetable['next'] > t_start:
249             return
250         try:
251             if self.first_run:
252                 since_last = 0
253             else:
254                 since_last = int((t_start - job.timetable['last']) * 1000000)
255             if not job.update(since_last):
256                 self._stop(job, "update failed")
257                 return
258         except AttributeError:
259             self._stop(job, "no update")
260             return
261         except (UnboundLocalError, Exception) as e:
262             self._stop(job, "misbehaving. Reason: " + str(e))
263             return
264         t_end = time.time()
265         job.timetable['next'] = t_end - (t_end % job.timetable['freq']) + job.timetable['freq']
266         # draw performance graph
267         if self.first_run:
268             dt = 0
269         else:
270             dt = int((t_end - job.timetable['last']) * 1000000)
271         sys.stdout.write("BEGIN netdata.plugin_pythond_"+job.execution_name+" "+str(since_last)+'\n')
272         sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
273         sys.stdout.write("END\n")
274         sys.stdout.flush()
275         job.timetable['last'] = t_start
276         self.first_run = False
277
278     def update(self):
279     # run updates (this will stay forever and ever and ever forever and ever it'll be the one...)
280         self.first_run = True
281         while True:
282             t_begin = time.time()
283             next_runs = []
284             for job in self.jobs:
285                 self._update_job(job)
286                 try:
287                     next_runs.append(job.timetable['next'])
288                 except KeyError:
289                     pass
290             if len(next_runs) == 0:
291                 debug("No plugins loaded")
292                 sys.stdout.write("DISABLE\n")
293                 sys.exit(1)
294             time.sleep(min(next_runs) - time.time())
295
296
297 def read_config(path):
298     try:
299         with open(path, 'r') as stream:
300             config = yaml.load(stream)
301     except IsADirectoryError:
302         debug(str(path), "is a directory")
303         return None
304     except yaml.YAMLError as e:
305         debug(str(path), "is malformed:", e)
306         return None
307     return config
308
309
310 def debug(*args):
311     if not DEBUG_FLAG:
312         return
313     sys.stderr.write(PROGRAM + ":")
314     for i in args:
315         sys.stderr.write(" " + str(i))
316     sys.stderr.write("\n")
317     sys.stderr.flush()
318
319
320 def parse_cmdline(directory, *commands):
321     # TODO number -> interval
322     global DEBUG_FLAG
323     DEBUG_FLAG = False
324     interval = None
325
326     mods = []
327     for cmd in commands[1:]:
328         if cmd == "check":
329             pass
330         elif cmd == "debug" or cmd == "all":
331             DEBUG_FLAG = True
332             # redirect stderr to stdout?
333         elif os.path.isfile(directory + cmd + ".chart.py") or os.path.isfile(directory + cmd):
334             DEBUG_FLAG = True
335             mods.append(cmd.replace(".chart.py", ""))
336         else:
337             try:
338                 interval = int(cmd)
339             except ValueError:
340                 pass
341
342     debug("started from", commands[0], "with options:", *commands[1:])
343     if len(mods) == 0 and DEBUG_FLAG is False:
344         interval = None
345
346     return {'interval': interval,
347             'modules': mods}
348
349
350 # if __name__ == '__main__':
351 def run():
352     global DEBUG_FLAG, PROGRAM
353     DEBUG_FLAG = True
354     PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
355     # parse env variables
356     # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
357     main_dir = os.getenv('NETDATA_PLUGINS_DIR',
358                          os.path.abspath(__file__).strip("python.d.plugin.py"))
359     config_dir = os.getenv('NETDATA_CONFIG_DIR', "/etc/netdata/")
360     interval = os.getenv('NETDATA_UPDATE_EVERY', None)
361
362     # read configuration file
363     disabled = []
364     if config_dir[-1] != '/':
365         config_dir += '/'
366     configfile = config_dir + "python.d.conf"
367     print(config_dir)
368
369     try:
370         conf = read_config(configfile)
371         print(conf)
372         try:
373             if str(conf['enable']) is False:
374                 debug("disabled in configuration file")
375                 sys.stdout.write("DISABLE\n")
376                 sys.exit(1)
377         except (KeyError, TypeError):
378             pass
379         try:
380             modules_conf = conf['plugins_config_dir']
381         except KeyError:
382             modules_conf = config_dir + "python.d/"  # default configuration directory
383         try:
384             modules_dir = conf['plugins_dir']
385         except KeyError:
386             modules_dir = main_dir.replace("plugins.d", "python.d")
387         try:
388             interval = conf['interval']
389         except KeyError:
390             pass  # use default interval from NETDATA_UPDATE_EVERY
391         try:
392             DEBUG_FLAG = conf['debug']
393         except KeyError:
394             pass
395         for k, v in conf.items():
396             if k in ("plugins_config_dir", "plugins_dir", "interval", "debug"):
397                 continue
398             if v is False:
399                 disabled.append(k)
400     except FileNotFoundError:
401         modules_conf = config_dir
402         modules_dir = main_dir.replace("plugins.d", "python.d")
403
404     # directories should end with '/'
405     if modules_dir[-1] != '/':
406         modules_dir += "/"
407     if modules_conf[-1] != '/':
408         modules_conf += "/"
409
410     # parse passed command line arguments
411     out = parse_cmdline(modules_dir, *sys.argv)
412     modules = out['modules']
413     if out['interval'] is not None:
414         interval = out['interval']
415     
416     # configure environement to run modules
417     sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
418     
419     # run plugins
420     charts = PythonCharts(interval, modules, modules_dir, modules_conf, disabled)
421     charts.check()
422     charts.create()
423     charts.update()
424     sys.stdout.write("DISABLE")
425
426 if __name__ == '__main__':
427     run()