3939c8d487e677968efae783cff753a3dec810ea
[matthijs/projects/backupninja.git] / src / lib / backupninja / action.py
1 # -*- mode: python; sh-basic-offset: 4; indent-tabs-mode: nil; -*-
2 # vim: set filetype=python sw=4 sts=4 expandtab autoindent:
3 #
4 #    Backupninja python reimplementation, based on original backupninja program
5 #    by riseup.net.
6 #    Copyright (C) 2010  Matthijs Kooijman <matthijs@stdin.nl>
7 #
8 #    This program is free software; you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation; either version 2 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License along
19 #    with this program; if not, write to the Free Software Foundation, Inc.,
20 #    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 """ Running backup actions """
23
24 import logging as log
25
26 from backupninja import config
27 from backupninja import handlers
28
29 def run_all_actions(opts, global_config):
30     """
31     Run all defined actions.
32
33     opts are the parsed commandline options, global_config is the parsed
34     global configuration.
35     """
36     log.info('Running all actions')
37     try:
38         actions = config.list_actions(opts)
39     except OSError, e:
40         log.critical('Unable to list actions: %s', e)
41         return
42
43     actions.sort()
44
45     for action in actions:
46         run_action(action, opts, global_config)
47
48 def run_action(action, opts, global_config):
49     """
50     Run a single action. opts are the parsed commandline options,
51     global_config is the parsed global configuration.
52     """
53     log.info('Running action "%s"', action)
54     # Split the action filename
55     parts = action.split('.', 2)
56     if (len(parts) < 2):
57         log.error('Invalid action filename: "%s". Should be in the form name.type, where type is a valid handler.')
58         return
59     (action_name, action_ty) = parts
60
61     # Get the config for this action
62     action_config = config.get_action_config(opts, action)
63
64     try:
65         # Create a handler for this action
66         handler = handlers.create_handler(action_ty, action_config)
67         # Run it
68         handler.run(test=opts.test)
69         handler.finish(test=opts.test)
70     except Exception, e:
71         log.error('Running action "%s" failed: %s', action, e)