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

« back to all changes in this revision

Viewing changes to setup.py

  • Committer: mattgiuca
  • Date: 2007-12-16 23:02:54 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:67
doc: Added app_howto doc, a guide on IVLE apps interface.
        Added Makefile for this directory.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
 
# IVLE - Informatics Virtual Learning Environment
3
 
# Copyright (C) 2007-2008 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
 
# Module: setup
20
 
# Author: Matt Giuca
21
 
# Date:   12/12/2007
22
 
 
23
 
# This is a command-line application, for use by the administrator.
24
 
# This program configures, builds and installs IVLE in three separate steps.
25
 
# It is called with at least one argument, which specifies which operation to
26
 
# take.
27
 
 
28
 
# setup.py listmake (for developer use only)
29
 
# Recurses through the source tree and builds a list of all files which should
30
 
# be copied upon installation. This should be run by the developer before
31
 
# cutting a distribution, and the listfile it generates should be included in
32
 
# the distribution, avoiding the administrator having to run it.
33
 
 
34
 
# setup.py config [args]
35
 
# Configures IVLE with machine-specific details, most notably, various paths.
36
 
# Either prompts the administrator for these details or accepts them as
37
 
# command-line args.
38
 
# Creates www/conf/conf.py and trampoline/conf.h.
39
 
 
40
 
# setup.py build
41
 
# Compiles all files and sets up a jail template in the source directory.
42
 
# Details:
43
 
# Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
44
 
# Creates jail/.
45
 
# Creates standard subdirs inside the jail, eg bin, opt, home, tmp.
46
 
# Copies console/ to a location within the jail.
47
 
# Copies OS programs and files to corresponding locations within the jail
48
 
#   (eg. python and Python libs, ld.so, etc).
49
 
# Generates .pyc files for all the IVLE .py files.
50
 
 
51
 
# setup.py install [--nojail] [--dry|n]
52
 
# (Requires root)
53
 
# Create target install directory ($target).
54
 
# Create $target/bin.
55
 
# Copy trampoline/trampoline to $target/bin.
56
 
# chown and chmod the installed trampoline.
57
 
# Copy www/ to $target.
58
 
# Copy jail/ to jails template directory (unless --nojail specified).
59
 
 
60
 
import os
61
 
import stat
62
 
import shutil
63
 
import sys
64
 
import getopt
65
 
import string
66
 
import errno
67
 
import mimetypes
68
 
import compileall
69
 
import getopt
70
 
 
71
 
# Import modules from the website is tricky since they're in the www
72
 
# directory.
73
 
sys.path.append(os.path.join(os.getcwd(), 'www'))
74
 
import conf
75
 
import common.makeuser
76
 
 
77
 
# Determine which Python version (2.4 or 2.5, for example) we are running,
78
 
# and use that as the filename to the Python directory.
79
 
# Just get the first 3 characters of sys.version.
80
 
PYTHON_VERSION = sys.version[0:3]
81
 
 
82
 
# Operating system files to copy over into the jail.
83
 
# These will be copied from the given place on the OS file system into the
84
 
# same place within the jail.
85
 
JAIL_FILES = [
86
 
    '/lib/ld-linux.so.2',
87
 
    '/lib/tls/i686/cmov/libc.so.6',
88
 
    '/lib/tls/i686/cmov/libdl.so.2',
89
 
    '/lib/tls/i686/cmov/libm.so.6',
90
 
    '/lib/tls/i686/cmov/libpthread.so.0',
91
 
    '/lib/tls/i686/cmov/libutil.so.1',
92
 
    '/etc/ld.so.conf',
93
 
    '/etc/ld.so.cache',
94
 
    # These 2 files do not exist in Ubuntu
95
 
    #'/etc/ld.so.preload',
96
 
    #'/etc/ld.so.nohwcap',
97
 
    # UNIX commands
98
 
    '/usr/bin/strace',
99
 
    '/bin/ls',
100
 
    '/bin/echo',
101
 
    # Needed by python
102
 
    '/usr/bin/python%s' % PYTHON_VERSION,
103
 
    # Needed by matplotlib
104
 
    '/usr/lib/i686/cmov/libssl.so.0.9.8',
105
 
    '/usr/lib/i686/cmov/libcrypto.so.0.9.8',
106
 
    '/lib/tls/i686/cmov/libnsl.so.1',
107
 
    '/usr/lib/libz.so.1',
108
 
    '/usr/lib/atlas/liblapack.so.3',
109
 
    '/usr/lib/atlas/libblas.so.3',
110
 
    '/usr/lib/libg2c.so.0',
111
 
    '/usr/lib/libstdc++.so.6',
112
 
    '/usr/lib/libfreetype.so.6',
113
 
    '/usr/lib/libpng12.so.0',
114
 
    '/usr/lib/libBLT.2.4.so.8.4',
115
 
    '/usr/lib/libtk8.4.so.0',
116
 
    '/usr/lib/libtcl8.4.so.0',
117
 
    '/usr/lib/tcl8.4/init.tcl',
118
 
    '/usr/lib/libX11.so.6',
119
 
    '/usr/lib/libXau.so.6',
120
 
    '/usr/lib/libXdmcp.so.6',
121
 
    '/lib/libgcc_s.so.1',
122
 
    '/etc/matplotlibrc',
123
 
]
124
 
