~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to setup/configure.py

setup.configure: Fixed bug if usrmgt_magic is None. Does not write comment if
    this is the case.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2009 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Module: setup/config
 
19
# Author: Matt Giuca, Refactored by David Coles
 
20
# Date:   03/07/2008
 
21
 
 
22
'''Configures IVLE with machine-specific details, most notably, various paths.
 
23
Either prompts the administrator for these details or accepts them as
 
24
command-line args.
 
25
 
 
26
Creates ivle/conf/conf.py and bin/trampoline/trampoline/conf.h.
 
27
'''
 
28
 
 
29
import optparse
 
30
import getopt
 
31
import os
 
32
import sys
 
33
import hashlib
 
34
import uuid
 
35
 
 
36
import ivle.config
 
37
 
 
38
import configobj
 
39
 
 
40
class ConfigOption:
 
41
    """A configuration option; one of the things written to conf.py."""
 
42
    def __init__(self, option_name, default, prompt, comment, ask=True):
 
43
        """Creates a configuration option.
 
44
        option_name: Name of the variable in conf.py. Also name of the
 
45
            command-line argument to setup.py conf.
 
46
        default: Default value for this variable.
 
47
        prompt: (Short) string presented during the interactive prompt in
 
48
            setup.py conf.
 
49
        comment: (Long) comment string stored in conf.py. Each line of this
 
50
            string should begin with a '#'.
 
51
        ask: Whether to ask the question in the default config run.
 
52
        """
 
53
        self.option_name = option_name
 
54
        self.default = default
 
55
        self.prompt = prompt
 
56
        self.comment = comment
 
57
        self.ask = ask
 
58
 
 
59
# Configuration options, defaults and descriptions
 
60
config_options = []
 
61
 
 
62
config_options.append(ConfigOption("urls/root", "/",
 
63
    """Root directory where IVLE is located (in URL space):""",
 
64
    """
 
65
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
 
66
# with this).
 
67
# eg. "/" or "/ivle".""", ask=False))
 
68
 
 
69
config_options.append(ConfigOption("paths/prefix", "/usr/local",
 
70
    """In the local file system, the prefix to the system directory where IVLE
 
71
is installed. (This should either be /usr or /usr/local):""",
 
72
    """
 
73
# In the local file system, the prefix to the system directory where IVLE is
 
74
# installed. This should either be '/usr' or '/usr/local'.
 
75
# ('/usr/local' for the usual install, '/usr' for distribution packages)""",
 
76
    ask=False))
 
77
 
 
78
config_options.append(ConfigOption("paths/site_packages",
 
79
    None,
 
80
    """site-packages directory in Python, where Python libraries are to be
 
81
installed. May be left as the default, in which case the value will be
 
82
computed from prefix and the current Python version:""",
 
83
    """
 
84
# 'site-packages' directory in Python, where Python libraries are to be
 
85
# installed. May be omitted (recommended), in which case the value will be
 
86
# computed from prefix and the current Python version.""", ask=False))
 
87
 
 
88
config_options.append(ConfigOption("paths/data",
 
89
    "/var/lib/ivle",
 
90
    "In the local file system, where user-modifiable data files should be "
 
91
    "located:",
 
92
    """
 
93
# In the local file system, where user-modifiable data files should be
 
94
# located.""", ask=False))
 
95
 
 
96
config_options.append(ConfigOption("paths/logs",
 
97
    "/var/log/ivle",
 
98
    """Directory where IVLE log files are stored (on the local
 
99
file system). Note - this must be writable by the user the IVLE server 
 
100
process runs as (usually www-data):""",
 
101
    """
 
102
# In the local file system, where IVLE error logs should be located.""",
 
103
    ask=False))
 
