Add logging and install/uninstall targets
[cascardo/ipsilon.git] / ipsilon / install / server.py
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2014  Simo Sorce <simo@redhat.com>
4 #
5 # see file 'COPYING' for use and warranty information
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 from ipsilon.login.common import LoginMgrsInstall
21 from ipsilon.providers.common import ProvidersInstall
22 import argparse
23 import logging
24 import os
25 import shutil
26 import sys
27 import time
28
29
30 class ConfigurationError(Exception):
31
32     def __init__(self, message):
33         super(ConfigurationError, self).__init__(message)
34         self.message = message
35
36     def __str__(self):
37         return repr(self.message)
38
39
40 LOGFILE = '/var/log/ipsilon-install.log'
41 logger = logging.getLogger()
42
43
44 def openlogs():
45     global logger  # pylint: disable=W0603
46     if os.path.isfile(LOGFILE):
47         try:
48             created = '%s' % time.ctime(os.path.getctime(LOGFILE))
49             shutil.move(LOGFILE, '%s.%s' % (LOGFILE, created))
50         except IOError:
51             pass
52     logger = logging.getLogger()
53     try:
54         lh = logging.FileHandler(LOGFILE)
55     except IOError, e:
56         print >> sys.stderr, 'Unable to open %s (%s)' % (LOGFILE, str(e))
57         lh = logging.StreamHandler(sys.stderr)
58     formatter = logging.Formatter('[%(asctime)s] %(message)s')
59     lh.setFormatter(formatter)
60     logger.addHandler(lh)
61
62
63 def install(plugins, args):
64     logger.info('Installation initiated')
65
66     logger.info('Configuring login managers')
67     for plugin_name in args['lm_order']:
68         plugin = plugins['Login Managers'][plugin_name]
69         plugin.configure(args)
70
71     logger.info('Configuring Authentication Providers')
72     for plugin_name in plugins['Auth Providers']:
73         plugin = plugins['Auth Providers'][plugin_name]
74         plugin.configure(args)
75
76
77 def uninstall(plugins, args):
78     logger.info('Uninstallation initiated')
79     raise Exception('Not Implemented')
80
81
82 def find_plugins():
83     plugins = {
84         'Login Managers': LoginMgrsInstall().plugins,
85         'Auth Providers': ProvidersInstall().plugins
86     }
87     return plugins
88
89
90 def parse_args(plugins):
91     parser = argparse.ArgumentParser(description='Ipsilon Install Options')
92     parser.add_argument('--version',
93                         action='version', version='%(prog)s 0.1')
94     parser.add_argument('-o', '--login-managers-order', dest='lm_order',
95                         help='Comma separated list of login managers')
96     parser.add_argument('--ipa', choices=['yes', 'no'], default='yes',
97                         help='Detect and use an IPA server for authentication')
98     parser.add_argument('--uninstall', action='store_true',
99                         help="Uninstall the server and all data")
100
101     lms = []
102
103     for plugin_group in plugins:
104         group = parser.add_argument_group(plugin_group)
105         for plugin_name in plugins[plugin_group]:
106             plugin = plugins[plugin_group][plugin_name]
107             if plugin.ptype == 'login':
108                 lms.append(plugin.name)
109             plugin.install_args(group)
110
111     args = vars(parser.parse_args())
112
113     if args['lm_order'] is None:
114         args['lm_order'] = []
115         for name in lms:
116             if args[name] == 'yes':
117                 args['lm_order'].append(name)
118     else:
119         args['lm_order'] = args['lm_order'].split(',')
120
121     if len(args['lm_order']) == 0:
122         #force the basic pam provider if nothing else is selected
123         if 'pam' not in args:
124             parser.print_help()
125             sys.exit(-1)
126         args['lm_order'] = ['pam']
127         args['pam'] = 'yes'
128
129     return args
130
131 if __name__ == '__main__':
132     opts = []
133     out = 0
134     openlogs()
135     try:
136         fplugins = find_plugins()
137         opts = parse_args(fplugins)
138
139         logger.setLevel(logging.DEBUG)
140
141         logger.info('Intallation arguments:')
142         for k in sorted(opts.iterkeys()):
143             logger.info('%s: %s', k, opts[k])
144
145         if 'uninstall' in opts and opts['uninstall'] is True:
146             uninstall(fplugins, opts)
147
148         install(fplugins, opts)
149     except Exception, e:  # pylint: disable=broad-except
150         logger.exception(e)
151         if 'uninstall' in opts and opts['uninstall'] is True:
152             print 'Uninstallation aborted.'
153         else:
154             print 'Installation aborted.'
155         print 'See log file %s for details' % LOGFILE
156         out = 1
157     finally:
158         if out == 0:
159             if 'uninstall' in opts and opts['uninstall'] is True:
160                 print 'Uninstallation complete.'
161             else:
162                 print 'Installation complete.'
163     sys.exit(out)