# Symlinks to make within the jail. Src mapped to dst.
125
 
JAIL_LINKS = {
126
 
    'python%s' % PYTHON_VERSION: 'jail/usr/bin/python',
127
 
}
128
 
# Trees to copy. Src mapped to dst (these will be passed to action_copytree).
129
 
JAIL_COPYTREES = {
130
 
    '/usr/lib/python%s' % PYTHON_VERSION:
131
 
        'jail/usr/lib/python%s' % PYTHON_VERSION,
132
 
    '/usr/share/matplotlib': 'jail/usr/share/matplotlib',
133
 
    '/etc/ld.so.conf.d': 'jail/etc/ld.so.conf.d',
134
 
}
135
 
 
136
 
class ConfigOption:
137
 
    """A configuration option; one of the things written to conf.py."""
138
 
    def __init__(self, option_name, default, prompt, comment):
139
 
        """Creates a configuration option.
140
 
        option_name: Name of the variable in conf.py. Also name of the
141
 
            command-line argument to setup.py conf.
142
 
        default: Default value for this variable.
143
 
        prompt: (Short) string presented during the interactive prompt in
144
 
            setup.py conf.
145
 
        comment: (Long) comment string stored in conf.py. Each line of this
146
 
            string should begin with a '#'.
147
 
        """
148
 
        self.option_name = option_name
149
 
        self.default = default
150
 
        self.prompt = prompt
151
 
        self.comment = comment
152
 
 
153
 
# Configuration options, defaults and descriptions
154
 
config_options = []
155
 
config_options.append(ConfigOption("root_dir", "/ivle",
156
 
    """Root directory where IVLE is located (in URL space):""",
157
 
    """
158
 
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
159
 
# with this).
160
 
# eg. "/" or "/ivle"."""))
161
 
config_options.append(ConfigOption("ivle_install_dir", "/opt/ivle",
162
 
    'Root directory where IVLE will be installed (on the local file '
163
 
    'system):',
164
 
    """
165
 
# In the local file system, where IVLE is actually installed.
166
 
# This directory should contain the "www" and "bin" directories."""))
167
 
config_options.append(ConfigOption("jail_base", "/home/informatics/jails",
168
 
    """Root directory where the jails (containing user files) are stored
169
 
(on the local file system):""",
170
 
    """
171
 
# In the local file system, where are the student/user file spaces located.
172
 
# The user jails are expected to be located immediately in subdirectories of
173
 
# this location."""))
174
 
config_options.append(ConfigOption("subjects_base",
175
 
    "/home/informatics/subjects",
176
 
    """Root directory where the subject directories (containing worksheets
177
 
and other per-subject files) are stored (on the local file system):""",
178
 
    """
179
 
# In the local file system, where are the per-subject file spaces located.
180
 
# The individual subject directories are expected to be located immediately
181
 
# in subdirectories of this location."""))
182
 
config_options.append(ConfigOption("problems_base",
183
 
    "/home/informatics/problems",
184
 
    """Root directory where the problem directories (containing
185
 
subject-independent problem sheets) are stored (on the local file
186
 
system):""",
187
 
    """
188
 
# In the local file system, where are the subject-independent problem sheet
189
 
# file spaces located."""))
190
 
config_options.append(ConfigOption("public_host", "public.localhost",
191
 
    """Hostname which will cause the server to go into "public mode",
192
 
providing login-free access to student's published work:""",
193
 
    """
194
 
# The server goes into "public mode" if the browser sends a request with this
195
 
# host. This is for security reasons - we only serve public student files on a
196
 
# separate domain to the main IVLE site.
197
 
# Public mode does not use cookies, and serves only public content.
198
 
# Private mode (normal mode) requires login, and only serves files relevant to
199
 
# the logged-in user."""))
200
 
config_options.append(ConfigOption("allowed_uids", "33",
201
 
    """UID of the web server process which will run IVLE.
202
 
Only this user may execute the trampoline. May specify multiple users as
203
 
a comma-separated list.
204
 
    (eg. "1002,78")""",
205
 
    """
206
 
# The User-ID of the web server process which will run IVLE, and any other
207
 
# users who are allowed to run the trampoline. This is stores as a string of
208
 
# comma-separated integers, simply because it is not used within Python, only
209
 
# used by the setup program to write to conf.h (see setup.py config)."""))
210
 
config_options.append(ConfigOption("db_host", "localhost",
211
 
    """PostgreSQL Database config
212
 
==========================
213
 
Hostname of the DB server:""",
214
 
    """
215
 
### PostgreSQL Database config ###
216
 
# Database server hostname"""))
217
 
config_options.append(ConfigOption("db_port", "5432",
218
 
    """Port of the DB server:""",
219
 
    """
220
 
# Database server port"""))
221
 