104
 
 
105
config_options.append(ConfigOption("urls/public_host", "public.localhost",
 
106
    """Hostname which will cause the server to go into "public mode",
 
107
providing login-free access to student's published work:""",
 
108
    """
 
109
# The server goes into "public mode" if the browser sends a request with this
 
110
# host. This is for security reasons - we only serve public student files on a
 
111
# separate domain to the main IVLE site.
 
112
# Public mode does not use cookies, and serves only public content.
 
113
# Private mode (normal mode) requires login, and only serves files relevant to
 
114
# the logged-in user."""))
 
115
 
 
116
config_options.append(ConfigOption("os/allowed_uids", "33",
 
117
    """UID of the web server process which will run IVLE.
 
118
Only this user may execute the trampoline. May specify multiple users as
 
119
a comma-separated list.
 
120
    (eg. "1002,78")""",
 
121
    """
 
122
# The User-ID of the web server process which will run IVLE, and any other
 
123
# users who are allowed to run the trampoline. This is stores as a string of
 
124
# comma-separated integers, simply because it is not used within Python, only
 
125
# used by the setup program to write to conf.h (see setup.py config).""",
 
126
    ask=False))
 
127
 
 
128
config_options.append(ConfigOption("database/host", "localhost",
 
129
    """PostgreSQL Database config
 
130
==========================
 
131
Hostname of the DB server:""",
 
132
    """
 
133
# Database server hostname"""))
 
134
 
 
135
config_options.append(ConfigOption("database/port", "5432",
 
136
    """Port of the DB server:""",
 
137
    """
 
138
# Database server port"""))
 
139
 
 
140
config_options.append(ConfigOption("database/name", "ivle",
 
141
    """Database name:""",
 
142
    """
 
143
# Database name"""))
 
144
 
 
145
config_options.append(ConfigOption("plugins/forum/dbname", "ivle_forum",
 
146
    """Forum Database name:""",
 
147
    """
 
148
# Forum Database name"""))
 
149
 
 
150
config_options.append(ConfigOption("database/username", "postgres",
 
151
    """Username for DB server login:""",
 
152
    """
 
153
# Database username"""))
 
154
 
 
155
config_options.append(ConfigOption("database/password", "",
 
156
    """Password for DB server login:
 
157
    (Caution: This password is stored in plaintext in ivle/conf/conf.py)""",
 
158
    """
 
159
# Database password"""))
 
160
 
 
161
config_options.append(ConfigOption("auth/modules", "",
 
162
    """Authentication config
 
163
=====================
 
164
Comma-separated list of authentication modules.""",
 
165
    """
 
166
# Comma-separated list of authentication modules.
 
167
# Note that auth is always enabled against the local database, and NO OTHER
 
168
# auth is enabled by default. This section is for specifying additional auth
 
169
# modules.
 
170
# These refer to importable Python modules in the www/auth directory.
 
171
# Modules "ldap_auth" and "guest" are available in the source tree, but
 
172
# other modules may be plugged in to auth against organisation-specific
 
173
# auth backends.""", ask=False))
 
174
 
 
175
config_options.append(ConfigOption("auth/ldap_url", "ldaps://www.example.com",
 
176
    """(LDAP options are only relevant if "ldap" is included in the list of
 
177
auth modules).
 
178
URL for LDAP authentication server:""",
 
179
    """
 
180
# URL for LDAP authentication server""", ask=False))
 
181
 
 
182
config_options.append(ConfigOption("auth/ldap_format_string",
 
183
    "uid=%s,ou=users,o=example",
 
184
    """Format string for LDAP auth request:
 
185
    (Must contain a single "%s" for the user's login name)""",
 
186
    """
 
187
# Format string for LDAP auth request
 
188
# (Must contain a single "%s" for the user's login name)""", ask=False))
 
189
 
 
190
config_options.append(ConfigOption("auth/subject_pulldown_modules", "",
 
191
    """Comma-separated list of subject pulldown modules.
 
192
Add proprietary modules to automatically enrol students in subjects.""",
 
193
    """
 
194
# Comma-separated list of subject pulldown modules.
 
195
# These refer to importable Python modules in the lib/pulldown_subj directory.
 
196
# Only "dummy_subj" is available in the source tree (an example), but
 
197
# other modules may be plugged in to pulldown against organisation-specific
 
198
# pulldown backends.""", ask=False))
 
