X-Git-Url: https://git.stderr.nl/gitweb?p=matthijs%2Fprojects%2Fbackupninja.git;a=blobdiff_plain;f=src%2Flib%2Fbackupninja%2Fhandlers%2F__init__.py;h=50abb41307c9078444200c86c731e9de284a1cb7;hp=da07b6d495146a615e29ca4c8a22b807d8de39bb;hb=0c1dd1831642f274eaef605fb2b75ac536791612;hpb=c9514724e6fad55405d92f3931056d5f69cfa4f4;ds=sidebyside diff --git a/src/lib/backupninja/handlers/__init__.py b/src/lib/backupninja/handlers/__init__.py index da07b6d..50abb41 100644 --- a/src/lib/backupninja/handlers/__init__.py +++ b/src/lib/backupninja/handlers/__init__.py @@ -17,65 +17,132 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -""" Handler superclass with common functionality """ +""" Action superclass with common functionality """ -import sys +import sys, ConfigParser import logging as log -class Handler(object): - def __init__(self, conf): - self.conf = conf +from backupninja import config - def run(self): +def fail_on_exception(f): + """ + This is a decorator meant for methods on the Action class. It + catches any exceptions thrown, sets the failed attribute to True and + rethrows the exception. + """ + def inner(self, *args, **kwargs): + try: + f(self, *args, **kwargs) + except: + self.failed = True + raise + return inner + +class Action(object): + """ + Subclasses of Action represent handlers for various action types. + This class is called Action instead of Handler, since even though the + classes could be referred to as handlers, the instances of this + class are really actions (i.e., it represents a specific action, + which is a combination of a action type and a specific action + configuration). + """ + def __init__(self): + # Subclasses should overwrite this with their default config + # See backupninja.config.load_config for the structure of this + # value. + self.default_config = {} + # Assume we'll run succesfully. If anything fails in the + # meanwhile, set this to True. + self.failed = False + # A logger object for this action. In the future, this might + # become a specific logger, that includes the action name and + # type. + self.log = log + + def run(self, **kwargs): """ - Run this handler for a single target. Override this method + Run this action for a single target. Override this method in a subclass """ pass - def finish(self): + def finish(self, **kwargs): """ Called when all targets have been processed. Can be overridden in a subclass. """ pass -def create_handler(ty, conf): + def load_config(self, filename): + """ + Load the configuration for this action from the given filename. + """ + self.conf = config.load_config(filename, self.default_config) + + def get_config_optional(self, section, option): + """ + Returns the value of the given option. If the option was not set + (and no default was set in self.default_config), return None. + + This is a convenience wrapper for ConfigParser.get(), since that + throws an exception on unset options. + """ + try: + return self.conf.get(section, option) + except ConfigParser.NoOptionError: + return None + + def get_config_mandatory(self, section, option): + """ + Returns the value of the given option. If the option was not set + (and no default was set in self.default_config), raises a + backupninja.config.ConfigError. + + This is a convenience wrapper for ConfigParser.get(), since that + has a very generic exception message on unknown options. + """ + try: + return self.conf.get(section, option) + except ConfigParser.NoOptionError: + raise config.ConfigError("Option '%s' in section '%s' is mandatory, please configure it" % (option, section)) + +def create_action(ty, **kwargs): """ - Create a new (subclass of) Handler object for an action with the - given type. conf is the configuration to pass to the handler. + Create a new (subclass of) Action object for an action with the + given type. Any extra keyword arguments are passed to the + constructor. - If the handler cannot be loaded, it is logged and None is returned - (but any exceptions raised by the handler code itself are not - handled). + If the handler class for this type cannot be loaded, an exception is + thrown. """ modname = 'backupninja.handlers.%s' % ty # Load the handler if it is not loaded yet if not modname in sys.modules: + log.debug('Loading handler for type "%s"', ty) try: __import__(modname, globals(), locals(), []) except ImportError, e: - log.error('Cannot load action handler for "%s": %s' - , ty, e) - return None + # Add some extra info, since the default exception does not + # show the full module name. + raise ImportError('Cannot load module %s: %s' % (modname, e)) + log.debug('Loaded handler for type "%s" from "%s"', ty, sys.modules[modname].__file__) # Get the module from the module table module = sys.modules[modname] # Check that the module has a "handler" top level function, which - # should create a new Handler object. + # should create a new Action object. if not hasattr(module, 'handler'): - log.error('Action handler for "%s" (in "%s) is not valid: it ' - 'does not have a "handler" top level function.' - , ty, module.__file__) - return None + raise ImportError('%s is not valid: it ' + 'does not have a "handler" top level function.' + % (module.__file__)) - # Call the "handler" function to create the actual handler - handler = module.handler(conf) + # Call the "handler" function to create the actual action + action = module.handler(**kwargs) - # Check if the handler returned is really a subclass of Handler - if not isinstance(handler, Handler): - log.error('Action handler for "%s" (in "%s) is not valid: it ' - 'does not return a subclass of backupninja.handlers.Handler.' - , ty, module.__file__) - return None - return handler + # Check if the handler returned is really a subclass of Action + if not isinstance(action, Action): + raise TypeError('%s is not valid, %s.handler did not return a ' + 'subclass of backupninja.handlers.Handler.' + % (module.__file__, modname)) + return action