config_options.append(ConfigOption("db_dbname", "ivle",
222
 
    """Database name:""",
223
 
    """
224
 
# Database name"""))
225
 
config_options.append(ConfigOption("db_user", "postgres",
226
 
    """Username for DB server login:""",
227
 
    """
228
 
# Database username"""))
229
 
config_options.append(ConfigOption("db_password", "",
230
 
    """Password for DB server login:
231
 
    (Caution: This password is stored in plaintext in www/conf/conf.py)""",
232
 
    """
233
 
# Database password"""))
234
 
 
235
 
# Try importing existing conf, but if we can't just set up defaults
236
 
# The reason for this is that these settings are used by other phases
237
 
# of setup besides conf, so we need to know them.
238
 
# Also this allows you to hit Return to accept the existing value.
239
 
try:
240
 
    confmodule = __import__("www/conf/conf")
241
 
    for opt in config_options:
242
 
        try:
243
 
            globals()[opt.option_name] = confmodule.__dict__[opt.option_name]
244
 
        except:
245
 
            globals()[opt.option_name] = opt.default
246
 
except ImportError:
247
 
    # Just set reasonable defaults
248
 
    for opt in config_options:
249
 
        globals()[opt.option_name] = opt.default
250
 
 
251
 
# Try importing install_list, but don't fail if we can't, because listmake can
252
 
# function without it.
253
 
try:
254
 
    import install_list
255
 
except:
256
 
    pass
257
 
 
258
 
# Mime types which will automatically be placed in the list by listmake.
259
 
# Note that listmake is not intended to be run by the final user (the system
260
 
# administrator who installs this), so the developers can customize the list
261
 
# as necessary, and include it in the distribution.
262
 
listmake_mimetypes = ['text/x-python', 'text/html',
263
 
    'application/x-javascript', 'application/javascript',
264
 
    'text/css', 'image/png', 'application/xml']
265
 
 
266
 
# Main function skeleton from Guido van Rossum
267
 
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
268
 
 
269
 
def main(argv=None):
270
 
    if argv is None:
271
 
        argv = sys.argv
272
 
 
273
 
    # Print the opening spiel including the GPL notice
274
 
 
275
 
    print """IVLE - Informatics Virtual Learning Environment Setup
276
 
Copyright (C) 2007-2008 The University of Melbourne
277
 
IVLE comes with ABSOLUTELY NO WARRANTY.
278
 
This is free software, and you are welcome to redistribute it
279
 
under certain conditions. See LICENSE.txt for details.
280
 
 
281
 
IVLE Setup
282
 
"""
283
 
 
284
 
    # First argument is the name of the setup operation
285
 
    try:
286
 
        operation = argv[1]
287
 
    except IndexError:
288
 
        # Print usage message and exit
289
 
        help([])
290
 
        return 1
291
 
 
292
 
    # Disallow run as root unless installing
293
 
    if (operation != 'install' and operation != 'updatejails'
294
 
        and os.geteuid() == 0):
295
 
        print >>sys.stderr, "I do not want to run this stage as root."
296
 
        print >>sys.stderr, "Please run as a normal user."
297
 
        return 1
298
 
    # Call the requested operation's function
299
 
    try:
300
 
        oper_func = {
301
 
            'help' : help,
302
 
            'config' : conf,
303
 
            'build' : build,
304
 
            'listmake' : listmake,
305
 
            'install' : install,
306
 
            'updatejails' : updatejails,
307
 
        }[operation]
308
 
    except KeyError:
309
 
        print >>sys.stderr, (
310
 
            """Invalid operation '%s'. Try python setup.py help."""
311
 
            % operation)
312
 
        return 1
313
 
    return oper_func(argv[2:])
314
 
 
315
 
# Operation functions
316
 
 
317
 
def help(args):
318
 
    if args == []:
319
 
        print """Usage: python setup.py operation [args]
320
 
Operation (and args) can be:
321
 
    help [operation]
322
 
    listmake (developer use only)
323
 
    config [args]
324
 
    build
325
 
    install [--nojail] [--nosubjects] [-n|--dry]
326
 
"""
327
 
        return 1
328
 
    elif len(args) != 1:
329
 
        print """Usage: python setup.py help [operation]"""
330
 
        return 2
331
 
    else:
332
 
        operation = args[0]
333
 
 
334
 
    if operation == 'help':
335
 
        print """python setup.py help [operation]
336
 
Prints the usage message or detailed help on an operation, then exits."""
337
 
    elif operation == 'listmake':
338
 
        print """python setup.py listmake
339
 
(For developer use only)
340
 
Recurses through the source tree and builds a list of all files which should
341
 
be copied upon installation. This should be run by the developer before
342
 
cutting a distribution, and the listfile it generates should be included in
343
 
the distribution, avoiding the administrator having to run it."""
344
 
    elif operation == 'config':