199
 
 
200
config_options.append(ConfigOption("urls/svn_addr", "http://svn.localhost/",
 
201
    """Subversion config
 
202
=================
 
203
The base url for accessing subversion repositories:""",
 
204
    """
 
205
# The base url for accessing subversion repositories."""))
 
206
 
 
207
config_options.append(ConfigOption("usrmgt/host", "localhost",
 
208
    """User Management Server config
 
209
============================
 
210
The hostname where the usrmgt-server runs:""",
 
211
    """
 
212
# The hostname where the usrmgt-server runs."""))
 
213
 
 
214
config_options.append(ConfigOption("usrmgt/port", "2178",
 
215
    """The port where the usrmgt-server runs:""",
 
216
    """
 
217
# The port where the usrmgt-server runs.""", ask=False))
 
218
 
 
219
config_options.append(ConfigOption("usrmgt/magic", None,
 
220
    """The password for the usrmgt-server:""",
 
221
    """
 
222
# The password for the usrmgt-server.""", ask=False))
 
223
 
 
224
def query_user(default, prompt):
 
225
    """Prompts the user for a string, which is read from a line of stdin.
 
226
    Exits silently if EOF is encountered. Returns the string, with spaces
 
227
    removed from the beginning and end.
 
228
 
 
229
    Returns default if a 0-length line (after spaces removed) was read.
 
230
    """
 
231
    if default is None:
 
232
        # A default of None means the value will be computed specially, so we
 
233
        # can't really tell you what it is
 
234
        defaultstr = "computed"
 
235
    elif isinstance(default, basestring):
 
236
        defaultstr = '"%s"' % default
 
237
    else:
 
238
        defaultstr = repr(default)
 
239
    sys.stdout.write('%s\n    (default: %s)\n>' % (prompt, defaultstr))
 
240
    try:
 
241
        val = sys.stdin.readline()
 
242
    except KeyboardInterrupt:
 
243
        # Ctrl+C
 
244
        sys.stdout.write("\n")
 
245
        sys.exit(1)
 
246
    sys.stdout.write("\n")
 
247
    # If EOF, exit
 
248
    if val == '': sys.exit(1)
 
249
    # If empty line, return default
 
250
    val = val.strip()
 
251
    if val == '': return default
 
252
    return val
 
253
 
 
254
def configure(args):
 
255
    # Call the real function
 
256
    return __configure(args)
 
257
 
 
258
def __configure(args):
 
259
    # Try importing existing conf, but if we can't just set up defaults
 
260
    # The reason for this is that these settings are used by other phases
 
261
    # of setup besides conf, so we need to know them.
 
262
    # Also this allows you to hit Return to accept the existing value.
 
263
    try:
 
264
        conf = ivle.config.Config()
 
265
    except ivle.config.ConfigError:
 
266
        # Couldn't find a config file anywhere.
 
267
        # Create a new blank config object (not yet bound to a file)
 
268
        # All lookups (below) will fail, so it will be initialised with all
 
269
        # the default values.
 
270
        conf = ivle.config.Config(blank=True)
 
271
 
 
272
    # Check that all the options are present, and if not, load the default
 
273
    for opt in config_options:
 
274
        try:
 
275
            conf.get_by_path(opt.option_name)
 
276
        except KeyError:
 
277
            # If the default is None, omit it
 
278
            # Else ConfigObj will write the string 'None' to the conf file
 
279
            if opt.default is not None:
 
280
                conf.set_by_path(opt.option_name, opt.default)
 
281
 
 
282
    # Store comments in the conf object
 
283
    for opt in config_options:
 
284
        # Omitted if the key doesn't exist
 
285
        conf.set_by_path(opt.option_name, comment=opt.comment)
 
286
 
 
287
    # Set up some variables
 
288
    cwd = os.getcwd()
 
289
 
 
290
    # the files that will be created/overwritten
 
