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

803 by dcoles
Setup: Modularised setup.py so it is now no longer over 1000 lines. This should
1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2008 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
# setup/config.py
23
# Configures IVLE with machine-specific details, most notably, various paths.
24
# Either prompts the administrator for these details or accepts them as
25
# command-line args.
26
# Creates lib/conf/conf.py and trampoline/conf.h.
27
28
import optparse
29
import getopt
30
import os
31
import hashlib
32
import uuid
33
from setup.setuputil import query_user
34
35
class ConfigOption:
36
    """A configuration option; one of the things written to conf.py."""
37
    def __init__(self, option_name, default, prompt, comment):
38
        """Creates a configuration option.
39
        option_name: Name of the variable in conf.py. Also name of the
40
            command-line argument to setup.py conf.
41
        default: Default value for this variable.
42
        prompt: (Short) string presented during the interactive prompt in
43
            setup.py conf.
44
        comment: (Long) comment string stored in conf.py. Each line of this
45
            string should begin with a '#'.
46
        """
47
        self.option_name = option_name
48
        self.default = default
49
        self.prompt = prompt
50
        self.comment = comment
51
52
# Configuration options, defaults and descriptions
53
config_options = []
54
config_options.append(ConfigOption("root_dir", "/",
55
    """Root directory where IVLE is located (in URL space):""",
56
    """
57
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
58
# with this).
59
# eg. "/" or "/ivle"."""))
60
config_options.append(ConfigOption("ivle_install_dir", "/opt/ivle",
61
    'Root directory where IVLE will be installed (on the local file '
62
    'system):',
63
    """
64
# In the local file system, where IVLE is actually installed.
65
# This directory should contain the "www" and "bin" directories."""))
66
config_options.append(ConfigOption("jail_base", "/home/informatics/jails",
67
    """Location of Directories
68
=======================
69
Root directory where the jails (containing user files) are stored
70
(on the local file system):""",
71
    """
72
# In the local file system, where are the student/user file spaces located.
73
# The user jails are expected to be located immediately in subdirectories of
74
# this location."""))
75
config_options.append(ConfigOption("subjects_base",
76
    "/home/informatics/subjects",
77
    """Root directory where the subject directories (containing worksheets
78
and other per-subject files) are stored (on the local file system):""",
79
    """
80
# In the local file system, where are the per-subject file spaces located.
81
# The individual subject directories are expected to be located immediately
82
# in subdirectories of this location."""))
83
config_options.append(ConfigOption("exercises_base",
84
    "/home/informatics/exercises",
85
    """Root directory where the exercise directories (containing
86
subject-independent exercise sheets) are stored (on the local file
87
system):""",
88
    """
89
# In the local file system, where are the subject-independent exercise sheet
90
# file spaces located."""))
91
config_options.append(ConfigOption("tos_path",
92
    "/home/informatics/tos.html",
93
    """Location where the Terms of Service document is stored (on the local
94
    file system):""",
95
    """
96
# In the local file system, where is the Terms of Service document located."""))
97
config_options.append(ConfigOption("motd_path",
98
    "/home/informatics/motd.html",
99
    """Location where the Message of the Day document is stored (on the local
100
    file system):""",
101
    """
102
# In the local file system, where is the Message of the Day document
103
# located. This is an HTML file (just the body fragment), which will
104
# be displayed on the login page. It is optional."""))
105
config_options.append(ConfigOption("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
config_options.append(ConfigOption("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
config_options.append(ConfigOption("db_host", "localhost",
126
    """PostgreSQL Database config
127
==========================
128
Hostname of the DB server:""",
129
    """
130
### PostgreSQL Database config ###
131
# Database server hostname"""))
132
config_options.append(ConfigOption("db_port", "5432",
133
    """Port of the DB server:""",
134
    """
135
# Database server port"""))
136
config_options.append(ConfigOption("db_dbname", "ivle",
137
    """Database name:""",
138
    """
139
# Database name"""))
140
config_options.append(ConfigOption("db_forumdbname", "ivle_forum",
141
    """Forum Database name:""",
142
    """
143
# Forum Database name"""))
144
config_options.append(ConfigOption("db_user", "postgres",
145
    """Username for DB server login:""",
146
    """
147
# Database username"""))
148
config_options.append(ConfigOption("db_password", "",
149
    """Password for DB server login:
150
    (Caution: This password is stored in plaintext in lib/conf/conf.py)""",
151
    """
152
# Database password"""))
153
config_options.append(ConfigOption("auth_modules", "ldap_auth",
154
    """Authentication config
155
=====================
156
Comma-separated list of authentication modules. Only "ldap" is available
157
by default.""",
158
    """
159
# Comma-separated list of authentication modules.
160
# These refer to importable Python modules in the www/auth directory.
161
# Modules "ldap" and "guest" are available in the source tree, but
162
# other modules may be plugged in to auth against organisation-specific
163
# auth backends."""))
164
config_options.append(ConfigOption("ldap_url", "ldaps://www.example.com",
165
    """(LDAP options are only relevant if "ldap" is included in the list of
166
auth modules).
167
URL for LDAP authentication server:""",
168
    """
169
# URL for LDAP authentication server"""))
170
config_options.append(ConfigOption("ldap_format_string",
171
    "uid=%s,ou=users,o=example",
172
    """Format string for LDAP auth request:
173
    (Must contain a single "%s" for the user's login name)""",
174
    """
175
# Format string for LDAP auth request
176
# (Must contain a single "%s" for the user's login name)"""))
177
config_options.append(ConfigOption("svn_addr", "http://svn.localhost/",
178
    """Subversion config
179
=================
180
The base url for accessing subversion repositories:""",
181
    """
182
# The base url for accessing subversion repositories."""))
183
config_options.append(ConfigOption("svn_conf", "/opt/ivle/svn/svn.conf",
184
    """The location of the subversion configuration file used by apache
185
to host the user repositories:""",
186
    """
187
# The location of the subversion configuration file used by
188
# apache to host the user repositories."""))
189
config_options.append(ConfigOption("svn_repo_path", "/home/informatics/repositories",
190
    """The root directory for the subversion repositories:""",
191
    """
192
# The root directory for the subversion repositories."""))
193
config_options.append(ConfigOption("svn_auth_ivle", "/opt/ivle/svn/ivle.auth",
194
    """The location of the password file used to authenticate users
195
of the subversion repository from the ivle server:""",
196
    """
197
# The location of the password file used to authenticate users
198
# of the subversion repository from the ivle server."""))
199
config_options.append(ConfigOption("svn_auth_local", "/opt/ivle/svn/local.auth",
200
    """The location of the password file used to authenticate local users
201
of the subversion repository:""",
202
    """
203
# The location of the password file used to authenticate local users
204
# of the subversion repository."""))
205
config_options.append(ConfigOption("usrmgt_host", "localhost",
206
    """User Management Server config
207
============================
208
The hostname where the usrmgt-server runs:""",
209
    """
210
# The hostname where the usrmgt-server runs."""))
211
config_options.append(ConfigOption("usrmgt_port", "2178",
212
    """The port where the usrmgt-server runs:""",
213
    """
214
# The port where the usrmgt-server runs."""))
215
config_options.append(ConfigOption("usrmgt_magic", "",
216
    """The password for the usrmgt-server:""",
217
    """
218
# The password for the usrmgt-server."""))
219
220
def configure(args):
221
    usage = """usage: %prog build [options]
222
(requires root)
223
Compiles all files and sets up a jail template in the source directory.
224
-O is recommended to cause compilation to be optimised.
225
Details:
226
Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
227
Creates jail with system and student packages installed from MIRROR.
228
Copies console/ to a location within the jail.
229
Copies OS programs and files to corresponding locations within the jail
230
  (eg. python and Python libs, ld.so, etc).
231
Generates .pyc or .pyo files for all the IVLE .py files."""
232
233
    # Parse arguments
234
    parser = optparse.OptionParser(usage)
235
    (options, args) = parser.parse_args(args)
236
237
    # Call the real function
238
    __configure(args)
239
240
def __configure(args):
241
    global db_port, usrmgt_port
242
243
    # Try importing existing conf, but if we can't just set up defaults
244
    # The reason for this is that these settings are used by other phases
245
    # of setup besides conf, so we need to know them.
246
    # Also this allows you to hit Return to accept the existing value.
247
    try:
248
        confmodule = __import__("lib/conf/conf")
249
        for opt in config_options:
250
            try:
251
                globals()[opt.option_name] = \
252
                confmodule.__dict__[opt.option_name]
253
            except:
254
                globals()[opt.option_name] = opt.default
255
    except ImportError:
256
        # Just set reasonable defaults
257
        for opt in config_options:
258
            globals()[opt.option_name] = opt.default
259
260
    # Set up some variables
261
    cwd = os.getcwd()
262
263
    # the files that will be created/overwritten
264
    conffile = os.path.join(cwd, "lib/conf/conf.py")
265
    jailconffile = os.path.join(cwd, "lib/conf/jailconf.py")
266
    conf_hfile = os.path.join(cwd, "trampoline/conf.h")
267
    phpBBconffile = os.path.join(cwd, "www/php/phpBB3/config.php")
268
    usrmgtserver_initdfile = os.path.join(cwd, "doc/setup/usrmgt-server.init")
269
270
    # Get command-line arguments to avoid asking questions.
271
272
    optnames = []
273
    for opt in config_options:
274
        optnames.append(opt.option_name + "=")
275
    (opts, args) = getopt.gnu_getopt(args, "", optnames)
276
277
    if args != []:
278
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
279
        return 2
280
281
    if opts == []:
282
        # Interactive mode. Prompt the user for all the values.
283
284
        print """This tool will create the following files:
285
    %s
286
    %s
287
    %s
288
    %s
289
    %s
290
prompting you for details about your configuration. The file will be
291
overwritten if it already exists. It will *not* install or deploy IVLE.
292
293
Please hit Ctrl+C now if you do not wish to do this.
294
""" % (conffile, jailconffile, conf_hfile, phpBBconffile, usrmgtserver_initdfile)
295
296
        # Get information from the administrator
297
        # If EOF is encountered at any time during the questioning, just exit
298
        # silently
299
300
        for opt in config_options:
301
            globals()[opt.option_name] = \
302
                query_user(globals()[opt.option_name], opt.prompt)
303
    else:
304
        opts = dict(opts)
305
        # Non-interactive mode. Parse the options.
306
        for opt in config_options:
307
            if '--' + opt.option_name in opts:
308
                globals()[opt.option_name] = opts['--' + opt.option_name]
309
310
    # Error handling on input values
311
    try:
312
        allowed_uids_list = map(int, allowed_uids.split(','))
313
    except ValueError:
314
        print >>sys.stderr, (
315
        "Invalid UID list (%s).\n"
316
        "Must be a comma-separated list of integers." % allowed_uids)
317
        return 1
318
    try:
319
        db_port = int(db_port)
320
        if db_port < 0 or db_port >= 65536: raise ValueError()
321
    except ValueError:
322
        print >>sys.stderr, (
323
        "Invalid DB port (%s).\n"
324
        "Must be an integer between 0 and 65535." % repr(db_port))
325
        return 1
326
    try:
327
        usrmgt_port = int(usrmgt_port)
328
        if usrmgt_port < 0 or usrmgt_port >= 65536: raise ValueError()
329
    except ValueError:
330
        print >>sys.stderr, (
331
        "Invalid user management port (%s).\n"
332
        "Must be an integer between 0 and 65535." % repr(usrmgt_port))
333
        return 1
334
335
    # Generate the forum secret
336
    forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
337
338
    # Write lib/conf/conf.py
339
340
    try:
341
        conf = open(conffile, "w")
342
343
        conf.write("""# IVLE Configuration File
344
# conf.py
345
# Miscellaneous application settings
346
347
""")
348
        for opt in config_options:
349
            conf.write('%s\n%s = %s\n' % (opt.comment, opt.option_name,
350
                repr(globals()[opt.option_name])))
351
352
	# Add the forum secret to the config file (regenerated each config)
353
        conf.write('forum_secret = "%s"\n' % (forum_secret))
354
355
        conf.close()
356
    except IOError, (errno, strerror):
357
        print "IO error(%s): %s" % (errno, strerror)
358
        sys.exit(1)
359
360
    print "Successfully wrote lib/conf/conf.py"
361
362
    # Write conf/jailconf.py
363
364
    try:
365
        conf = open(jailconffile, "w")
366
367
        # In the "in-jail" version of conf, we don't need MOST of the details
368
        # (it would be a security risk to have them here).
369
        # So we just write root_dir, and jail_base is "/".
370
        # (jail_base being "/" means "jail-relative" paths are relative to "/"
371
        # when inside the jail.)
372
        conf.write("""# IVLE Configuration File
373
# conf.py
374
# Miscellaneous application settings
375
# (User jail version)
376
377
378
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
379
# with this).
380
# eg. "/" or "/ivle".
381
root_dir = %s
382
383
# In the local file system, where are the student/user file spaces located.
384
# The user jails are expected to be located immediately in subdirectories of
385
# this location.
386
jail_base = '/'
387
388
# The hostname for serving publicly accessible pages
389
public_host = %s
390
""" % (repr(root_dir),repr(public_host)))
391
392
        conf.close()
393
    except IOError, (errno, strerror):
394
        print "IO error(%s): %s" % (errno, strerror)
395
        sys.exit(1)
396
397
    print "Successfully wrote lib/conf/jailconf.py"
398
399
    # Write trampoline/conf.h
400
401
    try:
402
        conf = open(conf_hfile, "w")
403
404
        conf.write("""/* IVLE Configuration File
405
 * conf.h
406
 * Administrator settings required by trampoline.
407
 * Note: trampoline will have to be rebuilt in order for changes to this file
408
 * to take effect.
409
 */
410
411
/* In the local file system, where are the jails located.
412
 * The trampoline does not allow the creation of a jail anywhere besides
413
 * jail_base or a subdirectory of jail_base.
414
 */
415
static const char* jail_base = "%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(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
426
427
        conf.close()
428
    except IOError, (errno, strerror):
429
        print "IO error(%s): %s" % (errno, strerror)
430
        sys.exit(1)
431
432
    print "Successfully wrote trampoline/conf.h"
433
434
    # Write www/php/phpBB3/config.php
435
436
    try:
437
        conf = open(phpBBconffile, "w")
438
        
439
        # php-pg work around
440
        if db_host == 'localhost':
441
            forumdb_host = '127.0.0.1'
442
        else:
443
            forumdb_host = db_host
444
445
        conf.write( """<?php
446
// phpBB 3.0.x auto-generated configuration file
447
// Do not change anything in this file!
448
$dbms = 'postgres';
449
$dbhost = '""" + forumdb_host + """';
450
$dbport = '""" + str(db_port) + """';
451
$dbname = '""" + db_forumdbname + """';
452
$dbuser = '""" + db_user + """';
453
$dbpasswd = '""" + db_password + """';
454
455
$table_prefix = 'phpbb_';
456
$acm_type = 'file';
457
$load_extensions = '';
458
@define('PHPBB_INSTALLED', true);
459
// @define('DEBUG', true);
460
//@define('DEBUG_EXTRA', true);
461
462
$forum_secret = '""" + forum_secret +"""';
463
?>"""   )
464
    
465
        conf.close()
466
    except IOError, (errno, strerror):
467
        print "IO error(%s): %s" % (errno, strerror)
468
        sys.exit(1)
469
470
    print "Successfully wrote www/php/phpBB3/config.php"
471
472
    # Write lib/conf/usrmgt-server.init
473
474
    try:
475
        conf = open(usrmgtserver_initdfile, "w")
476
477
        conf.write( '''#! /bin/sh
478
479
# Works for Ubuntu. Check before using on other distributions
480
481
### BEGIN INIT INFO
482
# Provides:          usrmgt-server
483
# Required-Start:    $syslog $networking $urandom
484
# Required-Stop:     $syslog
485
# Default-Start:     2 3 4 5
486
# Default-Stop:      1
487
# Short-Description: IVLE user management server
488
# Description:       Daemon connecting to the IVLE user management database.
489
### END INIT INFO
490
491
PATH=/sbin:/bin:/usr/sbin:/usr/bin
492
DESC="IVLE user management server"
493
NAME=usrmgt-server
494
DAEMON=/opt/ivle/scripts/$NAME
495
DAEMON_ARGS="''' + str(usrmgt_port) + ''' ''' + usrmgt_magic + '''"
496
PIDFILE=/var/run/$NAME.pid
497
SCRIPTNAME=/etc/init.d/usrmgt-server
498
499
# Exit if the daemon does not exist 
500
test -f $DAEMON || exit 0
501
502
# Load the VERBOSE setting and other rcS variables
503
[ -f /etc/default/rcS ] && . /etc/default/rcS
504
505
# Define LSB log_* functions.
506
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
507
. /lib/lsb/init-functions
508
509
#
510
# Function that starts the daemon/service
511
#
512
do_start()
513
{
514
	# Return
515
	#   0 if daemon has been started
516
	#   1 if daemon was already running
517
	#   2 if daemon could not be started
518
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
519
		|| return 1
520
	start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- \
521
		$DAEMON_ARGS \
522
		|| return 2
523
	# Add code here, if necessary, that waits for the process to be ready
524
	# to handle requests from services started subsequently which depend
525
	# on this one.  As a last resort, sleep for some time.
526
}
527
528
#
529
# Function that stops the daemon/service
530
#
531
do_stop()
532
{
533
	# Return
534
	#   0 if daemon has been stopped
535
	#   1 if daemon was already stopped
536
	#   2 if daemon could not be stopped
537
	#   other if a failure occurred
538
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
539
	RETVAL="$?"
540
	[ "$RETVAL" = 2 ] && return 2
541
	# Wait for children to finish too if this is a daemon that forks
542
	# and if the daemon is only ever run from this initscript.
543
	# If the above conditions are not satisfied then add some other code
544
	# that waits for the process to drop all resources that could be
545
	# needed by services started subsequently.  A last resort is to
546
	# sleep for some time.
547
	start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
548
	[ "$?" = 2 ] && return 2
549
	# Many daemons don't delete their pidfiles when they exit.
550
	rm -f $PIDFILE
551
	return "$RETVAL"
552
}
553
554
#
555
# Function that sends a SIGHUP to the daemon/service
556
#
557
do_reload() {
558
	#
559
	# If the daemon can reload its configuration without
560
	# restarting (for example, when it is sent a SIGHUP),
561
	# then implement that here.
562
	#
563
	start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
564
	return 0
565
}
566
567
case "$1" in
568
  start)
569
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
570
	do_start
571
	case "$?" in
572
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
573
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
574
	esac
575
	;;
576
  stop)
577
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
578
	do_stop
579
	case "$?" in
580
		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
581
		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
582
	esac
583
	;;
584
  #reload|force-reload)
585
	#
586
	# If do_reload() is not implemented then leave this commented out
587
	# and leave 'force-reload' as an alias for 'restart'.
588
	#
589
	#log_daemon_msg "Reloading $DESC" "$NAME"
590
	#do_reload
591
	#log_end_msg $?
592
	#;;
593
  restart|force-reload)
594
	#
595
	# If the "reload" option is implemented then remove the
596
	# 'force-reload' alias
597
	#
598
	log_daemon_msg "Restarting $DESC" "$NAME"
599
	do_stop
600
	case "$?" in
601
	  0|1)
602
		do_start
603
		case "$?" in
604
			0) log_end_msg 0 ;;
605
			1) log_end_msg 1 ;; # Old process is still running
606
			*) log_end_msg 1 ;; # Failed to start
607
		esac
608
		;;
609
	  *)
610
	  	# Failed to stop
611
		log_end_msg 1
612
		;;
613
	esac
614
	;;
615
  *)
616
	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
617
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
618
	exit 3
619
	;;
620
esac
621
622
:
623
''')
624
        
625
        conf.close()
626
    except IOError, (errno, strerror):
627
        print "IO error(%s): %s" % (errno, strerror)
628
        sys.exit(1)
629
630
    # fix permissions as the file contains the database password
631
    try:
632
        os.chmod('doc/setup/usrmgt-server.init', 0600)
633
    except OSError, (errno, strerror):
634
        print "WARNING: Couldn't chmod doc/setup/usrmgt-server.init:"
635
        print "OS error(%s): %s" % (errno, strerror)
636
637
    print "Successfully wrote lib/conf/usrmgt-server.init"
638
639
    print
640
    print "You may modify the configuration at any time by editing"
641
    print conffile
642
    print jailconffile
643
    print conf_hfile
644
    print phpBBconffile
645
    print usrmgtserver_initdfile
646
    print
647
    
648
    return 0