345
 
        print """python setup.py config [args]
346
 
Configures IVLE with machine-specific details, most notably, various paths.
347
 
Either prompts the administrator for these details or accepts them as
348
 
command-line args. Will be interactive only if there are no arguments given.
349
 
Takes defaults from existing conf file if it exists.
350
 
 
351
 
To run IVLE out of the source directory (allowing development without having
352
 
to rebuild/install), just provide ivle_install_dir as the IVLE trunk
353
 
directory, and run build/install one time.
354
 
 
355
 
Creates www/conf/conf.py and trampoline/conf.h.
356
 
 
357
 
Args are:"""
358
 
        for opt in config_options:
359
 
            print "    --" + opt.option_name
360
 
        print """As explained in the interactive prompt or conf.py.
361
 
"""
362
 
    elif operation == 'build':
363
 
        print """python -O setup.py build [--dry|-n]
364
 
Compiles all files and sets up a jail template in the source directory.
365
 
-O is recommended to cause compilation to be optimised.
366
 
Details:
367
 
Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
368
 
Creates jail/.
369
 
Creates standard subdirs inside the jail, eg bin, opt, home, tmp.
370
 
Copies console/ to a location within the jail.
371
 
Copies OS programs and files to corresponding locations within the jail
372
 
  (eg. python and Python libs, ld.so, etc).
373
 
Generates .pyc or .pyo files for all the IVLE .py files.
374
 
 
375
 
--dry | -n  Print out the actions but don't do anything."""
376
 
    elif operation == 'install':
377
 
        print """sudo python setup.py install [--nojail] [--nosubjects][--dry|-n]
378
 
(Requires root)
379
 
Create target install directory ($target).
380
 
Create $target/bin.
381
 
Copy trampoline/trampoline to $target/bin.
382
 
chown and chmod the installed trampoline.
383
 
Copy www/ to $target.
384
 
Copy jail/ to jails template directory (unless --nojail specified).
385
 
Copy subjects/ to subjects directory (unless --nosubjects specified).
386
 
 
387
 
--nojail        Do not copy the jail.
388
 
--nosubjects    Do not copy the subjects and problems directories.
389
 
--dry | -n  Print out the actions but don't do anything."""
390
 
    elif operation == 'updatejails':
391
 
        print """sudo python setup.py updatejails [--dry|-n]
392
 
(Requires root)
393
 
Copy jail/ to each subdirectory in jails directory.
394
 
 
395
 
--dry | -n  Print out the actions but don't do anything."""
396
 
    else:
397
 
        print >>sys.stderr, (
398
 
            """Invalid operation '%s'. Try python setup.py help."""
399
 
            % operation)
400
 
    return 1
401
 
 
402
 
def listmake(args):
403
 
    # We build two separate lists, by walking www and console
404
 
    list_www = build_list_py_files('www')
405
 
    list_console = build_list_py_files('console')
406
 
    list_subjects = build_list_py_files('subjects', no_top_level=True)
407
 
    list_problems = build_list_py_files('problems', no_top_level=True)
408
 
    # Make sure that the files generated by conf are in the list
409
 
    # (since listmake is typically run before conf)
410
 
    if "www/conf/conf.py" not in list_www:
411
 
        list_www.append("www/conf/conf.py")
412
 
    # Make sure that console/python-console is in the list
413
 
    if "console/python-console" not in list_console:
414
 
        list_console.append("console/python-console")
415
 
    # Write these out to a file
416
 
    cwd = os.getcwd()
417
 
    # the files that will be created/overwritten
418
 
    listfile = os.path.join(cwd, "install_list.py")
419
 
 
420
 
    try:
421
 
        file = open(listfile, "w")
422
 
 
423
 
        file.write("""# IVLE Configuration File
424
 
# install_list.py
425
 
# Provides lists of all files to be installed by `setup.py install' from
426
 
# certain directories.
427
 
# Note that any files with the given filename plus 'c' or 'o' (that is,
428
 
# compiled .pyc or .pyo files) will be copied as well.
429
 
 
430
 
# List of all installable files in www directory.
431
 
list_www = """)
432
 
        writelist_pretty(file, list_www)
433
 
        file.write("""
434
 
# List of all installable files in console directory.
435
 
list_console = """)
436
 
        writelist_pretty(file, list_console)
437
 
        file.write("""
438
 
# List of all installable files in subjects directory.
439
 
# This is to install sample subjects and material.
440
 
list_subjects = """)
441
 
        writelist_pretty(file, list_subjects)
442
 
        file.write("""
443
 
# List of all installable files in problems directory.
444
 
# This is to install sample exercise material.
445
 
list_problems = """)
446
 
        writelist_pretty(file, list_problems)
447
 
 
448
 
        file.close()
449
 
    except IOError, (errno, strerror):
450
 
        print "IO error(%s): %s" % (errno, strerror)
451
 
        sys.exit(1)
452
 
 
453
 
    print "Successfully wrote install_list.py"
454
 
 
455
 
    print
456
 
    print ("You may modify the set of installable files before cutting the "
457
 
            "distribution:")
458
 
    print listfile
459
 
    print
460
 
 
461
 
    return 0
462
 
 
463
 
def build_list_py_files(dir, no_top_level=False):
464
 
    """Builds a list of all py files found in a directory and its
465
 
    subdirectories. Returns this as a list of strings.
466
 
    no_top_level=True means the file paths will not include the top-level
467
 
    directory.
468
 
    """
