summaryrefslogtreecommitdiffstats
path: root/ipsilon/install/ipsilon-server-install
blob: 1ffd5940c3d606080728408336fa82d78c01de44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/python
#
# Copyright (C) 2014  Simo Sorce <simo@redhat.com>
#
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from ipsilon.login.common import LoginMgrsInstall
from ipsilon.providers.common import ProvidersInstall
from ipsilon.helpers.common import EnvHelpersInstall
from ipsilon.util.data import Store
from ipsilon.tools import files
import ConfigParser
import argparse
import cherrypy
import logging
import os
import pwd
import shutil
import socket
import subprocess
import sys
import time


TEMPLATES = '/usr/share/ipsilon/templates/install'
CONFDIR = '/etc/ipsilon'
DATADIR = '/var/lib/ipsilon'
HTTPDCONFD = '/etc/httpd/conf.d'
BINDIR = '/usr/sbin'
STATICDIR = '/usr/share/ipsilon'
WSGI_SOCKET_PREFIX = None


class ConfigurationError(Exception):

    def __init__(self, message):
        super(ConfigurationError, self).__init__(message)
        self.message = message

    def __str__(self):
        return repr(self.message)


#Silence cherrypy logging to screen
cherrypy.log.screen = False

# Regular logging
LOGFILE = '/var/log/ipsilon-install.log'
logger = logging.getLogger()


def openlogs():
    global logger  # pylint: disable=W0603
    if os.path.isfile(LOGFILE):
        try:
            created = '%s' % time.ctime(os.path.getctime(LOGFILE))
            shutil.move(LOGFILE, '%s.%s' % (LOGFILE, created))
        except IOError:
            pass
    logger = logging.getLogger()
    try:
        lh = logging.FileHandler(LOGFILE)
    except IOError, e:
        print >> sys.stderr, 'Unable to open %s (%s)' % (LOGFILE, str(e))
        lh = logging.StreamHandler(sys.stderr)
    formatter = logging.Formatter('[%(asctime)s] %(message)s')
    lh.setFormatter(formatter)
    logger.addHandler(lh)


def install(plugins, args):
    logger.info('Installation initiated')
    now = time.strftime("%Y%m%d%H%M%S", time.gmtime())
    instance_conf = os.path.join(CONFDIR, args['instance'])

    logger.info('Installing default config files')
    ipsilon_conf = os.path.join(instance_conf, 'ipsilon.conf')
    idp_conf = os.path.join(instance_conf, 'idp.conf')
    args['httpd_conf'] = os.path.join(HTTPDCONFD,
                                      'ipsilon-%s.conf' % args['instance'])
    args['data_dir'] = os.path.join(DATADIR, args['instance'])
    if os.path.exists(ipsilon_conf):
        shutil.move(ipsilon_conf, '%s.bakcup.%s' % (ipsilon_conf, now))
    if os.path.exists(idp_conf):
        shutil.move(idp_conf, '%s.backup.%s' % (idp_conf, now))
    if not os.path.exists(instance_conf):
        os.makedirs(instance_conf, 0700)
    confopts = {'instance': args['instance'],
                'datadir': args['data_dir'],
                'sysuser': args['system_user'],
                'ipsilondir': BINDIR,
                'staticdir': STATICDIR,
                'debugging': "True" if args['server_debugging'] else "False"}
    if WSGI_SOCKET_PREFIX:
        confopts['wsgi_socket'] = 'WSGISocketPrefix %s' % WSGI_SOCKET_PREFIX
    files.write_from_template(ipsilon_conf,
                              os.path.join(TEMPLATES, 'ipsilon.conf'),
                              confopts)
    files.write_from_template(idp_conf,
                              os.path.join(TEMPLATES, 'idp.conf'),
                              confopts)
    if not os.path.exists(args['httpd_conf']):
        os.symlink(idp_conf, args['httpd_conf'])
    sessdir = os.path.join(args['data_dir'], 'sessions')
    if not os.path.exists(sessdir):
        os.makedirs(sessdir, 0700)
    data_conf = os.path.join(args['data_dir'], 'ipsilon.conf')
    if not os.path.exists(data_conf):
        os.symlink(ipsilon_conf, data_conf)
    # Load the cherrypy config from the newly installed file so
    # that db paths and all is properly set before configuring
    # components
    cherrypy.config.update(ipsilon_conf)

    # Move pre-existing admin db away
    admin_db = cherrypy.config['admin.config.db']
    if os.path.exists(admin_db):
        shutil.move(admin_db, '%s.backup.%s' % (admin_db, now))

    # Rebuild user db
    users_db = cherrypy.config['user.prefs.db']
    if os.path.exists(users_db):
        shutil.move(users_db, '%s.backup.%s' % (users_db, now))
    db = Store()
    db.save_user_preferences(args['admin_user'], {'is_admin': 1})

    logger.info('Configuring environment helpers')
    for plugin_name in plugins['Environment Helpers']:
        plugin = plugins['Environment Helpers'][plugin_name]
        plugin.configure_server(args)

    logger.info('Configuring login managers')
    for plugin_name in args['lm_order']:
        plugin = plugins['Login Managers'][plugin_name]
        plugin.configure(args)

    logger.info('Configuring Authentication Providers')
    for plugin_name in plugins['Auth Providers']:
        plugin = plugins['Auth Providers'][plugin_name]
        plugin.configure(args)

    # Fixup permissions so only the ipsilon user can read these files
    files.fix_user_dirs(instance_conf, opts['system_user'])
    files.fix_user_dirs(args['data_dir'], opts['system_user'])
    try:
        subprocess.call(['/usr/sbin/restorecon', '-R', args['data_dir']])
    except Exception:  # pylint: disable=broad-except
        pass

