+ def run_hook(self, cmd_name, hook_type, logger):
+ '''Execute a hook file for a given command regarding the fact
+ it is pre or post
+
+ :param cmd_name str: The the command on which execute the hook
+ :param hook_type str: pre or post
+ :param logger Logger: the logging instance to use for the prints
+ '''
+ # The hooks must be defined in the application pyconf
+ # So, if there is no application, do not do anything
+ if not src.config_has_application(self.cfg):
+ return
+
+ # The hooks must be defined in the application pyconf in the
+ # APPLICATION section, hook : { command : 'script_path.py'}
+ if "hook" not in self.cfg.APPLICATION \
+ or cmd_name not in self.cfg.APPLICATION.hook:
+ return
+
+ # Get the hook_script path and verify that it exists
+ hook_script_path = self.cfg.APPLICATION.hook[cmd_name]
+ if not os.path.exists(hook_script_path):
+ raise src.SatException(_("Hook script not found: %s") %
+ hook_script_path)
+
+ # Try to execute the script, catch the exception if it fails
+ try:
+ # import the module (in the sense of python)
+ pymodule = imp.load_source(cmd_name, hook_script_path)
+
+ # format a message to be printed at hook execution
+ msg = src.printcolors.printcWarning(_("Run hook script"))
+ msg = "%s: %s\n" % (msg,
+ src.printcolors.printcInfo(hook_script_path))
+
+ # run the function run_pre_hook if this function is called
+ # before the command, run_post_hook if it is called after
+ if hook_type == C_PRE_HOOK and "run_pre_hook" in dir(pymodule):
+ logger.write(msg, 1)
+ pymodule.run_pre_hook(self.cfg, logger)
+ elif hook_type == C_POST_HOOK and "run_post_hook" in dir(pymodule):
+ logger.write(msg, 1)
+ pymodule.run_post_hook(self.cfg, logger)
+
+ except Exception as exc:
+ msg = _("Unable to run hook script: %s") % hook_script_path
+ msg += "\n" + str(exc)
+ raise src.SatException(msg)
+