469
 
    pylist = []
470
 
    for (dirpath, dirnames, filenames) in os.walk(dir):
471
 
        # Exclude directories beginning with a '.' (such as '.svn')
472
 
        filter_mutate(lambda x: x[0] != '.', dirnames)
473
 
        # All *.py files are added to the list
474
 
        pylist += [os.path.join(dirpath, item) for item in filenames
475
 
            if mimetypes.guess_type(item)[0] in listmake_mimetypes]
476
 
    if no_top_level:
477
 
        for i in range(0, len(pylist)):
478
 
            _, pylist[i] = pylist[i].split(os.sep, 1)
479
 
    return pylist
480
 
 
481
 
def writelist_pretty(file, list):
482
 
    """Writes a list one element per line, to a file."""
483
 
    if list == []:
484
 
        file.write("[]\n")
485
 
    else:
486
 
        file.write('[\n')
487
 
        for elem in list:
488
 
            file.write('    %s,\n' % repr(elem))
489
 
        file.write(']\n')
490
 
 
491
 
def conf(args):
492
 
    global db_port
493
 
    # Set up some variables
494
 
 
495
 
    cwd = os.getcwd()
496
 
    # the files that will be created/overwritten
497
 
    conffile = os.path.join(cwd, "www/conf/conf.py")
498
 
    conf_hfile = os.path.join(cwd, "trampoline/conf.h")
499
 
 
500
 
    # Get command-line arguments to avoid asking questions.
501
 
 
502
 
    optnames = []
503
 
    for opt in config_options:
504
 
        optnames.append(opt.option_name + "=")
505
 
    (opts, args) = getopt.gnu_getopt(args, "", optnames)
506
 
 
507
 
    if args != []:
508
 
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
509
 
        return 2
510
 
 
511
 
    if opts == []:
512
 
        # Interactive mode. Prompt the user for all the values.
513
 
 
514
 
        print """This tool will create the following files:
515
 
    %s
516
 
    %s
517
 
prompting you for details about your configuration. The file will be
518
 
overwritten if it already exists. It will *not* install or deploy IVLE.
519
 
 
520
 
Please hit Ctrl+C now if you do not wish to do this.
521
 
""" % (conffile, conf_hfile)
522
 
 
523
 
        # Get information from the administrator
524
 
        # If EOF is encountered at any time during the questioning, just exit
525
 
        # silently
526
 
 
527
 
        for opt in config_options:
528
 
            globals()[opt.option_name] = \
529
 
                query_user(globals()[opt.option_name], opt.prompt)
530
 
    else:
531
 
        opts = dict(opts)
532
 
        # Non-interactive mode. Parse the options.
533
 
        for opt in config_options:
534
 
            if '--' + opt.option_name in opts:
535
 
                globals()[opt.option_name] = opts['--' + opt.option_name]
536
 
 
537
 
    # Error handling on input values
538
 
    try:
539
 
        allowed_uids_list = map(int, allowed_uids.split(','))
540
 
    except ValueError:
541
 
        print >>sys.stderr, (
542
 
        "Invalid UID list (%s).\n"
543
 
        "Must be a comma-separated list of integers." % allowed_uids)
544
 
        return 1
545
 
    try:
546
 
        db_port = int(db_port)
547
 
        if db_port < 0 or db_port >= 65536: raise ValueError()
548
 
    except ValueError:
549
 
        print >>sys.stderr, (
550
 
        "Invalid DB port (%s).\n"
551
 
        "Must be an integer between 0 and 65535." % repr(db_port))
552
 
        return 1
553
 
 
554
 
    # Write www/conf/conf.py
555
 
 
556
 
    try:
557
 
        conf = open(conffile, "w")
558
 
 
559
 
        conf.write("""# IVLE Configuration File
560
 
# conf.py
561
 
# Miscellaneous application settings
562
 
 
563
 
""")
564
 
        for opt in config_options:
565
 
            conf.write('%s\n%s = %s\n' % (opt.comment, opt.option_name,
566
 
                repr(globals()[opt.option_name])))
567
 
 
568
 
        conf.close()
569
 
    except IOError, (errno, strerror):
570
 
        print "IO error(%s): %s" % (errno, strerror)
571
 
        sys.exit(1)
572
 
 
573
 
    print "Successfully wrote www/conf/conf.py"
574
 
 
575
 
    # Write trampoline/conf.h
576
 
 
577
 
    try:
578
 
        conf = open(conf_hfile, "w")
579
 
 
580
 
        conf.write("""/* IVLE Configuration File
581
 
 * conf.h
582
 
 * Administrator settings required by trampoline.
583
 
 * Note: trampoline will have to be rebuilt in order for changes to this file
584
 
 * to take effect.
585
 
 */
586
 
 
587
 
/* In the local file system, where are the jails located.
588
 
 * The trampoline does not allow the creation of a jail anywhere besides
589
 
 * jail_base or a subdirectory of jail_base.
590
 
 */
591
 
static const char* jail_base = "%s";
592
 
 
593
 
/* Which user IDs are allowed to run the trampoline.
594
 
 * This list should be limited to the web server user.
595
 
 * (Note that root is an implicit member of this list).
596
 
 */
597
 
static const int allowed_uids[] = { %s };
598
 
""" % (jail_base, repr(allowed_uids_list)[1:-1]))
599
 
 
600
 
        conf.close()
