1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
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.
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.
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
18
# Module: setup/config
19
# Author: Matt Giuca, Refactored by David Coles
22
'''Configures IVLE with machine-specific details, most notably, various paths.
23
Either prompts the administrator for these details or accepts them as
26
Creates ivle/conf/conf.py and bin/trampoline/trampoline/conf.h.
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
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.
53
self.option_name = option_name
54
self.default = default
56
self.comment = comment
59
# Configuration options, defaults and descriptions
62
config_options.append(ConfigOption("urls/root", "/",
63
"""Root directory where IVLE is located (in URL space):""",
65
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
67
# eg. "/" or "/ivle".""", ask=False))
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):""",
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)""",
78
config_options.append(ConfigOption("paths/site_packages",
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:""",
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))
88
config_options.append(ConfigOption("paths/data",
90
"In the local file system, where user-modifiable data files should be "
93
# In the local file system, where user-modifiable data files should be
94
# located.""", ask=False))
96
config_options.append(ConfigOption("paths/logs",
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):""",
102
# In the local file system, where IVLE error logs should be located.""",
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:""",
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."""))
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.
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).""",
128
config_options.append(ConfigOption("database/host", "localhost",
129
"""PostgreSQL Database config
130
==========================
131
Hostname of the DB server:""",
133
# Database server hostname"""))
135
config_options.append(ConfigOption("database/port", "5432",
136
"""Port of the DB server:""",
138
# Database server port"""))
140
config_options.append(ConfigOption("database/name", "ivle",
141
"""Database name:""",
145
config_options.append(ConfigOption("plugins/forum/dbname", "ivle_forum",
146
"""Forum Database name:""",
148
# Forum Database name"""))
150
config_options.append(ConfigOption("database/username", "postgres",
151
"""Username for DB server login:""",
153
# Database username"""))
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)""",
159
# Database password"""))
161
config_options.append(ConfigOption("auth/modules", "",
162
"""Authentication config
163
=====================
164
Comma-separated list of authentication modules.""",
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
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))
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
178
URL for LDAP authentication server:""",
180
# URL for LDAP authentication server""", ask=False))
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)""",
187
# Format string for LDAP auth request
188
# (Must contain a single "%s" for the user's login name)""", ask=False))
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.""",
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))
200
config_options.append(ConfigOption("urls/svn_addr", "http://svn.localhost/",
203
The base url for accessing subversion repositories:""",
205
# The base url for accessing subversion repositories."""))
207
config_options.append(ConfigOption("usrmgt/host", "localhost",
208
"""User Management Server config
209
============================
210
The hostname where the usrmgt-server runs:""",
212
# The hostname where the usrmgt-server runs."""))
214
config_options.append(ConfigOption("usrmgt/port", "2178",
215
"""The port where the usrmgt-server runs:""",
217
# The port where the usrmgt-server runs.""", ask=False))
219
config_options.append(ConfigOption("usrmgt/magic", None,
220
"""The password for the usrmgt-server:""",
222
# The password for the usrmgt-server.""", ask=False))
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.
229
Returns default if a 0-length line (after spaces removed) was read.
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
238
defaultstr = repr(default)
239
sys.stdout.write('%s\n (default: %s)\n>' % (prompt, defaultstr))
241
val = sys.stdin.readline()
242
except KeyboardInterrupt:
244
sys.stdout.write("\n")
246
sys.stdout.write("\n")
248
if val == '': sys.exit(1)
249
# If empty line, return default
251
if val == '': return default
255
# Call the real function
256
return __configure(args)
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.
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)
272
# Check that all the options are present, and if not, load the default
273
for opt in config_options:
275
conf.get_by_path(opt.option_name)
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)
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)
287
# Set up some variables
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")
295
# Get command-line arguments to avoid asking questions.
298
for opt in config_options:
299
optnames.append(opt.option_name + "=")
300
(opts, args) = getopt.gnu_getopt(args, "", optnames)
303
print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
307
# Interactive mode. Prompt the user for all the values.
309
print """This tool will create the following files:
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.
316
Please hit Ctrl+C now if you do not wish to do this.
317
""" % (conffile, conf_hfile, phpBBconffile)
319
# Get information from the administrator
320
# If EOF is encountered at any time during the questioning, just exit
323
for opt in config_options:
325
conf.set_by_path(opt.option_name,
326
query_user(conf.get_by_path(opt.option_name), opt.prompt))
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])
335
# Error handling on input values
337
allowed_uids_list = map(int,
338
conf['os']['allowed_uids'].split(','))
340
print >>sys.stderr, (
341
"Invalid UID list (%s).\n"
342
"Must be a comma-separated list of integers." %
343
conf['os']['allowed_uids'])
346
conf['database']['port'] = int(conf['database']['port'])
347
if (conf['database']['port'] < 0
348
or conf['database']['port'] >= 65536):
351
print >>sys.stderr, (
352
"Invalid DB port (%s).\n"
353
"Must be an integer between 0 and 65535." %
354
repr(conf['database']['port']))
357
conf['usrmgt']['port'] = int(conf['usrmgt']['port'])
358
if (conf['usrmgt']['port'] < 0 or conf['usrmgt']['port'] >= 65536):
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']))
367
# By default we generate the magic randomly.
369
conf['usrmgt']['magic'] # Throw away; just check for KeyError
371
conf['usrmgt']['magic'] = hashlib.md5(uuid.uuid4().bytes).hexdigest()
373
# Generate the forum secret
374
forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
376
# Write ./etc/ivle.conf (even if we loaded from a different filename)
377
conf.filename = conffile
379
conf.initial_comment = ["# IVLE Configuration File"]
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
387
print "Successfully wrote %s" % conffile
389
# Write bin/trampoline/conf.h
391
conf_h = open(conf_hfile, "w")
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__')
400
conf_h.write("""/* IVLE Configuration File
402
* Administrator settings required by trampoline.
403
* Note: trampoline will have to be rebuilt in order for changes to this file
407
#define IVLE_AUFS_JAILS
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.
413
static const char* jail_base = "%s";
414
static const char* jail_src_base = "%s";
415
static const char* jail_system = "%s";
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).
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
430
print "Successfully wrote %s" % conf_hfile
432
# Write www/php/phpBB3/config.php
434
conf_php = open(phpBBconffile, "w")
437
if conf['database']['host'] == 'localhost':
438
forumdb_host = '127.0.0.1'
440
forumdb_host = conf['database']['host']
442
conf_php.write( """<?php
443
// phpBB 3.0.x auto-generated configuration file
444
// Do not change anything in this file!
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'] + """';
452
$table_prefix = 'phpbb_';
454
$load_extensions = '';
455
@define('PHPBB_INSTALLED', true);
456
// @define('DEBUG', true);
457
//@define('DEBUG_EXTRA', true);
459
$forum_secret = '""" + forum_secret +"""';
464
print "Successfully wrote %s" % phpBBconffile
467
print "You may modify the configuration at any time by editing"