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

« back to all changes in this revision

Viewing changes to setup/ivle-config

Remove the setup.configure import from setup.

Show diffs side-by-side

added added

removed removed

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