601
 
    except IOError, (errno, strerror):
602
 
        print "IO error(%s): %s" % (errno, strerror)
603
 
        sys.exit(1)
604
 
 
605
 
    print "Successfully wrote trampoline/conf.h"
606
 
 
607
 
    print
608
 
    print "You may modify the configuration at any time by editing"
609
 
    print conffile
610
 
    print conf_hfile
611
 
    print
612
 
    return 0
613
 
 
614
 
def build(args):
615
 
    # Get "dry" variable from command line
616
 
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
617
 
    opts = dict(opts)
618
 
    dry = '-n' in opts or '--dry' in opts
619
 
 
620
 
    if dry:
621
 
        print "Dry run (no actions will be executed\n"
622
 
 
623
 
    # Compile the trampoline
624
 
    curdir = os.getcwd()
625
 
    os.chdir('trampoline')
626
 
    action_runprog('make', [], dry)
627
 
    os.chdir(curdir)
628
 
 
629
 
    # Create the jail and its subdirectories
630
 
    # Note: Other subdirs will be made by copying files
631
 
    action_mkdir('jail', dry)
632
 
    action_mkdir('jail/home', dry)
633
 
    action_mkdir('jail/tmp', dry)
634
 
 
635
 
    # Copy all console and operating system files into the jail
636
 
    action_copylist(install_list.list_console, 'jail/opt/ivle', dry)
637
 
    copy_os_files_jail(dry)
638
 
    # Chmod the python console
639
 
    action_chmod_x('jail/opt/ivle/console/python-console', dry)
640
 
    
641
 
 
642
 
    # Compile .py files into .pyc or .pyo files
643
 
    compileall.compile_dir('www', quiet=True)
644
 
    compileall.compile_dir('console', quiet=True)
645
 
 
646
 
    return 0
647
 
 
648
 
def copy_os_files_jail(dry):
649
 
    """Copies necessary Operating System files from their usual locations
650
 
    into the jail/ directory of the cwd."""
651
 
    # Currently source paths are configured for Ubuntu.
652
 
    for filename in JAIL_FILES:
653
 
        copy_file_to_jail(filename, dry)
654
 
    for src, dst in JAIL_LINKS.items():
655
 
        action_symlink(src, dst, dry)
656
 
    for src, dst in JAIL_COPYTREES.items():
657
 
        action_copytree(src, dst, dry)
658
 
 
659
 
def copy_file_to_jail(src, dry):
660
 
    """Copies a single file from an absolute location into the same location
661
 
    within the jail. src must begin with a '/'. The jail will be located
662
 
    in a 'jail' subdirectory of the current path."""
663
 
    action_copyfile(src, 'jail' + src, dry)
664
 
 
665
 
def install(args):
666
 
    # Get "dry" and "nojail" variables from command line
667
 
    (opts, args) = getopt.gnu_getopt(args, "n",
668
 
        ['dry', 'nojail', 'nosubjects'])
669
 
    opts = dict(opts)
670
 
    dry = '-n' in opts or '--dry' in opts
671
 
    nojail = '--nojail' in opts
672
 
    nosubjects = '--nosubjects' in opts
673
 
 
674
 
    if dry:
675
 
        print "Dry run (no actions will be executed\n"
676
 
 
677
 
    if not dry and os.geteuid() != 0:
678
 
        print >>sys.stderr, "Must be root to run install"
679
 
        print >>sys.stderr, "(I need to chown some files)."
680
 
        return 1
681
 
 
682
 
    # Create the target (install) directory
683
 
    action_mkdir(ivle_install_dir, dry)
684
 
 
685
 
    # Create bin and copy the compiled files there
686
 
    action_mkdir(os.path.join(ivle_install_dir, 'bin'), dry)
687
 
    tramppath = os.path.join(ivle_install_dir, 'bin/trampoline')
688
 
    action_copyfile('trampoline/trampoline', tramppath, dry)
689
 
    # chown trampoline to root and set setuid bit
690
 
    action_chown_setuid(tramppath, dry)
691
 
 
692
 
    # Copy the www directory using the list
693
 
    action_copylist(install_list.list_www, ivle_install_dir, dry)
694
 
 
695
 
    if not nojail:
696
 
        # Copy the local jail directory built by the build action
697
 
        # to the jails template directory (it will be used as a template
698
 
        # for all the students' jails).
699
 
        action_copytree('jail', os.path.join(jail_base, 'template'), dry)
700
 
    if not nosubjects:
701
 
        # Copy the subjects and problems directories across
702
 
        action_copylist(install_list.list_subjects, subjects_base, dry,
703
 
            srcdir="./subjects")