291
    conffile = os.path.join(cwd, "etc/ivle.conf")
 
292
    conf_hfile = os.path.join(cwd, "bin/trampoline/conf.h")
 
293
    phpBBconffile = os.path.join(cwd, "www/php/phpBB3/config.php")
 
294
 
 
295
    # Get command-line arguments to avoid asking questions.
 
296
 
 
297
    optnames = []
 
298
    for opt in config_options:
 
299
        optnames.append(opt.option_name + "=")
 
300
    (opts, args) = getopt.gnu_getopt(args, "", optnames)
 
301
 
 
302
    if args != []:
 
303
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
 
304
        return 2
 
305
 
 
306
    if opts == []:
 
307
        # Interactive mode. Prompt the user for all the values.
 
308
 
 
309
        print """This tool will create the following files:
 
310
    %s
 
311
    %s
 
312
    %s
 
313
prompting you for details about your configuration. The file will be
 
314
overwritten if it already exists. It will *not* install or deploy IVLE.
 
315
 
 
316
Please hit Ctrl+C now if you do not wish to do this.
 
317
""" % (conffile, conf_hfile, phpBBconffile)
 
318
 
 
319
        # Get information from the administrator
 
320
        # If EOF is encountered at any time during the questioning, just exit
 
321
        # silently
 
322
 
 
323
        for opt in config_options:
 
324
            if opt.ask:
 
325
                conf.set_by_path(opt.option_name,
 
326
                    query_user(conf.get_by_path(opt.option_name), opt.prompt))
 
327
    else:
 
328
        opts = dict(opts)
 
329
        # Non-interactive mode. Parse the options.
 
330
        for opt in config_options:
 
331
            if '--' + opt.option_name in opts:
 
332
                conf.set_by_path(opt.option_name,
 
333
                                 opts['--' + opt.option_name])
 
334
 
 
335
    # Error handling on input values
 
336
    try:
 
337
        allowed_uids_list = map(int,
 
338
                                conf['os']['allowed_uids'].split(','))
 
339
    except ValueError:
 
340
        print >>sys.stderr, (
 
341
        "Invalid UID list (%s).\n"
 
342
        "Must be a comma-separated list of integers." %
 
343
            conf['os']['allowed_uids'])
 
344
        return 1
 
345
    try:
 
346
        conf['database']['port'] = int(conf['database']['port'])
 
347
        if (conf['database']['port'] < 0
 
348
            or conf['database']['port'] >= 65536):
 
349
            raise ValueError()
 
350
    except ValueError:
 
351
        print >>sys.stderr, (
 
352
        "Invalid DB port (%s).\n"
 
353
        "Must be an integer between 0 and 65535." %
 
354
            repr(conf['database']['port']))
 
355
        return 1
 
356
    try:
 
357
        conf['usrmgt']['port'] = int(conf['usrmgt']['port'])
 
358
        if (conf['usrmgt']['port'] < 0 or conf['usrmgt']['port'] >= 65536):
 
359
            raise ValueError()
 
360
    except ValueError:
 
361
        print >>sys.stderr, (
 
362
        "Invalid user management port (%s).\n"
 
363
        "Must be an integer between 0 and 65535." %
 
364
            repr(conf['usrmgt']['port']))
 
365
        return 1
 
366
 
 
367
    # By default we generate the magic randomly.
 
368
    try:
 
369
        conf['usrmgt']['magic']     # Throw away; just check for KeyError
 
370
    except KeyError:
 
371
        conf['usrmgt']['magic'] = hashlib.md5(uuid.uuid4().bytes).hexdigest()
 
372
 
 
373
    # Generate the forum secret
 
374
    forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
 
375
 
 
376
    # Write ./etc/ivle.conf (even if we loaded from a different filename)
 
377
    conf.filename = conffile
 
378
 
 
379
    conf.initial_comment = ["# IVLE Configuration File"]
 
380
 
 
381
    # Add the forum secret to the config file (regenerated each config)
 
