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

« back to all changes in this revision

Viewing changes to setup.py

  • Committer: mattgiuca
  • Date: 2008-02-05 06:29:54 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:418
Renamed trunk/console to trunk/scripts. We are now able to put more scripts in
here such as fileservice.
Added fileservice (empty at the moment).
setup.py, consoleservice: Updated so they refer to scripts now instead of
console directory. (This changes listmake and install_list.py as well).

Added remakeuser.py which lets you recreate a user's jail without creating a
DB entry (but the user is already supposed to exist).

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
# Date:   12/12/2007
22
22
 
23
23
# This is a command-line application, for use by the administrator.
24
 
# This program is a frontend for the modules in the setup packages that 
25
 
# build and install IVLE in separate steps.
 
24
# This program configures, builds and installs IVLE in three separate steps.
26
25
# It is called with at least one argument, which specifies which operation to
27
26
# take.
28
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 lib/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
29
63
import sys
30
 
import setup.build
31
 
import setup.install
 
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(), 'lib'))
 
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 lib/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__("lib/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
32
268
 
33
269
def main(argv=None):
34
270
    if argv is None:
37
273
    # Print the opening spiel including the GPL notice
38
274
 
39
275
    print """IVLE - Informatics Virtual Learning Environment Setup
40
 
Copyright (C) 2007-2009 The University of Melbourne
 
276
Copyright (C) 2007-2008 The University of Melbourne
41
277
IVLE comes with ABSOLUTELY NO WARRANTY.
42
278
This is free software, and you are welcome to redistribute it
43
279
under certain conditions. See LICENSE.txt for details.
53
289
        help([])
54
290
        return 1
55
291
 
56
 
    oper_func = call_operator(operation)
57
 
    return oper_func(argv[2:])
58
 
 
59
 
def help(args):
60
 
    if len(args)!=1:
61
 
        print """Usage: python setup.py operation [options]
62
 
Operation can be:
63
 
    help [operation]
64
 
    build
65
 
    install
66
 
 
67
 
    For help and options for a specific operation use 'help [operation]'."""
68
 
    else:
69
 
        operator = args[0]
70
 
        oper_func = call_operator(operator)
71
 
        oper_func(['operator','--help'])
72
 
 
73
 
def call_operator(operation):
 
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
74
298
    # Call the requested operation's function
75
299
    try:
76
300
        oper_func = {
77
301
            'help' : help,
78
 
            'build' : setup.build.build,
79
 
            'install' : setup.install.install,
 
302
            'config' : conf,
 
303
            'build' : build,
 
304
            'listmake' : listmake,
 
305
            'install' : install,
 
306
            'updatejails' : updatejails,
80
307
        }[operation]
81
308
    except KeyError:
82
309
        print >>sys.stderr, (
83
310
            """Invalid operation '%s'. Try python setup.py help."""
84
311
            % operation)
85
 
        sys.exit(1)
86
 
    return oper_func
 
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 lib/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_lib = build_list_py_files('lib')
 
406
    list_scripts = build_list_py_files('scripts')
 
407
    list_subjects = build_list_py_files('subjects', no_top_level=True)
 
408
    list_problems = build_list_py_files('problems', no_top_level=True)
 
409
    # Make sure that the files generated by conf are in the list
 
410
    # (since listmake is typically run before conf)
 
411
    if "lib/conf/conf.py" not in list_lib:
 
412
        list_www.append("lib/conf/conf.py")
 
413
    # Make sure that console/python-console is in the list
 
414
    if "scripts/python-console" not in list_scripts:
 
415
        list_scripts.append("scripts/python-console")
 
416
    if "scripts/fileservice" not in list_scripts:
 
417
        list_scripts.append("scripts/fileservice")
 
418
    # Write these out to a file
 
419
    cwd = os.getcwd()
 
420
    # the files that will be created/overwritten
 
421
    listfile = os.path.join(cwd, "install_list.py")
 
422
 
 
423
    try:
 
424
        file = open(listfile, "w")
 
425
 
 
426
        file.write("""# IVLE Configuration File
 
427
# install_list.py
 
428
# Provides lists of all files to be installed by `setup.py install' from
 
429
# certain directories.
 
430
# Note that any files with the given filename plus 'c' or 'o' (that is,
 
431
# compiled .pyc or .pyo files) will be copied as well.
 
432
 
 
433
# List of all installable files in www directory.
 
434
list_www = """)
 
435
        writelist_pretty(file, list_www)
 
436
        file.write("""
 
437
# List of all installable files in lib directory.
 
438
list_lib = """)
 
439
        writelist_pretty(file, list_lib)
 
440
        file.write("""
 
441
# List of all installable files in scripts directory.
 
442
list_scripts = """)
 
443
        writelist_pretty(file, list_scripts)
 
444
        file.write("""
 
445
# List of all installable files in subjects directory.
 
446
# This is to install sample subjects and material.
 
447
list_subjects = """)
 
448
        writelist_pretty(file, list_subjects)
 
449
        file.write("""
 
450
# List of all installable files in problems directory.
 
451
# This is to install sample exercise material.
 
452
list_problems = """)
 
453
        writelist_pretty(file, list_problems)
 
454
 
 
455
        file.close()
 
456
    except IOError, (errno, strerror):
 
457
        print "IO error(%s): %s" % (errno, strerror)
 
458
        sys.exit(1)
 
459
 
 
460
    print "Successfully wrote install_list.py"
 
461
 
 
462
    print
 
463
    print ("You may modify the set of installable files before cutting the "
 
464
            "distribution:")
 
465
    print listfile
 
466
    print
 
467
 
 
468
    return 0
 
469
 
 
470
def build_list_py_files(dir, no_top_level=False):
 
471
    """Builds a list of all py files found in a directory and its
 
472
    subdirectories. Returns this as a list of strings.
 
473
    no_top_level=True means the file paths will not include the top-level
 
474
    directory.
 
475
    """
 
476
    pylist = []
 
477
    for (dirpath, dirnames, filenames) in os.walk(dir):
 
478
        # Exclude directories beginning with a '.' (such as '.svn')
 
479
        filter_mutate(lambda x: x[0] != '.', dirnames)
 
480
        # All *.py files are added to the list
 
481
        pylist += [os.path.join(dirpath, item) for item in filenames
 
482
            if mimetypes.guess_type(item)[0] in listmake_mimetypes]
 
483
    if no_top_level:
 
484
        for i in range(0, len(pylist)):
 
485
            _, pylist[i] = pylist[i].split(os.sep, 1)
 
486
    return pylist
 
487
 
 
488
def writelist_pretty(file, list):
 
489
    """Writes a list one element per line, to a file."""
 
490
    if list == []:
 
491
        file.write("[]\n")
 
492
    else:
 
493
        file.write('[\n')
 
494
        for elem in list:
 
495
            file.write('    %s,\n' % repr(elem))
 
496
        file.write(']\n')
 
497
 
 
498
def conf(args):
 
499
    global db_port
 
500
    # Set up some variables
 
501
 
 
502
    cwd = os.getcwd()
 
503
    # the files that will be created/overwritten
 
504
    conffile = os.path.join(cwd, "lib/conf/conf.py")
 
505
    conf_hfile = os.path.join(cwd, "trampoline/conf.h")
 
506
 
 
507
    # Get command-line arguments to avoid asking questions.
 
508
 
 
509
    optnames = []
 
510
    for opt in config_options:
 
511
        optnames.append(opt.option_name + "=")
 
512
    (opts, args) = getopt.gnu_getopt(args, "", optnames)
 
513
 
 
514
    if args != []:
 
515
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
 
516
        return 2
 
517
 
 
518
    if opts == []:
 
519
        # Interactive mode. Prompt the user for all the values.
 
520
 
 
521
        print """This tool will create the following files:
 
522
    %s
 
523
    %s
 
524
prompting you for details about your configuration. The file will be
 
525
overwritten if it already exists. It will *not* install or deploy IVLE.
 
526
 
 
527
Please hit Ctrl+C now if you do not wish to do this.
 
528
""" % (conffile, conf_hfile)
 
529
 
 
530
        # Get information from the administrator
 
531
        # If EOF is encountered at any time during the questioning, just exit
 
532
        # silently
 
533
 
 
534
        for opt in config_options:
 
535
            globals()[opt.option_name] = \
 
536
                query_user(globals()[opt.option_name], opt.prompt)
 
537
    else:
 
538
        opts = dict(opts)
 
539
        # Non-interactive mode. Parse the options.
 
540
        for opt in config_options:
 
541
            if '--' + opt.option_name in opts:
 
542
                globals()[opt.option_name] = opts['--' + opt.option_name]
 
543
 
 
544
    # Error handling on input values
 
545
    try:
 
546
        allowed_uids_list = map(int, allowed_uids.split(','))
 
547
    except ValueError:
 
548
        print >>sys.stderr, (
 
549
        "Invalid UID list (%s).\n"
 
550
        "Must be a comma-separated list of integers." % allowed_uids)
 
551
        return 1
 
552
    try:
 
553
        db_port = int(db_port)
 
554
        if db_port < 0 or db_port >= 65536: raise ValueError()
 
555
    except ValueError:
 
556
        print >>sys.stderr, (
 
557
        "Invalid DB port (%s).\n"
 
558
        "Must be an integer between 0 and 65535." % repr(db_port))
 
559
        return 1
 
560
 
 
561
    # Write lib/conf/conf.py
 
562
 
 
563
    try:
 
564
        conf = open(conffile, "w")
 
565
 
 
566
        conf.write("""# IVLE Configuration File
 
567
# conf.py
 
568
# Miscellaneous application settings
 
569
 
 
570
""")
 
571
        for opt in config_options:
 
572
            conf.write('%s\n%s = %s\n' % (opt.comment, opt.option_name,
 
573
                repr(globals()[opt.option_name])))
 
574
 
 
575
        conf.close()
 
576
    except IOError, (errno, strerror):
 
577
        print "IO error(%s): %s" % (errno, strerror)
 
578
        sys.exit(1)
 
579
 
 
580
    print "Successfully wrote lib/conf/conf.py"
 
581
 
 
582
    # Write trampoline/conf.h
 
583
 
 
584
    try:
 
585
        conf = open(conf_hfile, "w")
 
586
 
 
587
        conf.write("""/* IVLE Configuration File
 
588
 * conf.h
 
589
 * Administrator settings required by trampoline.
 
590
 * Note: trampoline will have to be rebuilt in order for changes to this file
 
591
 * to take effect.
 
592
 */
 
593
 
 
594
/* In the local file system, where are the jails located.
 
595
 * The trampoline does not allow the creation of a jail anywhere besides
 
596
 * jail_base or a subdirectory of jail_base.
 
597
 */
 
598
static const char* jail_base = "%s";
 
599
 
 
600
/* Which user IDs are allowed to run the trampoline.
 
601
 * This list should be limited to the web server user.
 
602
 * (Note that root is an implicit member of this list).
 
603
 */
 
604
static const int allowed_uids[] = { %s };
 
605
""" % (jail_base, repr(allowed_uids_list)[1:-1]))
 
606
 
 
607
        conf.close()
 
608
    except IOError, (errno, strerror):
 
609
        print "IO error(%s): %s" % (errno, strerror)
 
610
        sys.exit(1)
 
611
 
 
612
    print "Successfully wrote trampoline/conf.h"
 
613
 
 
614
    print
 
615
    print "You may modify the configuration at any time by editing"
 
616
    print conffile
 
617
    print conf_hfile
 
618
    print
 
619
    return 0
 
620
 
 
621
def build(args):
 
622
    # Get "dry" variable from command line
 
623
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
 
624
    opts = dict(opts)
 
625
    dry = '-n' in opts or '--dry' in opts
 
626
 
 
627
    if dry:
 
628
        print "Dry run (no actions will be executed\n"
 
629
 
 
630
    # Compile the trampoline
 
631
    curdir = os.getcwd()
 
632
    os.chdir('trampoline')
 
633
    action_runprog('make', [], dry)
 
634
    os.chdir(curdir)
 
635
 
 
636
    # Create the jail and its subdirectories
 
637
    # Note: Other subdirs will be made by copying files
 
638
    action_mkdir('jail', dry)
 
639
    action_mkdir('jail/home', dry)
 
640
    action_mkdir('jail/tmp', dry)
 
641
 
 
642
    # Copy all console and operating system files into the jail
 
643
    action_copylist(install_list.list_scripts, 'jail/opt/ivle', dry)
 
644
    copy_os_files_jail(dry)
 
645
    # Chmod the python console
 
646
    action_chmod_x('jail/opt/ivle/scripts/python-console', dry)
 
647
    action_chmod_x('jail/opt/ivle/scripts/fileservice', dry)
 
648
    
 
649
 
 
650
    # Compile .py files into .pyc or .pyo files
 
651
    compileall.compile_dir('www', quiet=True)
 
652
    compileall.compile_dir('console', quiet=True)
 
653
 
 
654
    return 0
 
655
 
 
656
def copy_os_files_jail(dry):
 
657
    """Copies necessary Operating System files from their usual locations
 
658
    into the jail/ directory of the cwd."""
 
659
    # Currently source paths are configured for Ubuntu.
 
660
    for filename in JAIL_FILES:
 
661
        copy_file_to_jail(filename, dry)
 
662
    for src, dst in JAIL_LINKS.items():
 
663
        action_symlink(src, dst, dry)
 
664
    for src, dst in JAIL_COPYTREES.items():
 
665
        action_copytree(src, dst, dry)
 
666
 
 
667
def copy_file_to_jail(src, dry):
 
668
    """Copies a single file from an absolute location into the same location
 
669
    within the jail. src must begin with a '/'. The jail will be located
 
670
    in a 'jail' subdirectory of the current path."""
 
671
    action_copyfile(src, 'jail' + src, dry)
 
672
 
 
673
def install(args):
 
674
    # Get "dry" and "nojail" variables from command line
 
675
    (opts, args) = getopt.gnu_getopt(args, "n",
 
676
        ['dry', 'nojail', 'nosubjects'])
 
677
    opts = dict(opts)
 
678
    dry = '-n' in opts or '--dry' in opts
 
679
    nojail = '--nojail' in opts
 
680
    nosubjects = '--nosubjects' in opts
 
681
 
 
682
    if dry:
 
683
        print "Dry run (no actions will be executed\n"
 
684
 
 
685
    if not dry and os.geteuid() != 0:
 
686
        print >>sys.stderr, "Must be root to run install"
 
687
        print >>sys.stderr, "(I need to chown some files)."
 
688
        return 1
 
689
 
 
690
    # Create the target (install) directory
 
691
    action_mkdir(ivle_install_dir, dry)
 
692
 
 
693
    # Create bin and copy the compiled files there
 
694
    action_mkdir(os.path.join(ivle_install_dir, 'bin'), dry)
 
695
    tramppath = os.path.join(ivle_install_dir, 'bin/trampoline')
 
696
    action_copyfile('trampoline/trampoline', tramppath, dry)
 
697
    # chown trampoline to root and set setuid bit
 
698
    action_chown_setuid(tramppath, dry)
 
699
 
 
700
    # Copy the www and lib directories using the list
 
701
    action_copylist(install_list.list_www, ivle_install_dir, dry)
 
702
    action_copylist(install_list.list_lib, ivle_install_dir, dry)
 
703
 
 
704
    if not nojail:
 
705
        # Copy the local jail directory built by the build action
 
706
        # to the jails template directory (it will be used as a template
 
707
        # for all the students' jails).
 
708
        action_copytree('jail', os.path.join(jail_base, 'template'), dry)
 
709
    if not nosubjects:
 
710
        # Copy the subjects and problems directories across
 
711
        action_copylist(install_list.list_subjects, subjects_base, dry,
 
712
            srcdir="./subjects")
 
713
        action_copylist(install_list.list_problems, problems_base, dry,
 
714
            srcdir="./problems")
 
715
 
 
716
    # Append IVLE path to ivle.pth in python site packages
 
717
    # (Unless it's already there)
 
718
    ivle_pth = os.path.join(sys.prefix,
 
719
        "lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION)
 
720
    ivle_www = os.path.join(ivle_install_dir, "www")
 
721
    ivle_lib = os.path.join(ivle_install_dir, "lib")
 
722
    write_ivle_pth = True
 
723
    write_ivle_lib_pth = True
 
724
    try:
 
725
        file = open(ivle_pth, 'r')
 
726
        for line in file:
 
727
            if line.strip() == ivle_www:
 
728
                write_ivle_pth = False
 
729
            elif line.strip() == ivle_lib:
 
730
                write_ivle_lib_pth = False
 
731
        file.close()
 
732
    except (IOError, OSError):
 
733
        pass
 
734
    if write_ivle_pth:
 
735
        action_append(ivle_pth, ivle_www)
 
736
    if write_ivle_lib_pth:
 
737
        action_append(ivle_pth, ivle_lib)
 
738
 
 
739
    return 0
 
740
 
 
741
def updatejails(args):
 
742
    # Get "dry" variable from command line
 
743
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
 
744
    opts = dict(opts)
 
745
    dry = '-n' in opts or '--dry' in opts
 
746
 
 
747
    if dry:
 
748
        print "Dry run (no actions will be executed\n"
 
749
 
 
750
    if not dry and os.geteuid() != 0:
 
751
        print >>sys.stderr, "Must be root to run install"
 
752
        print >>sys.stderr, "(I need to chown some files)."
 
753
        return 1
 
754
 
 
755
    # Update the template jail directory in case it hasn't been installed
 
756
    # recently.
 
757
    action_copytree('jail', os.path.join(jail_base, 'template'), dry)
 
758
 
 
759
    # Re-link all the files in all students jails.
 
760
    for dir in os.listdir(jail_base):
 
761
        if dir == 'template': continue
 
762
        # First back up the student's home directory
 
763
        temp_home = os.tmpnam()
 
764
        action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
 
765
        # Delete the student's jail and relink the jail files
 
766
        action_linktree(os.path.join(jail_base, 'template'),
 
767
            os.path.join(jail_base, dir), dry)
 
768
        # Restore the student's home directory
 
769
        action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
 
770
        # Set up the user's home directory just in case they don't have a
 
771
        # directory for this yet
 
772
        action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
 
773
 
 
774
    return 0
 
775
 
 
776
# The actions call Python os functions but print actions and handle dryness.
 
777
# May still throw os exceptions if errors occur.
 
778
 
 
779
class RunError:
 
780
    """Represents an error when running a program (nonzero return)."""
 
781
    def __init__(self, prog, retcode):
 
782
        self.prog = prog
 
783
        self.retcode = retcode
 
784
    def __str__(self):
 
785
        return str(self.prog) + " returned " + repr(self.retcode)
 
786
 
 
787
def action_runprog(prog, args, dry):
 
788
    """Runs a unix program. Searches in $PATH. Synchronous (waits for the
 
789
    program to return). Runs in the current environment. First prints the
 
790
    action as a "bash" line.
 
791
 
 
792
    Throws a RunError with a retcode of the return value of the program,
 
793
    if the program did not return 0.
 
794
 
 
795
    prog: String. Name of the program. (No path required, if in $PATH).
 
796
    args: [String]. Arguments to the program.
 
797
    dry: Bool. If True, prints but does not execute.
 
798
    """
 
799
    print prog, string.join(args, ' ')
 
800
    if dry: return
 
801
    ret = os.spawnvp(os.P_WAIT, prog, args)
 
802
    if ret != 0:
 
803
        raise RunError(prog, ret)
 
804
 
 
805
def action_rename(src, dst, dry):
 
806
    """Calls rename. Deletes the target if it already exists."""
 
807
    if os.access(dst, os.F_OK):
 
808
        print "rm -r", dst
 
809
        if not dry:
 
810
            shutil.rmtree(dst, True)
 
811
    print "mv ", src, dst
 
812
    if dry: return
 
813
    try:
 
814
        os.rename(src, dst)
 
815
    except OSError, (err, msg):
 
816
        if err != errno.EEXIST:
 
817
            raise
 
818
 
 
819
def action_mkdir(path, dry):
 
820
    """Calls mkdir. Silently ignored if the directory already exists.
 
821
    Creates all parent directories as necessary."""
 
822
    print "mkdir -p", path
 
823
    if dry: return
 
824
    try:
 
825
        os.makedirs(path)
 
826
    except OSError, (err, msg):
 
827
        if err != errno.EEXIST:
 
828
            raise
 
829
 
 
830
def action_copytree(src, dst, dry):
 
831
    """Copies an entire directory tree. Symlinks are seen as normal files and
 
832
    copies of the entire file (not the link) are made. Creates all parent
 
833
    directories as necessary.
 
834
 
 
835
    See shutil.copytree."""
 
836
    if os.access(dst, os.F_OK):
 
837
        print "rm -r", dst
 
838
        if not dry:
 
839
            shutil.rmtree(dst, True)
 
840
    print "cp -r", src, dst
 
841
    if dry: return
 
842
    shutil.copytree(src, dst, True)
 
843
 
 
844
def action_linktree(src, dst, dry):
 
845
    """Hard-links an entire directory tree. Same as copytree but the created
 
846
    files are hard-links not actual copies. Removes the existing destination.
 
847
    """
 
848
    if os.access(dst, os.F_OK):
 
849
        print "rm -r", dst
 
850
        if not dry:
 
851
            shutil.rmtree(dst, True)
 
852
    print "<cp with hardlinks> -r", src, dst
 
853
    if dry: return
 
854
    common.makeuser.linktree(src, dst)
 
855
 
 
856
def action_copylist(srclist, dst, dry, srcdir="."):
 
857
    """Copies all files in a list to a new location. The files in the list
 
858
    are read relative to the current directory, and their destinations are the
 
859
    same paths relative to dst. Creates all parent directories as necessary.
 
860
    srcdir is "." by default, can be overridden.
 
861
    """
 
862
    for srcfile in srclist:
 
863
        dstfile = os.path.join(dst, srcfile)
 
864
        srcfile = os.path.join(srcdir, srcfile)
 
865
        dstdir = os.path.split(dstfile)[0]
 
866
        if not os.path.isdir(dstdir):
 
867
            action_mkdir(dstdir, dry)
 
868
        print "cp -f", srcfile, dstfile
 
869
        if not dry:
 
870
            try:
 
871
                shutil.copyfile(srcfile, dstfile)
 
872
                shutil.copymode(srcfile, dstfile)
 
873
            except shutil.Error:
 
874
                pass
 
875
 
 
876
def action_copyfile(src, dst, dry):
 
877
    """Copies one file to a new location. Creates all parent directories
 
878
    as necessary.
 
879
    Warn if file not found.
 
880
    """
 
881
    dstdir = os.path.split(dst)[0]
 
882
    if not os.path.isdir(dstdir):
 
883
        action_mkdir(dstdir, dry)
 
884
    print "cp -f", src, dst
 
885
    if not dry:
 
886
        try:
 
887
            shutil.copyfile(src, dst)
 
888
            shutil.copymode(src, dst)
 
889
        except (shutil.Error, IOError), e:
 
890
            print "Warning: " + str(e)
 
891
 
 
892
def action_symlink(src, dst, dry):
 
893
    """Creates a symlink in a given location. Creates all parent directories
 
894
    as necessary.
 
895
    """
 
896
    dstdir = os.path.split(dst)[0]
 
897
    if not os.path.isdir(dstdir):
 
898
        action_mkdir(dstdir, dry)
 
899
    # Delete existing file
 
900
    if os.path.exists(dst):
 
901
        os.remove(dst)
 
902
    print "ln -fs", src, dst
 
903
    if not dry:
 
904
        os.symlink(src, dst)
 
905
 
 
906
def action_append(ivle_pth, ivle_www):
 
907
    file = open(ivle_pth, 'a+')
 
908
    file.write(ivle_www + '\n')
 
909
    file.close()
 
910
 
 
911
def action_chown_setuid(file, dry):
 
912
    """Chowns a file to root, and sets the setuid bit on the file.
 
913
    Calling this function requires the euid to be root.
 
914
    The actual mode of path is set to: rws--s--s
 
915
    """
 
916
    print "chown root:root", file
 
917
    if not dry:
 
918
        os.chown(file, 0, 0)
 
919
    print "chmod a+xs", file
 
920
    print "chmod u+rw", file
 
921
    if not dry:
 
922
        os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
 
923
            | stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
 
924
 
 
925
def action_chmod_x(file, dry):
 
926
    """Chmod 755 a file (sets permissions to rwxr-xr-x)."""
 
927
    print "chmod 755", file
 
928
    if not dry:
 
929
        os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
 
930
            | stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH | stat.S_IROTH)
 
931
 
 
932
def query_user(default, prompt):
 
933
    """Prompts the user for a string, which is read from a line of stdin.
 
934
    Exits silently if EOF is encountered. Returns the string, with spaces
 
935
    removed from the beginning and end.
 
936
 
 
937
    Returns default if a 0-length line (after spaces removed) was read.
 
938
    """
 
939
    sys.stdout.write('%s\n    (default: "%s")\n>' % (prompt, default))
 
940
    try:
 
941
        val = sys.stdin.readline()
 
942
    except KeyboardInterrupt:
 
943
        # Ctrl+C
 
944
        sys.stdout.write("\n")
 
945
        sys.exit(1)
 
946
    sys.stdout.write("\n")
 
947
    # If EOF, exit
 
948
    if val == '': sys.exit(1)
 
949
    # If empty line, return default
 
950
    val = val.strip()
 
951
    if val == '': return default
 
952
    return val
 
953
 
 
954
def filter_mutate(function, list):
 
955
    """Like built-in filter, but mutates the given list instead of returning a
 
956
    new one. Returns None."""
 
957
    i = len(list)-1
 
958
    while i >= 0:
 
959
        # Delete elements which do not match
 
960
        if not function(list[i]):
 
961
            del list[i]
 
962
        i -= 1
87
963
 
88
964
if __name__ == "__main__":
89
965
    sys.exit(main())
90