]> Frank Brehm's Git Trees - pixelpark/puppetmaster-webhooks.git/commitdiff
Some refactoring in lib/webhooks/handler.py
authorFrank Brehm <frank.brehm@pixelpark.com>
Mon, 20 Aug 2018 13:58:51 +0000 (15:58 +0200)
committerFrank Brehm <frank.brehm@pixelpark.com>
Mon, 20 Aug 2018 13:58:51 +0000 (15:58 +0200)
lib/webhooks/handler.py

index 8ec2cbdf326ac4c30b2fd64d1be97bfd0a181c7d..a86c18dd2dc3737cd90646d8ecfa9b59acb49d42 100644 (file)
@@ -33,9 +33,9 @@ from .errors import CommandNotFoundError
 from .obj import BaseObjectError
 from .obj import BaseObject
 
-__version__ = '0.1.2'
+__version__ = '0.2.1'
 
-log = logging.getLogger(__name__)
+LOG = logging.getLogger(__name__)
 
 
 # Some module varriables
@@ -158,7 +158,7 @@ class BaseHandler(BaseObject):
         else:
             self.initialized = initialized
         if self.verbose > 3:
-            log.debug("Initialized.")
+            LOG.debug("Initialized.")
 
     # -----------------------------------------------------------
     @property
@@ -275,37 +275,37 @@ class BaseHandler(BaseObject):
         """
 
         if self.verbose > 2:
-            log.debug("Searching for command {!r} ...".format(cmd))
+            LOG.debug("Searching for command {!r} ...".format(cmd))
 
         # Checking an absolute path
         if os.path.isabs(cmd):
             if not os.path.exists(cmd):
-                log.warning("Command {!r} doesn't exists.".format(cmd))
+                LOG.warning("Command {!r} doesn't exists.".format(cmd))
                 return None
             if not os.access(cmd, os.X_OK):
-                log.warning("Command {!r} is not executable.".format(cmd))
+                LOG.warning("Command {!r} is not executable.".format(cmd))
                 return None
             return os.path.normpath(cmd)
 
         # Checking a relative path
         for d in caller_search_path():
             if self.verbose > 3:
-                log.debug("Searching command in {!r} ...".format(d))
+                LOG.debug("Searching command in {!r} ...".format(d))
             p = os.path.join(d, cmd)
             if os.path.exists(p):
                 if self.verbose > 2:
-                    log.debug("Found {!r} ...".format(p))
+                    LOG.debug("Found {!r} ...".format(p))
                 if os.access(p, os.X_OK):
                     return os.path.normpath(p)
                 else:
-                    log.debug("Command {!r} is not executable.".format(p))
+                    LOG.debug("Command {!r} is not executable.".format(p))
 
         # command not found, sorry
         if quiet:
             if self.verbose > 2:
-                log.debug("Command {!r} not found.".format(cmd))
+                LOG.debug("Command {!r} not found.".format(cmd))
         else:
-            log.warning("Command {!r} not found.".format(cmd))
+            LOG.warning("Command {!r} not found.".format(cmd))
 
         return None
 
@@ -314,7 +314,7 @@ class BaseHandler(BaseObject):
         self, cmd, sudo=None, simulate=None, quiet=None, shell=False,
             stdout=None, stderr=None, bufsize=0, drop_stderr=False,
             close_fds=False, hb_handler=None, hb_interval=2.0,
-            poll_interval=0.2, **kwargs):
+            poll_interval=0.2, log_output=True, **kwargs):
         """
         Executing a OS command.
 
@@ -381,10 +381,10 @@ class BaseHandler(BaseObject):
         cmd_str = ' '.join(map(lambda x: pipes.quote(x), cmd_list))
 
         if not quiet or self.verbose > 1:
-            log.debug("Executing: {}".format(cmd_list))
+            LOG.debug("Executing: {}".format(cmd_list))
 
         if quiet and self.verbose > 1:
-            log.debug("Quiet execution")
+            LOG.debug("Quiet execution")
 
         used_stdout = subprocess.PIPE
         if stdout is not None:
@@ -425,7 +425,7 @@ class BaseHandler(BaseObject):
         if hb_handler is not None:
 
             if not quiet or self.verbose > 1:
-                log.debug((
+                LOG.debug((
                     "Starting asynchronous communication with '{cmd}', "
                     "heartbeat interval is {interval:0.1f} seconds.").format(
                         cmd=cmd_str, interval=hb_interval))
@@ -440,7 +440,7 @@ class BaseHandler(BaseObject):
             while True:
 
                 if self.verbose > 3:
-                    log.debug("Checking for the end of the communication ...")
+                    LOG.debug("Checking for the end of the communication ...")
                 if cmd_obj.poll() is not None:
                     cmd_obj.wait()
                     break
@@ -450,12 +450,12 @@ class BaseHandler(BaseObject):
                 time_diff = cur_time - start_time
                 if time_diff >= hb_interval:
                     if not quiet or self.verbose > 1:
-                        log.debug("Time to execute the heartbeat handler.")
+                        LOG.debug("Time to execute the heartbeat handler.")
                     if hb_handler:
                         hb_handler()
                     start_time = cur_time
                 if self.verbose > 3:
-                    log.debug("Sleeping {:0.2f} seconds ...".format(poll_interval))
+                    LOG.debug("Sleeping {:0.2f} seconds ...".format(poll_interval))
                 time.sleep(poll_interval)
 
                 # Reading out file descriptors
@@ -463,66 +463,57 @@ class BaseHandler(BaseObject):
                     try:
                         stdoutdata += os.read(cmd_obj.stdout.fileno(), 1024)
                         if self.verbose > 3:
-                            log.debug("  stdout is now: {!r}".format(stdoutdata))
+                            LOG.debug("  stdout is now: {!r}".format(stdoutdata))
                     except OSError:
                         pass
                 if used_stderr is not None:
                     try:
                         stderrdata += os.read(cmd_obj.stderr.fileno(), 1024)
                         if self.verbose > 3:
-                            log.debug("  stderr is now: {!r}".format(stderrdata))
+                            LOG.debug("  stderr is now: {!r}".format(stderrdata))
                     except OSError:
                         pass
         else:
             if not quiet or self.verbose > 1:
-                log.debug("Starting synchronous communication with '{}'.".format(cmd_str))
+                LOG.debug("Starting synchronous communication with '{}'.".format(cmd_str))
             (stdoutdata, stderrdata) = cmd_obj.communicate()
 
         if not quiet or self.verbose > 1:
-            log.debug("Finished communication with '{}'.".format(cmd_str))
+            LOG.debug("Finished communication with '{}'.".format(cmd_str))
+
+        ret = cmd_obj.wait()
+        if not quiet:
+            LOG.debug("Returncode: {}".format(ret))
 
         if stderrdata:
             if six.PY3:
-                if self.verbose > 2:
-                    log.debug("Decoding {what} from {enc!r}.".format(
+                if self.verbose > 3:
+                    LOG.debug("Decoding {what} from {enc!r}.".format(
                         what='STDERR', enc=cur_encoding))
                 stderrdata = stderrdata.decode(cur_encoding)
-            if quiet and not self.verbose:
-                pass
-            else:
-                msg = "Output on {where}: {what!r}.".format(
+            if not quiet:
+                msg = "Output on {where}:\n{what}.".format(
                     where="STDERR", what=stderrdata.strip())
-                if quiet:
-                    log.debug(msg)
+                if ret:
+                    LOG.warn(msg)
+                elif log_output:
+                    LOG.info(msg)
                 else:
-                    self.handle_error(msg, self.appname)
+                    LOG.debug(msg)
 
         if stdoutdata:
             if six.PY3:
-                if self.verbose > 2:
-                    log.debug("Decoding {what} from {enc!r}.".format(
+                if self.verbose > 3:
+                    LOG.debug("Decoding {what} from {enc!r}.".format(
                         what='STDOUT', enc=cur_encoding))
                 stdoutdata = stdoutdata.decode(cur_encoding)
-            do_out = False
-            if self.verbose:
-                if quiet:
-                    if self.verbose > 3:
-                        do_out = True
-                    else:
-                        do_out = False
-                else:
-                    do_out = True
-            else:
-                if not quiet:
-                    do_out = True
-            if do_out:
-                msg = "Output on {where}: {what!r}.".format(
+            if not quiet:
+                msg = "Output on {where}:\n{what}.".format(
                     where="STDOUT", what=stderrdata.strip())
-                log.debug(msg)
-
-        ret = cmd_obj.wait()
-        if not quiet or self.verbose > 1:
-            log.debug("Returncode: {}".format(ret))
+                if log_output:
+                    LOG.info(msg)
+                else:
+                    LOG.debug(msg)
 
         return (ret, stdoutdata, stderrdata)
 
@@ -573,7 +564,7 @@ class BaseHandler(BaseObject):
                 errno.EACCES, 'Read permission denied.', filename)
 
         if self.verbose > needed_verbose_level:
-            log.debug("Reading file content of {!r} ...".format(filename))
+            LOG.debug("Reading file content of {!r} ...".format(filename))
 
         signal.signal(signal.SIGALRM, read_alarm_caller)
         signal.alarm(timeout)
@@ -642,27 +633,27 @@ class BaseHandler(BaseObject):
         if os.path.exists(filename):
             if not os.access(filename, os.W_OK):
                 if self.simulate:
-                    log.error("Write permission to {!r} denied.".format(filename))
+                    LOG.error("Write permission to {!r} denied.".format(filename))
                 else:
                     raise IOError(errno.EACCES, 'Write permission denied.', filename)
         else:
             parent_dir = os.path.dirname(filename)
             if not os.access(parent_dir, os.W_OK):
                 if self.simulate:
-                    log.error("Write permission to {!r} denied.".format(parent_dir))
+                    LOG.error("Write permission to {!r} denied.".format(parent_dir))
                 else:
                     raise IOError(errno.EACCES, 'Write permission denied.', parent_dir)
 
         if self.verbose > verb_level1:
             if self.verbose > verb_level2:
-                log.debug("Write {what!r} into {to!r}.".format(
+                LOG.debug("Write {what!r} into {to!r}.".format(
                     what=content, to=filename))
             else:
-                log.debug("Writing {!r} ...".format(filename))
+                LOG.debug("Writing {!r} ...".format(filename))
 
         if self.simulate:
             if self.verbose > verb_level2:
-                log.debug("Simulating write into {!r}.".format(filename))
+                LOG.debug("Simulating write into {!r}.".format(filename))
             return
 
         signal.signal(signal.SIGALRM, write_alarm_caller)
@@ -670,14 +661,14 @@ class BaseHandler(BaseObject):
 
         # Open filename for writing unbuffered
         if self.verbose > verb_level3:
-            log.debug("Opening {!r} for write unbuffered ...".format(filename))
+            LOG.debug("Opening {!r} for write unbuffered ...".format(filename))
         fh = open(filename, 'w', 0)
 
         try:
             fh.write(content)
         finally:
             if self.verbose > verb_level3:
-                log.debug("Closing {!r} ...".format(filename))
+                LOG.debug("Closing {!r} ...".format(filename))
             fh.close()
 
         signal.alarm(0)