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

« back to all changes in this revision

Viewing changes to setup/configure.py

  • Committer: mattgiuca
  • Date: 2008-01-12 15:35:53 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:201
Added "test" directory.
Added make_date_test.py, a short script I wrote to test the date format
algorithm committed in the previous revision.

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