]> arthur.barton.de Git - netdata.git/blobdiff - plugins.d/python.d.plugin
notify user when sth wrong in update()
[netdata.git] / plugins.d / python.d.plugin
index b14f3dd5fe5a973c5f9aa8fa411510820fd07082..167e6e3db2943320d3c373cad54f8f0a7a958da6 100755 (executable)
@@ -18,12 +18,14 @@ except AssertionError:
 class PythonCharts(object):
     
     def __init__(self,
-                 interval=1,
+                 interval=None,
                  modules=[],
                  modules_path='../python.d/',
                  modules_configs='../conf.d/'):
         self.first_run = True
-        self.interval = interval
+        if interval is None:
+            interval = 1
+        self.default_priority = 90000
         # check if plugin directory exists
         if not os.path.isdir(modules_path):
             debug("cannot find charts directory ", modules_path)
@@ -34,9 +36,13 @@ class PythonCharts(object):
         self.modules = []
         if len(modules) > 0:
             for m in modules:
-                self.modules.append(
-                    self.import_plugin(
-                        modules_path + m + ".chart.py"))
+                mod = self.import_plugin(modules_path + m + ".chart.py")
+                if mod is not None:
+                    self.modules.append(mod)
+            if len(self.modules) == 0:
+                debug("cannot find provided module(s)", modules_path)
+                sys.stdout.write("DISABLE\n")
+                sys.exit(1)
         else:
             self.load_modules(modules_path)
             if len(self.modules) == 0:
@@ -46,24 +52,25 @@ class PythonCharts(object):
 
         self.load_configs()
 
-        # set last execution and execution frequency dict
+        # set timetable dict (last execution, next execution and frequency)
+        # set priorities
         self.timetable = {}
         for m in self.modules:
             try:
-                interval = m.update_every
-                interval = int(interval)
-            except AttributeError:
-                interval = self.interval
-            except ValueError:
-                interval = self.interval
-                debug(m.__name__ + 
-                      ": wrong value of 'update_every' setting to " +
-                      str(self.interval))
-            # ensure module update frequency is not less than execution of this program
-            if interval < self.interval:
-                interval = self.interval
-            # charts updates are twice as frequent as user specified
-            self.timetable[m.__name__] = [0, interval/2.0]
+                m.priority = int(m.priority)
+            except (AttributeError,ValueError):
+                m.priority = self.default_priority
+             
+            if interval is None:
+                try:
+                    interval = int(m.update_every)
+                except (AttributeError, ValueError):
+                    interval = 1
+            
+            now = time.time()
+            self.timetable[m.__name__] = {'last' : now,
+                                          'next' : now - (now % interval) + interval,
+                                          'freq' : interval}
 
     def import_plugin(self, path, name=None):
         if name is None:
@@ -121,7 +128,7 @@ class PythonCharts(object):
                   mod.__name__ +
                   ".conf' not found. Using defaults.")
         elif reason[:11] == "misbehaving":
-            debug(mod.__name__, "is misbeaving. Disabling it")
+            debug(mod.__name__, "is "+reason)
 
     def check(self):
         for mod in self.modules:
@@ -146,7 +153,7 @@ class PythonCharts(object):
                         " '' 'Execution time for " +
                         chart +
                         " plugin' 'milliseconds / run' python.d netdata.plugin_python area 145000 " +
-                        str(self.timetable[mod.__name__][1]) +
+                        str(self.timetable[mod.__name__]['freq']) +
                         '\n')
                     sys.stdout.write("DIMENSION run_time 'run time' absolute 1 1\n\n")
                     sys.stdout.flush()
@@ -156,42 +163,53 @@ class PythonCharts(object):
                 self.disable_module(mod, "misbehaving")
 
     def update_module(self, mod):
-        t1 = time.time()
+        t_start = time.time()
         # check if it is time to execute module update() function
-        if (t1 - self.timetable[mod.__name__][0]) < self.timetable[mod.__name__][1]:
+        if self.timetable[mod.__name__]['next'] > t_start:
             return
         try:
-            if not self.first_run:
-                t = ""
+            if self.first_run:
+                since_last = 0
             else:
-                t=int((t1- self.timetable[mod.__name__][0]) * 1000000)
-            if not mod.update(t):
+                since_last = int((t_start - self.timetable[mod.__name__]['last']) * 1000000)
+            if not mod.update(since_last):
                 self.disable_module(mod, "update failed")
                 return
         except AttributeError:
             self.disable_module(mod, "no update")
             return
-        except UnboundLocalError:
-            self.disable_module(mod, "misbehaving")
+        except (UnboundLocalError, Exception) as e:
+            self.disable_module(mod, "misbehaving. Reason: " + str(e))
             return
-        t2 = time.time()
+        t_end = time.time()
+        self.timetable[mod.__name__]['next'] = t_end - (t_end % self.timetable[mod.__name__]['freq']) + self.timetable[mod.__name__]['freq']
         if self.first_run:
-            dt = ""
+            dt = 0
         else:
-            dt = int((t2 - self.timetable[mod.__name__][0]) * 1000000)
-        sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(dt)+'\n')
-        sys.stdout.write("SET run_time = " + str(int((t2 - t1) * 1000)) + '\n')
+            dt = int((t_end - self.timetable[mod.__name__]['last']) * 1000000)
+        sys.stdout.write("BEGIN netdata.plugin_pythond_"+mod.__name__+" "+str(since_last)+'\n')
+        sys.stdout.write("SET run_time = " + str(int((t_end - t_start) * 1000)) + '\n')
         sys.stdout.write("END\n")
         sys.stdout.flush()
-        self.timetable[mod.__name__][0] = t1
+        self.timetable[mod.__name__]['last'] = t_start
+        self.first_run = False
 
     def update(self):
+        self.first_run = True
         while True:
             t_begin = time.time()
+            next_runs = []
             for mod in self.modules:
                 self.update_module(mod)
-            time.sleep((self.interval - (time.time() - t_begin)) / 2)
-            self.first_run = False
+                try:
+                    next_runs.append(self.timetable[mod.__name__]['next'])
+                except KeyError:
+                    pass
+            if len(next_runs) == 0:
+                debug("No plugins loaded")
+                sys.stdout.write("DISABLE\n")
+                sys.exit(1)
+            time.sleep(min(next_runs) - time.time())
 
 
 def read_config(path):
@@ -219,7 +237,7 @@ def debug(*args):
 
 def parse_cmdline(directory, *commands):
     # TODO number -> interval
-    global DEBUG_FLAG, PROGRAM
+    global DEBUG_FLAG
     DEBUG_FLAG = False
     interval = None
 
@@ -239,7 +257,6 @@ def parse_cmdline(directory, *commands):
             except ValueError:
                 pass
 
-    PROGRAM = commands[0].split('/')[-1].split('.plugin')[0]
     debug("started from", commands[0], "with options:", *commands[1:])
 
     return {'interval': interval,
@@ -248,6 +265,9 @@ def parse_cmdline(directory, *commands):
 
 # if __name__ == '__main__':
 def run():
+    global DEBUG_FLAG, PROGRAM
+    DEBUG_FLAG = True
+    PROGRAM = sys.argv[0].split('/')[-1].split('.plugin')[0]
     # parse env variables
     # https://github.com/firehol/netdata/wiki/External-Plugins#environment-variables
     main_dir = os.getenv('NETDATA_PLUGINS_DIR',
@@ -282,7 +302,6 @@ def run():
             interval = int(conf['interval'])
         except (KeyError, TypeError):
             pass  # default interval
-        global DEBUG_FLAG
         try:
             DEBUG_FLAG = bool(conf['debug'])
         except (KeyError, TypeError):
@@ -300,11 +319,15 @@ def run():
     # parse passed command line arguments
     out = parse_cmdline(modules_dir, *sys.argv)
     modules = out['modules']
-    if out['interval'] is not None:
-        interval = out['interval']
+#    if out['interval'] is not None:
+#        interval = out['interval']
+
+    # configure environement to run modules
+    #sys.path.append(modules_dir+"python_modules") # append path to directory with modules dependencies
 
     # run plugins
-    charts = PythonCharts(interval, modules, modules_dir, modules_conf)
+#    charts = PythonCharts(interval, modules, modules_dir, modules_conf)
+    charts = PythonCharts(out['interval'], modules, modules_dir, modules_conf)
     charts.check()
     charts.create()
     charts.update()