704
 
        action_copylist(install_list.list_problems, problems_base, dry,
705
 
            srcdir="./problems")
706
 
 
707
 
    # Append IVLE path to ivle.pth in python site packages
708
 
    # (Unless it's already there)
709
 
    ivle_pth = os.path.join(sys.prefix,
710
 
        "lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION)
711
 
    ivle_www = os.path.join(ivle_install_dir, "www")
712
 
    write_ivle_pth = True
713
 
    try:
714
 
        file = open(ivle_pth, 'r')
715
 
        for line in file:
716
 
            if line.strip() == ivle_www:
717
 
                write_ivle_pth = False
718
 
                break
719
 
    except (IOError, OSError):
720
 
        pass
721
 
    if write_ivle_pth:
722
 
        action_append(ivle_pth, ivle_www)
723
 
 
724
 
    return 0
725
 
 
726
 
def updatejails(args):
727
 
    # Get "dry" variable from command line
728
 
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
729
 
    opts = dict(opts)
730
 
    dry = '-n' in opts or '--dry' in opts
731
 
 
732
 
    if dry:
733
 
        print "Dry run (no actions will be executed\n"
734
 
 
735
 
    if not dry and os.geteuid() != 0:
736
 
        print >>sys.stderr, "Must be root to run install"
737
 
        print >>sys.stderr, "(I need to chown some files)."
738
 
        return 1
739
 
 
740
 
    # Update the template jail directory in case it hasn't been installed
741
 
    # recently.
742
 
    action_copytree('jail', os.path.join(jail_base, 'template'), dry)
743
 
 
744
 
    # Re-link all the files in all students jails.
745
 
    for dir in os.listdir(jail_base):
746
 
        if dir == 'template': continue
747
 
        # First back up the student's home directory
748
 
        temp_home = os.tmpnam()
749
 
        action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
750
 
        # Delete the student's jail and relink the jail files
751
 
        action_linktree(os.path.join(jail_base, 'template'),
752
 
            os.path.join(jail_base, dir), dry)
753
 
        # Restore the student's home directory
754
 
        action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
755
 
        # Set up the user's home directory just in case they don't have a
756
 
        # directory for this yet
757
 
        action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
758
 
 
759
 
    return 0
760
 
 
761
 
# The actions call Python os functions but print actions and handle dryness.
762
 
# May still throw os exceptions if errors occur.
763
 
 
764
 
class RunError:
765
 
    """Represents an error when running a program (nonzero return)."""
766
 
    def __init__(self, prog, retcode):
767
 
        self.prog = prog
768
 
        self.retcode = retcode
769
 
    def __str__(self):
770
 
        return str(self.prog) + " returned " + repr(self.retcode)
771
 
 
772
 
def action_runprog(prog, args, dry):
773
 
    """Runs a unix program. Searches in $PATH. Synchronous (waits for the
774
 
    program to return). Runs in the current environment. First prints the
775
 
    action as a "bash" line.
776
 
 
777
 
    Throws a RunError with a retcode of the return value of the program,
778
 
    if the program did not return 0.
779
 
 
780
 
    prog: String. Name of the program. (No path required, if in $PATH).
781
 
    args: [String]. Arguments to the program.
782
 
    dry: Bool. If True, prints but does not execute.
783
 
    """
784
 
    print prog, string.join(args, ' ')
785
 
    if dry: return
786
 
    ret = os.spawnvp(os.P_WAIT, prog, args)
787
 
    if ret != 0:
788
 
        raise RunError(prog, ret)
789
 
 
790
 
def action_rename(src, dst, dry):
791
 
    """Calls rename. Deletes the target if it already exists."""
792
 
    if os.access(dst, os.F_OK):
793
 
        print "rm -r", dst
794
 
        if not dry:
795
 
            shutil.rmtree(dst, True)
796
 
    print "mv ", src, dst
797
 
    if dry: return
798
 
    try:
799
 
        os.rename(src, dst)
800
 
    except OSError, (err, msg):
801
 
        if err != errno.EEXIST:
802
 
            raise
803
 
 
804
 
def action_mkdir(path, dry):
805
 
    """Calls mkdir. Silently ignored if the directory already exists.
806
 
    Creates all parent directories as necessary."""
807
 
    print "mkdir -p", path
808
 
    if dry: return
809
 
    try:
810
 
        os.makedirs(path)
811
 
    except OSError, (err, msg):
812
 
        if err != errno.EEXIST:
813
 
            raise
814
 
 
815
 
def action_copytree(src, dst, dry):
816
 
    """Copies an entire directory tree. Symlinks are seen as normal files and
817
 
    copies of the entire file (not the link) are made. Creates all parent
818
 
    directories as necessary.
819
 
 
820
 
    See shutil.copytree."""
821
 
    if os.access(dst, os.F_OK):
822
 
        print "rm -r", dst
823
 
        if not dry:
824
 
            shutil.rmtree(dst, True)
825
 
    print "cp -r", src, dst
826
 
    if dry: return
827
 
    shutil.copytree(src, dst, True)
828
 
 
829
 
def action_linktree(src, dst, dry):
830
 
    """Hard-links an entire directory tree. Same as copytree but the created
831
 
    files are hard-links not actual copies. Removes the existing destination.
832
 
    """
833
 
    if os.access(dst, os.F_OK):
834
 
        print "rm -r", dst
835
 
        if not dry:
836
 
            shutil.rmtree(dst, True)
837
 
    print "<cp with hardlinks> -r", src, dst
838
 
    if dry: return
839
 
    common.makeuser.linktree(src, dst)
840
 
 
841
 
def action_copylist(srclist, dst, dry, srcdir="."):
842
 
    """Copies all files in a list to a new location. The files in the list
843
 
    are read relative to the current directory, and their destinations are the
844
 
    same paths relative to dst. Creates all parent directories as necessary.
845
 
    srcdir is "." by default, can be overridden.
846
 
    """
847
 
    for srcfile in srclist:
848
 
        dstfile = os.path.join(dst, srcfile)
849
 
        srcfile = os.path.join(srcdir, srcfile)
850
 
        dstdir = os.path.split(dstfile)[0]
851
 
        if not os.path.isdir(dstdir):
852
 
            action_mkdir(dstdir, dry)
853
 
        print "cp -f", srcfile, dstfile
854
 
        if not dry:
855
 
            try:
856
 
                shutil.copyfile(srcfile, dstfile)
857
 
                shutil.copymode(srcfile, dstfile)
858
 
            except shutil.Error:
859
 
                pass
860
 
 
861
 
def action_copyfile(src, dst, dry):
862
 
    """Copies one file to a new location. Creates all parent directories
863
 
    as necessary.
864
 
    Warn if file not found.
865
 
    """
866
 
    dstdir = os.path.split(dst)[0]
867
 
    if not os.path.isdir(dstdir):
868
 
        action_mkdir(dstdir, dry)
869
 
    print "cp -f", src, dst
870
 
    if not dry:
871
 
        try:
872
 
            shutil.copyfile(src, dst)
873
 
            shutil.copymode(src, dst)
874
 
        except (shutil.Error, IOError), e:
875
 
            print "Warning: " + str(e)
876
 
 
877
 
def action_symlink(src, dst, dry):
878
 
    """Creates a symlink in a given location. Creates all parent directories
879
 
    as necessary.
880
 
    """
881
 
    dstdir = os.path.split(dst)[0]
882
 
    if not os.path.isdir(dstdir):
883
 
        action_mkdir(dstdir, dry)
884
 
    # Delete existing file
885
 
    if os.path.exists(dst):
886
 
        os.remove(dst)
887
 
    print "ln -fs", src, dst
888
 
    if not dry:
889
 
        os.symlink(src, dst)
890
 
 
891
 
def action_append(ivle_pth, ivle_www):
892
 
    file = open(ivle_pth, 'a+')
893
 
    file.write(ivle_www + '\n')
894
 
    file.close()
895
 
 
896
 
def action_chown_setuid(file, dry):
897
 
    """Chowns a file to root, and sets the setuid bit on the file.
898
 
    Calling this function requires the euid to be root.
899
 
    The actual mode of path is set to: rws--s--s
900
 
    """
901
 
    print "chown root:root", file
902
 
    if not dry:
903
 
        os.chown(file, 0, 0)
904
 
    print "chmod a+xs", file
905
 
    print "chmod u+rw", file
906
 
    if not dry:
907
 
        os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
908
 
            | stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
909
 
 
910
 
def action_chmod_x(file, dry):
911
 
    """Chmod 755 a file (sets permissions to rwxr-xr-x)."""
912
 
    print "chmod 755", file
913
 
    if not dry:
914
 
        os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
915
 
            | stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH | stat.S_IROTH)
