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