def uninstall(plugins, args):
    logger.info('Uninstallation initiated')
    raise Exception('Not Implemented')


def find_plugins():
    plugins = {
        'Environment Helpers': EnvHelpersInstall().plugins,
        'Login Managers': LoginMgrsInstall().plugins,
        'Auth Providers': ProvidersInstall().plugins
    }
    return plugins


def parse_config_profile(args):
    config = ConfigParser.ConfigParser()
    files = config.read(args['config_profile'])
    if len(files) == 0:
        raise ConfigurationError('Config Profile file %s not found!' %
                                 args['config_profile'])

    if 'globals' in config.sections():
        G = config.options('globals')
        for g in G:
            val = config.get('globals', g)
            if g in globals():
                globals()[g] = val
            else:
                for k in globals().keys():
                    if k.lower() == g.lower():
                        globals()[k] = val
                        break

    if 'arguments' in config.sections():
        A = config.options('arguments')
        for a in A:
            args[a] = config.get('arguments', a)

    return args


def parse_args(plugins):
    parser = argparse.ArgumentParser(description='Ipsilon Install Options')
    parser.add_argument('--version',
                        action='version', version='%(prog)s 0.1')
    parser.add_argument('-o', '--login-managers-order', dest='lm_order',
                        help='Comma separated list of login managers')
    parser.add_argument('--hostname',
                        help="Machine's fully qualified host name")
    parser.add_argument('--instance', default='idp',
                        help="IdP instance name, each is a separate idp")
    parser.add_argument('--system-user', default='ipsilon',
                        help="User account used to run the server")
    parser.add_argument('--admin-user', default='admin',
                        help="User account that is assigned admin privileges")
    parser.add_argument('--config-profile', default=None,
                        help="File containing install options")
    parser.add_argument('--server-debugging', action='store_true',
                        help="Uninstall the server and all data")
    parser.add_argument('--uninstall', action='store_true',
                        help="Uninstall the server and all data")

    lms = []

    for plugin_group in plugins:
        group = parser.add_argument_group(plugin_group)
        for plugin_name in plugins[plugin_group]:
            plugin = plugins[plugin_group][plugin_name]
            if plugin.ptype == 'login':
                lms.append(plugin.name)
            plugin.install_args(group)

    args = vars(parser.parse_args())

    if args['config_profile']:
        args = parse_config_profile(args)

    if not args['hostname']:
        args['hostname'] = socket.getfqdn()

    if len(args['hostname'].split('.')) < 2:
        raise ConfigurationError('Hostname: %s is not a FQDN')

    try:
        pwd.getpwnam(args['system_user'])
    except KeyError:
        raise ConfigurationError('User: %s not found on the system')

    if args['lm_order'] is None:
        args['lm_order'] = []
        for name in lms:
            if args[name] == 'yes':
                args['lm_order'].append(name)
    else:
        args['lm_order'] = args['lm_order'].split(',')

    if len(args['lm_order']) == 0:
        #force the basic pam provider if nothing else is selected
        if 'pam' not in args:
            parser.print_help()
            sys.exit(-1)
        args['lm_order'] = ['pam']
        args['pam'] = 'yes'

    #FIXME: check instance is only alphanums

    return args

if __name__ == '__main__':
    opts = []
    out = 0
    openlogs()
    try:
        fplugins = find_plugins()
        opts = parse_args(fplugins)

        logger.setLevel(logging.DEBUG)

        logger.info('Intallation arguments:')
        for k in sorted(opts.iterkeys()):
            logger.info('%s: %s', k, opts[k])

        if 'uninstall' in opts and opts['uninstall'] is True:
            uninstall(fplugins, opts)

        install(fplugins, opts)
    except Exception, e:  # pylint: disable=broad-except
        logger.exception(e)
        if 'uninstall' in opts and opts['uninstall'] is True:
            print 'Uninstallation aborted.'
        else:
            print 'Installation aborted.'
        print 'See log file %s for details' % LOGFILE
        out = 1
    finally:
        if out == 0:
            if 'uninstall' in opts and opts['uninstall'] is True:
                print 'Uninstallation complete.'
            else:
                print 'Installation complete.'
                print 'Please restart HTTPD to enable the IdP instance.'
    sys.exit(out)