382
    config_options.append(ConfigOption('plugins/forum/secret', None, '', ''))
 
383
    conf['plugins']['forum']['secret'] = forum_secret
 
384
 
 
385
    conf.write()
 
386
 
 
387
    print "Successfully wrote %s" % conffile
 
388
 
 
389
    # Write bin/trampoline/conf.h
 
390
 
 
391
    conf_h = open(conf_hfile, "w")
 
392
 
 
393
    # XXX Compute jail_base, jail_src_base and jail_system. These will
 
394
    # ALSO be done by the boilerplate code, but we need them here in order
 
395
    # to write to the C file.
 
396
    jail_base = os.path.join(conf['paths']['data'], 'jailmounts')
 
397
    jail_src_base = os.path.join(conf['paths']['data'], 'jails')
 
398
    jail_system = os.path.join(jail_src_base, '__base__')
 
399
 
 
400
    conf_h.write("""/* IVLE Configuration File
 
401
 * conf.h
 
402
 * Administrator settings required by trampoline.
 
403
 * Note: trampoline will have to be rebuilt in order for changes to this file
 
404
 * to take effect.
 
405
 */
 
406
 
 
407
#define IVLE_AUFS_JAILS
 
408
 
 
409
/* In the local file system, where are the jails located.
 
410
 * The trampoline does not allow the creation of a jail anywhere besides
 
411
 * jail_base or a subdirectory of jail_base.
 
412
 */
 
413
static const char* jail_base = "%s";
 
414
static const char* jail_src_base = "%s";
 
415
static const char* jail_system = "%s";
 
416
 
 
417
/* Which user IDs are allowed to run the trampoline.
 
418
 * This list should be limited to the web server user.
 
419
 * (Note that root is an implicit member of this list).
 
420
 */
 
421
static const int allowed_uids[] = { %s };
 
422
""" % (repr(jail_base)[1:-1], repr(jail_src_base)[1:-1],
 
423
       repr(jail_system)[1:-1], repr(allowed_uids_list)[1:-1]))
 
424
    # Note: The above uses PYTHON reprs, not C reprs
 
425
    # However they should be the same with the exception of the outer
 
426
    # characters, which are stripped off and replaced
 
427
 
 
428
    conf_h.close()
 
429
 
 
430
    print "Successfully wrote %s" % conf_hfile
 
431
 
 
432
    # Write www/php/phpBB3/config.php
 
433
 
 
434
    conf_php = open(phpBBconffile, "w")
 
435
    
 
436
    # php-pg work around
 
437
    if conf['database']['host'] == 'localhost':
 
438
        forumdb_host = '127.0.0.1'
 
439
    else:
 
440
        forumdb_host = conf['database']['host']
 
441
 
 
442
    conf_php.write( """<?php
 
443
// phpBB 3.0.x auto-generated configuration file
 
444
// Do not change anything in this file!
 
445
$dbms = 'postgres';
 
446
$dbhost = '""" + forumdb_host + """';
 
447
$dbport = '""" + str(conf['database']['port']) + """';
 
448
$dbname = '""" + conf['plugins']['forum']['dbname'] + """';
 
449
$dbuser = '""" + conf['database']['username'] + """';
 
450
$dbpasswd = '""" + conf['database']['password'] + """';
 
451
 
 
452
$table_prefix = 'phpbb_';
 
453
$acm_type = 'file';
 
454
$load_extensions = '';
 
455
@define('PHPBB_INSTALLED', true);
 
456
// @define('DEBUG', true);
 
457
//@define('DEBUG_EXTRA', true);
 
458
 
 
459
$forum_secret = '""" + forum_secret +"""';
 
460
?>"""   )
 
461
    
 
462
    conf_php.close()
 
463
 
 
464
    print "Successfully wrote %s" % phpBBconffile
 
465
 
 
466
    print
 
467
    print "You may modify the configuration at any time by editing"
 
468
    print conffile
 
469
    print conf_hfile
 
470
    print phpBBconffile
 
471
    print
 
472
    
 
473
    return 0