916
 
 
917
 
def query_user(default, prompt):
918
 
    """Prompts the user for a string, which is read from a line of stdin.
919
 
    Exits silently if EOF is encountered. Returns the string, with spaces
920
 
    removed from the beginning and end.
921
 
 
922
 
    Returns default if a 0-length line (after spaces removed) was read.
923
 
    """
924
 
    sys.stdout.write('%s\n    (default: "%s")\n>' % (prompt, default))
925
 
    try:
926
 
        val = sys.stdin.readline()
927
 
    except KeyboardInterrupt:
928
 
        # Ctrl+C
929
 
        sys.stdout.write("\n")
930
 
        sys.exit(1)
931
 
    sys.stdout.write("\n")
932
 
    # If EOF, exit
933
 
    if val == '': sys.exit(1)
934
 
    # If empty line, return default
935
 
    val = val.strip()
936
 
    if val == '': return default
937
 
    return val
938
 
 
939
 
def filter_mutate(function, list):
940
 
    """Like built-in filter, but mutates the given list instead of returning a
941
 
    new one. Returns None."""
942
 
    i = len(list)-1
943
 
    while i >= 0:
944
 
        # Delete elements which do not match
945
 
        if not function(list[i]):
946
 
            del list[i]
947
 
        i -= 1
948
 
 
949
 
if __name__ == "__main__":
950
 
    sys.exit(main())