15
16
# along with this program; if not, write to the Free Software
16
17
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
# Module: setup/config
19
19
# Author: Matt Giuca, Refactored by David Coles
22
21
'''Configures IVLE with machine-specific details, most notably, various paths.
23
22
Either prompts the administrator for these details or accepts them as
26
Creates ivle/conf/conf.py and bin/trampoline/trampoline/conf.h.
36
from setup.util import query_user
40
# This dict maps legacy config option names to new config option paths
41
# ('section/option_name')
42
# NOTE: This is copied from ivle/conf/conf.py (because neither of these files
43
# can see each other).
45
'root_dir': 'urls/root',
46
'prefix': 'paths/prefix',
47
'data_path': 'paths/data',
48
'log_path': 'paths/logs',
49
'python_site_packages_override': 'paths/site_packages',
50
'public_host': 'urls/public_host',
51
'allowed_uids': 'os/allowed_uids',
52
'db_host': 'database/host',
53
'db_port': 'database/port',
54
'db_dbname': 'database/name',
55
'db_forumdbname': 'plugins/forum/dbname',
56
'db_user': 'database/username',
57
'db_password': 'database/password',
58
'auth_modules': 'auth/modules',
59
'ldap_url': 'auth/ldap_url',
60
'ldap_format_string': 'auth/ldap_format_string',
61
'subject_pulldown_modules': 'auth/subject_pulldown_modules',
62
'svn_addr': 'urls/svn_addr',
63
'usrmgt_host': 'usrmgt/host',
64
'usrmgt_port': 'usrmgt/port',
65
'usrmgt_magic': 'usrmgt/magic',
66
'forum_secret': 'plugins/forum/secret',
69
40
class ConfigOption:
70
41
"""A configuration option; one of the things written to conf.py."""
71
42
def __init__(self, option_name, default, prompt, comment, ask=True):
142
104
# Private mode (normal mode) requires login, and only serves files relevant to
143
105
# the logged-in user."""))
145
config_options.append(ConfigOption("allowed_uids", "33",
146
"""UID of the web server process which will run IVLE.
147
Only this user may execute the trampoline. May specify multiple users as
148
a comma-separated list.
107
config_options.append(ConfigOption("media/version", None,
108
"""Version of IVLE media resources (must change on each upgrade):""",
151
# The User-ID of the web server process which will run IVLE, and any other
152
# users who are allowed to run the trampoline. This is stores as a string of
153
# comma-separated integers, simply because it is not used within Python, only
154
# used by the setup program to write to conf.h (see setup.py config).""",
110
# Version string for IVLE media resource URLs. When set, they are aggressively
111
# cached by the browser, so it must be either left unset or changed each time
112
# a media file is changed.""", ask=False))
157
config_options.append(ConfigOption("db_host", "localhost",
114
config_options.append(ConfigOption("database/host", "localhost",
158
115
"""PostgreSQL Database config
159
116
==========================
160
117
Hostname of the DB server:""",
162
119
# Database server hostname"""))
164
config_options.append(ConfigOption("db_port", "5432",
121
config_options.append(ConfigOption("database/port", "5432",
165
122
"""Port of the DB server:""",
167
124
# Database server port"""))
169
config_options.append(ConfigOption("db_dbname", "ivle",
126
config_options.append(ConfigOption("database/name", "ivle",
170
127
"""Database name:""",
172
129
# Database name"""))
174
config_options.append(ConfigOption("db_forumdbname", "ivle_forum",
175
"""Forum Database name:""",
177
# Forum Database name"""))
179
config_options.append(ConfigOption("db_user", "postgres",
131
config_options.append(ConfigOption("database/username", "postgres",
180
132
"""Username for DB server login:""",
182
134
# Database username"""))
184
config_options.append(ConfigOption("db_password", "",
136
config_options.append(ConfigOption("database/password", "",
185
137
"""Password for DB server login:
186
(Caution: This password is stored in plaintext in ivle/conf/conf.py)""",
138
(Caution: This password is stored in plaintext!)""",
188
140
# Database password"""))
190
config_options.append(ConfigOption("auth_modules", "",
142
config_options.append(ConfigOption("auth/modules", "",
191
143
"""Authentication config
192
144
=====================
193
145
Comma-separated list of authentication modules.""",
226
178
# other modules may be plugged in to pulldown against organisation-specific
227
179
# pulldown backends.""", ask=False))
229
config_options.append(ConfigOption("svn_addr", "http://svn.localhost/",
181
config_options.append(ConfigOption("urls/svn_addr",
182
"http://svn.ivle.localhost/",
230
183
"""Subversion config
231
184
=================
232
185
The base url for accessing subversion repositories:""",
234
187
# The base url for accessing subversion repositories."""))
236
config_options.append(ConfigOption("usrmgt_host", "localhost",
189
config_options.append(ConfigOption("usrmgt/host", "localhost",
237
190
"""User Management Server config
238
191
============================
239
192
The hostname where the usrmgt-server runs:""",
241
194
# The hostname where the usrmgt-server runs."""))
243
config_options.append(ConfigOption("usrmgt_port", "2178",
196
config_options.append(ConfigOption("usrmgt/port", "2178",
244
197
"""The port where the usrmgt-server runs:""",
246
199
# The port where the usrmgt-server runs.""", ask=False))
248
config_options.append(ConfigOption("usrmgt_magic", None,
201
config_options.append(ConfigOption("usrmgt/magic", None,
249
202
"""The password for the usrmgt-server:""",
251
204
# The password for the usrmgt-server.""", ask=False))
206
def query_user(default, prompt):
207
"""Prompts the user for a string, which is read from a line of stdin.
208
Exits silently if EOF is encountered. Returns the string, with spaces
209
removed from the beginning and end.
211
Returns default if a 0-length line (after spaces removed) was read.
214
# A default of None means the value will be computed specially, so we
215
# can't really tell you what it is
216
defaultstr = "computed"
217
elif isinstance(default, basestring):
218
defaultstr = '"%s"' % default
220
defaultstr = repr(default)
221
sys.stdout.write('%s\n (default: %s)\n>' % (prompt, defaultstr))
223
val = sys.stdin.readline()
224
except KeyboardInterrupt:
226
sys.stdout.write("\n")
228
sys.stdout.write("\n")
230
if val == '': sys.exit(1)
231
# If empty line, return default
233
if val == '': return default
253
236
def configure(args):
254
# Call the real function
255
return __configure(args)
257
def __configure(args):
258
global db_port, usrmgt_port
260
237
# Try importing existing conf, but if we can't just set up defaults
261
238
# The reason for this is that these settings are used by other phases
262
239
# of setup besides conf, so we need to know them.
263
240
# Also this allows you to hit Return to accept the existing value.
265
confmodule = __import__("ivle/conf/conf")
266
for opt in config_options:
268
globals()[opt.option_name] = \
269
confmodule.__dict__[opt.option_name]
271
globals()[opt.option_name] = opt.default
273
# Just set reasonable defaults
274
for opt in config_options:
275
globals()[opt.option_name] = opt.default
242
conf = ivle.config.Config()
243
except ivle.config.ConfigError:
244
# Couldn't find a config file anywhere.
245
# Create a new blank config object (not yet bound to a file)
246
# All lookups (below) will fail, so it will be initialised with all
247
# the default values.
248
conf = ivle.config.Config(blank=True)
250
# Check that all the options are present, and if not, load the default
251
for opt in config_options:
253
conf.get_by_path(opt.option_name)
255
# If the default is None, omit it
256
# Else ConfigObj will write the string 'None' to the conf file
257
if opt.default is not None:
258
conf.set_by_path(opt.option_name, opt.default)
260
# Store comments in the conf object
261
for opt in config_options:
262
# Omitted if the key doesn't exist
263
conf.set_by_path(opt.option_name, comment=opt.comment)
277
265
# Set up some variables
278
266
cwd = os.getcwd()
280
268
# the files that will be created/overwritten
281
conffile = os.path.join(cwd, "etc/ivle.conf")
282
conf_hfile = os.path.join(cwd, "bin/trampoline/conf.h")
283
phpBBconffile = os.path.join(cwd, "www/php/phpBB3/config.php")
270
confdir = os.environ['IVLECONF']
272
confdir = '/etc/ivle'
274
conffile = os.path.join(confdir, 'ivle.conf')
275
plugindefaultfile = os.path.join(confdir, 'plugins.d/000default.conf')
285
277
# Get command-line arguments to avoid asking questions.
313
305
for opt in config_options:
315
globals()[opt.option_name] = \
316
query_user(globals()[opt.option_name], opt.prompt)
307
conf.set_by_path(opt.option_name,
308
query_user(conf.get_by_path(opt.option_name), opt.prompt))
318
310
opts = dict(opts)
319
311
# Non-interactive mode. Parse the options.
320
312
for opt in config_options:
321
313
if '--' + opt.option_name in opts:
322
globals()[opt.option_name] = opts['--' + opt.option_name]
314
conf.set_by_path(opt.option_name,
315
opts['--' + opt.option_name])
324
317
# Error handling on input values
326
allowed_uids_list = map(int, allowed_uids.split(','))
328
print >>sys.stderr, (
329
"Invalid UID list (%s).\n"
330
"Must be a comma-separated list of integers." % allowed_uids)
333
db_port = int(db_port)
334
if db_port < 0 or db_port >= 65536: raise ValueError()
336
print >>sys.stderr, (
337
"Invalid DB port (%s).\n"
338
"Must be an integer between 0 and 65535." % repr(db_port))
341
usrmgt_port = int(usrmgt_port)
342
if usrmgt_port < 0 or usrmgt_port >= 65536: raise ValueError()
319
conf['database']['port'] = int(conf['database']['port'])
320
if (conf['database']['port'] < 0
321
or conf['database']['port'] >= 65536):
324
if conf['database']['port'] == '' or conf['database']['port'] is None:
327
print >>sys.stderr, (
328
"Invalid DB port (%s).\n"
329
"Must be an integer between 0 and 65535." %
330
repr(conf['database']['port']))
333
conf['usrmgt']['port'] = int(conf['usrmgt']['port'])
334
if (conf['usrmgt']['port'] < 0 or conf['usrmgt']['port'] >= 65536):
343
336
except ValueError:
344
337
print >>sys.stderr, (
345
338
"Invalid user management port (%s).\n"
346
"Must be an integer between 0 and 65535." % repr(usrmgt_port))
339
"Must be an integer between 0 and 65535." %
340
repr(conf['usrmgt']['port']))
349
343
# By default we generate the magic randomly.
350
if globals()['usrmgt_magic'] is None:
351
globals()['usrmgt_magic'] = hashlib.md5(uuid.uuid4().bytes).hexdigest()
353
# Generate the forum secret
354
forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
356
# Write ./etc/ivle.conf
358
conf = configobj.ConfigObj()
345
conf['usrmgt']['magic'] # Throw away; just check for KeyError
347
conf['usrmgt']['magic'] = hashlib.md5(uuid.uuid4().bytes).hexdigest()
349
clobber_permissions = not os.path.exists(conffile)
351
# Write ./etc/ivle.conf (even if we loaded from a different filename)
359
352
conf.filename = conffile
361
353
conf.initial_comment = ["# IVLE Configuration File"]
363
# Add the forum secret to the config file (regenerated each config)
364
config_options.append(ConfigOption('forum_secret', None, '', ''))
365
globals()['forum_secret'] = forum_secret
367
for legacyopt in config_options:
368
newopt_path = CONFIG_OPTIONS[legacyopt.option_name].split('/')
369
# Iterate over each segment of the path, and find the section in conf
370
# file to insert the value into (use all but the last path segment)
372
for seg in newopt_path[:-1]:
373
# Create the section if it isn't there
374
if seg not in conf_section:
375
conf_section[seg] = {}
376
conf_section = conf_section[seg]
377
# The final path segment names the key to insert into
378
keyname = newopt_path[-1]
379
value = globals()[legacyopt.option_name]
380
if value is not None:
381
conf_section[keyname] = value
382
conf_section.comments[keyname] = legacyopt.comment.split('\n')
356
# We need to restrict permissions on a new file, as it contains
357
# a nice database password.
358
if clobber_permissions:
359
os.chown(conffile, 33, 33) # chown to www-data
360
os.chmod(conffile, stat.S_IRUSR | stat.S_IWUSR) # No g/o perms!
386
362
print "Successfully wrote %s" % conffile
388
# Write bin/trampoline/conf.h
390
conf = open(conf_hfile, "w")
392
# XXX Compute jail_base, jail_src_base and jail_system. These will
393
# ALSO be done by the boilerplate code, but we need them here in order
394
# to write to the C file.
395
jail_base = os.path.join(data_path, 'jailmounts')
396
jail_src_base = os.path.join(data_path, 'jails')
397
jail_system = os.path.join(jail_src_base, '__base__')
399
conf.write("""/* IVLE Configuration File
401
* Administrator settings required by trampoline.
402
* Note: trampoline will have to be rebuilt in order for changes to this file
406
#define IVLE_AUFS_JAILS
408
/* In the local file system, where are the jails located.
409
* The trampoline does not allow the creation of a jail anywhere besides
410
* jail_base or a subdirectory of jail_base.
412
static const char* jail_base = "%s";
413
static const char* jail_src_base = "%s";
414
static const char* jail_system = "%s";
416
/* Which user IDs are allowed to run the trampoline.
417
* This list should be limited to the web server user.
418
* (Note that root is an implicit member of this list).
420
static const int allowed_uids[] = { %s };
421
""" % (repr(jail_base)[1:-1], repr(jail_src_base)[1:-1],
422
repr(jail_system)[1:-1], repr(allowed_uids_list)[1:-1]))
423
# Note: The above uses PYTHON reprs, not C reprs
424
# However they should be the same with the exception of the outer
425
# characters, which are stripped off and replaced
429
print "Successfully wrote %s" % conf_hfile
431
# Write www/php/phpBB3/config.php
433
conf = open(phpBBconffile, "w")
436
if db_host == 'localhost':
437
forumdb_host = '127.0.0.1'
439
forumdb_host = db_host
442
// phpBB 3.0.x auto-generated configuration file
443
// Do not change anything in this file!
445
$dbhost = '""" + forumdb_host + """';
446
$dbport = '""" + str(db_port) + """';
447
$dbname = '""" + db_forumdbname + """';
448
$dbuser = '""" + db_user + """';
449
$dbpasswd = '""" + db_password + """';
451
$table_prefix = 'phpbb_';
453
$load_extensions = '';
454
@define('PHPBB_INSTALLED', true);
455
// @define('DEBUG', true);
456
//@define('DEBUG_EXTRA', true);
458
$forum_secret = '""" + forum_secret +"""';
463
print "Successfully wrote %s" % phpBBconffile
466
print "You may modify the configuration at any time by editing"
364
plugindefault = open(plugindefaultfile, 'w')
365
plugindefault.write("""# IVLE default plugin configuration file
366
[ivle.webapp.core#Plugin]
367
[ivle.webapp.admin.user#Plugin]
368
[ivle.webapp.tutorial#Plugin]
369
[ivle.webapp.admin.subject#Plugin]
370
[ivle.webapp.filesystem.browser#Plugin]
371
[ivle.webapp.filesystem.diff#Plugin]
372
[ivle.webapp.filesystem.svnlog#Plugin]
373
[ivle.webapp.filesystem.serve#Plugin]
374
[ivle.webapp.groups#Plugin]
375
[ivle.webapp.console#Plugin]
376
[ivle.webapp.security#Plugin]
377
[ivle.webapp.media#Plugin]
378
[ivle.webapp.help#Plugin]
379
[ivle.webapp.tos#Plugin]
380
[ivle.webapp.userservice#Plugin]
381
[ivle.webapp.fileservice#Plugin]
382
[ivle.webapp.submit#Plugin]
384
plugindefault.close()
385
print "Successfully wrote %s" % plugindefaultfile
388
print "You may modify the configuration at any time by editing " + conffile
396
# Print the opening spiel including the GPL notice
398
print """IVLE - Informatics Virtual Learning Environment Setup
399
Copyright (C) 2007-2009 The University of Melbourne
400
IVLE comes with ABSOLUTELY NO WARRANTY.
401
This is free software, and you are welcome to redistribute it
402
under certain conditions. See LICENSE.txt for details.
407
return configure(argv[1:])
409
if __name__ == "__main__":