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

97 by mattgiuca
Moved template.py and setup.py to better places.
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.
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
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
118 by mattgiuca
setup.py: Added copytree and copylist actions.
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
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
34
# setup.py conf [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).
97 by mattgiuca
Moved template.py and setup.py to better places.
59
60
import os
119 by mattgiuca
setup.py: Added install action. Completely works!
61
import stat
118 by mattgiuca
setup.py: Added copytree and copylist actions.
62
import shutil
97 by mattgiuca
Moved template.py and setup.py to better places.
63
import sys
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
64
import getopt
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
65
import string
66
import errno
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
67
import mimetypes
116 by mattgiuca
setup.py: mkdir now properly obeys "dry".
68
import compileall
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
69
import getopt
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
70
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
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
251 by mattgiuca
setup.py: Worked the "files to copy into jail" out into a separate list
77
# Operating system files to copy over into the jail.
78
# These will be copied from the given place on the OS file system into the
79
# same place within the jail.
80
JAIL_FILES = [
81
    '/lib/ld-linux.so.2',
82
    '/lib/tls/i686/cmov/libc.so.6',
83
    '/lib/tls/i686/cmov/libdl.so.2',
84
    '/lib/tls/i686/cmov/libm.so.6',
85
    '/lib/tls/i686/cmov/libpthread.so.0',
86
    '/lib/tls/i686/cmov/libutil.so.1',
87
    '/usr/bin/python2.5',
88
]
89
# Symlinks to make within the jail. Src mapped to dst.
90
JAIL_LINKS = {
91
    'python2.5': 'jail/usr/bin/python',
92
}
93
# Trees to copy. Src mapped to dst (these will be passed to action_copytree).
94
JAIL_COPYTREES = {
95
    '/usr/lib/python2.5': 'jail/usr/lib/python2.5',
96
}
97
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
98
# Try importing existing conf, but if we can't just set up defaults
99
# The reason for this is that these settings are used by other phases
100
# of setup besides conf, so we need to know them.
101
# Also this allows you to hit Return to accept the existing value.
102
try:
103
    confmodule = __import__("www/conf/conf")
195 by mattgiuca
Configuration: Moved "default_app" setting from conf/conf.py to conf/apps.py.
104
    try:
105
        root_dir = confmodule.root_dir
106
    except:
107
        root_dir = "/ivle"
108
    try:
109
        ivle_install_dir = confmodule.ivle_install_dir
110
    except:
111
        ivle_install_dir = "/opt/ivle"
112
    try:
113
        jail_base = confmodule.jail_base
114
    except:
115
        jail_base = "/home/informatics/jails"
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
116
except ImportError:
117
    # Just set reasonable defaults
118
    root_dir = "/ivle"
119
    ivle_install_dir = "/opt/ivle"
120
    jail_base = "/home/informatics/jails"
121
# Always defaults
122
allowed_uids = "0"
123
118 by mattgiuca
setup.py: Added copytree and copylist actions.
124
# Try importing install_list, but don't fail if we can't, because listmake can
125
# function without it.
126
try:
127
    import install_list
128
except:
129
    pass
130
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
131
# Mime types which will automatically be placed in the list by listmake.
132
# Note that listmake is not intended to be run by the final user (the system
133
# administrator who installs this), so the developers can customize the list
134
# as necessary, and include it in the distribution.
135
listmake_mimetypes = ['text/x-python', 'text/html',
136
    'application/x-javascript', 'application/javascript',
137
    'text/css', 'image/png']
138
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
139
# Main function skeleton from Guido van Rossum
140
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
141
142
def main(argv=None):
143
    if argv is None:
144
        argv = sys.argv
145
146
    # Print the opening spiel including the GPL notice
147
148
    print """IVLE - Informatics Virtual Learning Environment Setup
97 by mattgiuca
Moved template.py and setup.py to better places.
149
Copyright (C) 2007-2008 The University of Melbourne
150
IVLE comes with ABSOLUTELY NO WARRANTY.
151
This is free software, and you are welcome to redistribute it
152
under certain conditions. See LICENSE.txt for details.
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
153
154
IVLE Setup
155
"""
156
157
    # First argument is the name of the setup operation
158
    try:
159
        operation = argv[1]
160
    except IndexError:
161
        # Print usage message and exit
162
        help([])
163
        return 1
164
131 by mattgiuca
setup.py:
165
    # Disallow run as root unless installing
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
166
    if (operation != 'install' and operation != 'updatejails'
167
        and os.geteuid() == 0):
131 by mattgiuca
setup.py:
168
        print >>sys.stderr, "I do not want to run this stage as root."
169
        print >>sys.stderr, "Please run as a normal user."
170
        return 1
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
171
    # Call the requested operation's function
172
    try:
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
173
        oper_func = {
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
174
            'help' : help,
175
            'conf' : conf,
176
            'build' : build,
177
            'listmake' : listmake,
178
            'install' : install,
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
179
            'updatejails' : updatejails,
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
180
        }[operation]
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
181
    except KeyError:
182
        print >>sys.stderr, (
183
            """Invalid operation '%s'. Try python setup.py help."""
184
            % operation)
129 by mattgiuca
setup.py: Minor fix, exits cleanly if arguments are invalid.
185
        return 1
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
186
    return oper_func(argv[2:])
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
187
188
# Operation functions
189
190
def help(args):
191
    if args == []:
192
        print """Usage: python setup.py operation [args]
193
Operation (and args) can be:
194
    help [operation]
131 by mattgiuca
setup.py:
195
    listmake (developer use only)
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
196
    conf [args]
197
    build
198
    install [--nojail] [-n|--dry]
199
"""
200
        return 1
201
    elif len(args) != 1:
202
        print """Usage: python setup.py help [operation]"""
203
        return 2
204
    else:
205
        operation = args[0]
206
207
    if operation == 'help':
208
        print """python setup.py help [operation]
209
Prints the usage message or detailed help on an operation, then exits."""
118 by mattgiuca
setup.py: Added copytree and copylist actions.
210
    elif operation == 'listmake':
211
        print """python setup.py listmake
212
(For developer use only)
213
Recurses through the source tree and builds a list of all files which should
214
be copied upon installation. This should be run by the developer before
215
cutting a distribution, and the listfile it generates should be included in
216
the distribution, avoiding the administrator having to run it."""
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
217
    elif operation == 'conf':
218
        print """python setup.py conf [args]
219
Configures IVLE with machine-specific details, most notably, various paths.
220
Either prompts the administrator for these details or accepts them as
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
221
command-line args. Will be interactive only if there are no arguments given.
222
Takes defaults from existing conf file if it exists.
133 by mattgiuca
setup.py: Now allows IVLE to be installed over itself, in order to allow
223
224
To run IVLE out of the source directory (allowing development without having
225
to rebuild/install), just provide ivle_install_dir as the IVLE trunk
226
directory, and run build/install one time.
227
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
228
Creates www/conf/conf.py and trampoline/conf.h.
133 by mattgiuca
setup.py: Now allows IVLE to be installed over itself, in order to allow
229
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
230
Args are:
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
231
    --root_dir
232
    --ivle_install_dir
233
    --jail_base
234
    --allowed_uids
235
As explained in the interactive prompt or conf.py.
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
236
"""
237
    elif operation == 'build':
118 by mattgiuca
setup.py: Added copytree and copylist actions.
238
        print """python -O setup.py build [--dry|-n]
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
239
Compiles all files and sets up a jail template in the source directory.
116 by mattgiuca
setup.py: mkdir now properly obeys "dry".
240
-O is recommended to cause compilation to be optimised.
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
241
Details:
242
Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
243
Creates jail/.
244
Creates standard subdirs inside the jail, eg bin, opt, home, tmp.
245
Copies console/ to a location within the jail.
246
Copies OS programs and files to corresponding locations within the jail
247
  (eg. python and Python libs, ld.so, etc).
118 by mattgiuca
setup.py: Added copytree and copylist actions.
248
Generates .pyc or .pyo files for all the IVLE .py files.
249
250
--dry | -n  Print out the actions but don't do anything."""
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
251
    elif operation == 'install':
252
        print """sudo python setup.py install [--nojail] [--dry|-n]
253
(Requires root)
254
Create target install directory ($target).
255
Create $target/bin.
256
Copy trampoline/trampoline to $target/bin.
257
chown and chmod the installed trampoline.
258
Copy www/ to $target.
259
Copy jail/ to jails template directory (unless --nojail specified).
260
261
--nojail    Do not copy the jail.
262
--dry | -n  Print out the actions but don't do anything."""
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
263
    elif operation == 'updatejails':
264
        print """sudo python setup.py updatejails [--dry|-n]
265
(Requires root)
266
Copy jail/ to each subdirectory in jails directory.
267
268
--dry | -n  Print out the actions but don't do anything."""
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
269
    else:
270
        print >>sys.stderr, (
271
            """Invalid operation '%s'. Try python setup.py help."""
272
            % operation)
273
    return 1
274
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
275
def listmake(args):
276
    # We build two separate lists, by walking www and console
277
    list_www = build_list_py_files('www')
278
    list_console = build_list_py_files('console')
279
    # Make sure that the files generated by conf are in the list
280
    # (since listmake is typically run before conf)
281
    if "www/conf/conf.py" not in list_www:
282
        list_www.append("www/conf/conf.py")
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
283
    # Make sure that console/python-console is in the list
284
    if "console/python-console" not in list_console:
285
        list_console.append("console/python-console")
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
286
    # Write these out to a file
287
    cwd = os.getcwd()
288
    # the files that will be created/overwritten
289
    listfile = os.path.join(cwd, "install_list.py")
290
291
    try:
292
        file = open(listfile, "w")
293
294
        file.write("""# IVLE Configuration File
295
# install_list.py
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
296
# Provides lists of all files to be installed by `setup.py install' from
297
# certain directories.
116 by mattgiuca
setup.py: mkdir now properly obeys "dry".
298
# Note that any files with the given filename plus 'c' or 'o' (that is,
299
# compiled .pyc or .pyo files) will be copied as well.
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
300
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
301
# List of all installable files in www directory.
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
302
list_www = """)
303
        writelist_pretty(file, list_www)
304
        file.write("""
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
305
# List of all installable files in console directory.
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
306
list_console = """)
307
        writelist_pretty(file, list_console)
308
309
        file.close()
310
    except IOError, (errno, strerror):
311
        print "IO error(%s): %s" % (errno, strerror)
312
        sys.exit(1)
313
314
    print "Successfully wrote install_list.py"
315
316
    print
317
    print ("You may modify the set of installable files before cutting the "
318
            "distribution:")
319
    print listfile
320
    print
321
322
    return 0
323
324
def build_list_py_files(dir):
325
    """Builds a list of all py files found in a directory and its
326
    subdirectories. Returns this as a list of strings."""
327
    pylist = []
328
    for (dirpath, dirnames, filenames) in os.walk(dir):
329
        # Exclude directories beginning with a '.' (such as '.svn')
330
        filter_mutate(lambda x: x[0] != '.', dirnames)
331
        # All *.py files are added to the list
332
        pylist += [os.path.join(dirpath, item) for item in filenames
117 by mattgiuca
setup.py: listmake uses mimetypes to select all files with certain mime types,
333
            if mimetypes.guess_type(item)[0] in listmake_mimetypes]
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
334
    return pylist
335
336
def writelist_pretty(file, list):
337
    """Writes a list one element per line, to a file."""
338
    if list == []:
339
        file.write("[]\n")
340
    else:
341
        file.write('[\n')
342
        for elem in list:
343
            file.write('    %s,\n' % repr(elem))
344
        file.write(']\n')
345
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
346
def conf(args):
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
347
    global root_dir, ivle_install_dir, jail_base, allowed_uids
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
348
    # Set up some variables
349
350
    cwd = os.getcwd()
351
    # the files that will be created/overwritten
352
    conffile = os.path.join(cwd, "www/conf/conf.py")
353
    conf_hfile = os.path.join(cwd, "trampoline/conf.h")
354
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
355
    # Get command-line arguments to avoid asking questions.
356
357
    (opts, args) = getopt.gnu_getopt(args, "", ['root_dir=',
358
                    'ivle_install_dir=', 'jail_base=', 'allowed_uids='])
359
360
    if args != []:
361
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
362
        return 2
363
364
    if opts == []:
365
        # Interactive mode. Prompt the user for all the values.
366
367
        print """This tool will create the following files:
100 by mattgiuca
setup.py: Added a new config variable, ivle_install_dir.
368
    %s
369
    %s
97 by mattgiuca
Moved template.py and setup.py to better places.
370
prompting you for details about your configuration. The file will be
371
overwritten if it already exists. It will *not* install or deploy IVLE.
372
373
Please hit Ctrl+C now if you do not wish to do this.
100 by mattgiuca
setup.py: Added a new config variable, ivle_install_dir.
374
""" % (conffile, conf_hfile)
97 by mattgiuca
Moved template.py and setup.py to better places.
375
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
376
        # Get information from the administrator
377
        # If EOF is encountered at any time during the questioning, just exit
378
        # silently
97 by mattgiuca
Moved template.py and setup.py to better places.
379
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
380
        root_dir = query_user(root_dir,
381
        """Root directory where IVLE is located (in URL space):""")
382
        ivle_install_dir = query_user(ivle_install_dir,
383
        'Root directory where IVLE will be installed (on the local file '
384
        'system):')
385
        jail_base = query_user(jail_base,
386
        """Root directory where the jails (containing user files) are stored
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
387
(on the local file system):""")
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
388
        allowed_uids = query_user(allowed_uids,
389
        """UID of the web server process which will run IVLE.
112 by mattgiuca
setup.py: A few comment changes.
390
Only this user may execute the trampoline. May specify multiple users as
391
a comma-separated list.
392
    (eg. "1002,78")""")
110 by mattgiuca
setup.py: Added to trampoline/conf.h an "allowed_uids" array. Asks the user
393
120 by mattgiuca
setup.py: Added command-line argument mode for conf. This completely works!
394
    else:
395
        opts = dict(opts)
396
        # Non-interactive mode. Parse the options.
397
        if '--root_dir' in opts:
398
            root_dir = opts['--root_dir']
399
        if '--ivle_install_dir' in opts:
400
            ivle_install_dir = opts['--ivle_install_dir']
401
        if '--jail_base' in opts:
402
            jail_base = opts['--jail_base']
403
        if '--allowed_uids' in opts:
404
            allowed_uids = opts['--allowed_uids']
405
110 by mattgiuca
setup.py: Added to trampoline/conf.h an "allowed_uids" array. Asks the user
406
    # Error handling on input values
407
    try:
112 by mattgiuca
setup.py: A few comment changes.
408
        allowed_uids = map(int, allowed_uids.split(','))
110 by mattgiuca
setup.py: Added to trampoline/conf.h an "allowed_uids" array. Asks the user
409
    except ValueError:
112 by mattgiuca
setup.py: A few comment changes.
410
        print >>sys.stderr, (
411
        "Invalid UID list (%s).\n"
412
        "Must be a comma-separated list of integers." % allowed_uids)
110 by mattgiuca
setup.py: Added to trampoline/conf.h an "allowed_uids" array. Asks the user
413
        return 1
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
414
415
    # Write www/conf/conf.py
416
417
    try:
418
        conf = open(conffile, "w")
419
420
        conf.write("""# IVLE Configuration File
97 by mattgiuca
Moved template.py and setup.py to better places.
421
# conf.py
422
# Miscellaneous application settings
423
424
425
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
426
# with this).
427
# eg. "/" or "/ivle".
100 by mattgiuca
setup.py: Added a new config variable, ivle_install_dir.
428
root_dir = "%s"
429
430
# In the local file system, where IVLE is actually installed.
431
# This directory should contain the "www" and "bin" directories.
432
ivle_install_dir = "%s"
97 by mattgiuca
Moved template.py and setup.py to better places.
433
434
# In the local file system, where are the student/user file spaces located.
435
# The user jails are expected to be located immediately in subdirectories of
436
# this location.
106 by mattgiuca
Renamed "student_dir" to "jail_base" across the suite.
437
jail_base = "%s"
195 by mattgiuca
Configuration: Moved "default_app" setting from conf/conf.py to conf/apps.py.
438
""" % (root_dir, ivle_install_dir, jail_base))
110 by mattgiuca
setup.py: Added to trampoline/conf.h an "allowed_uids" array. Asks the user
439
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
440
        conf.close()
441
    except IOError, (errno, strerror):
442
        print "IO error(%s): %s" % (errno, strerror)
443
        sys.exit(1)
444
445
    print "Successfully wrote www/conf/conf.py"
446
447
    # Write trampoline/conf.h
448
449
    try:
450
        conf = open(conf_hfile, "w")
451
452
        conf.write("""/* IVLE Configuration File
100 by mattgiuca
setup.py: Added a new config variable, ivle_install_dir.
453
 * conf.h
454
 * Administrator settings required by trampoline.
455
 * Note: trampoline will have to be rebuilt in order for changes to this file
456
 * to take effect.
457
 */
458
459
/* In the local file system, where are the jails located.
460
 * The trampoline does not allow the creation of a jail anywhere besides
461
 * jail_base or a subdirectory of jail_base.
462
 */
463
static const char* jail_base = "%s";
110 by mattgiuca
setup.py: Added to trampoline/conf.h an "allowed_uids" array. Asks the user
464
465
/* Which user IDs are allowed to run the trampoline.
466
 * This list should be limited to the web server user.
467
 * (Note that root is an implicit member of this list).
468
 */
112 by mattgiuca
setup.py: A few comment changes.
469
static const int allowed_uids[] = { %s };
470
""" % (jail_base, repr(allowed_uids)[1:-1]))
100 by mattgiuca
setup.py: Added a new config variable, ivle_install_dir.
471
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
472
        conf.close()
473
    except IOError, (errno, strerror):
474
        print "IO error(%s): %s" % (errno, strerror)
475
        sys.exit(1)
476
477
    print "Successfully wrote trampoline/conf.h"
478
479
    print
480
    print "You may modify the configuration at any time by editing"
481
    print conffile
482
    print conf_hfile
483
    print
484
    return 0
485
486
def build(args):
121 by mattgiuca
setup: build and install now read command line options
487
    # Get "dry" variable from command line
488
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
489
    opts = dict(opts)
490
    dry = '-n' in opts or '--dry' in opts
491
492
    if dry:
493
        print "Dry run (no actions will be executed\n"
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
494
495
    # Compile the trampoline
496
    action_runprog('gcc', ['-Wall', '-o', 'trampoline/trampoline',
497
        'trampoline/trampoline.c'], dry)
498
499
    # Create the jail and its subdirectories
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
500
    # Note: Other subdirs will be made by copying files
116 by mattgiuca
setup.py: mkdir now properly obeys "dry".
501
    action_mkdir('jail', dry)
502
    action_mkdir('jail/home', dry)
503
    action_mkdir('jail/tmp', dry)
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
504
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
505
    # Copy all console and operating system files into the jail
118 by mattgiuca
setup.py: Added copytree and copylist actions.
506
    action_copylist(install_list.list_console, 'jail/opt/ivle', dry)
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
507
    copy_os_files_jail(dry)
118 by mattgiuca
setup.py: Added copytree and copylist actions.
508
116 by mattgiuca
setup.py: mkdir now properly obeys "dry".
509
    # Compile .py files into .pyc or .pyo files
510
    compileall.compile_dir('www', quiet=True)
511
    compileall.compile_dir('console', quiet=True)
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
512
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
513
    return 0
514
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
515
def copy_os_files_jail(dry):
516
    """Copies necessary Operating System files from their usual locations
517
    into the jail/ directory of the cwd."""
518
    # Currently source paths are configured for Ubuntu.
251 by mattgiuca
setup.py: Worked the "files to copy into jail" out into a separate list
519
    for filename in JAIL_FILES:
520
        copy_file_to_jail(filename, dry)
521
    for src, dst in JAIL_LINKS.items():
522
        action_symlink(src, dst, dry)
523
    for src, dst in JAIL_COPYTREES.items():
524
        action_copytree(src, dst, dry)
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
525
526
def copy_file_to_jail(src, dry):
527
    """Copies a single file from an absolute location into the same location
528
    within the jail. src must begin with a '/'. The jail will be located
529
    in a 'jail' subdirectory of the current path."""
530
    action_copyfile(src, 'jail' + src, dry)
531
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
532
def install(args):
121 by mattgiuca
setup: build and install now read command line options
533
    # Get "dry" and "nojail" variables from command line
534
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry', 'nojail'])
535
    opts = dict(opts)
536
    dry = '-n' in opts or '--dry' in opts
537
    nojail = '--nojail' in opts
538
539
    if dry:
540
        print "Dry run (no actions will be executed\n"
119 by mattgiuca
setup.py: Added install action. Completely works!
541
542
    if not dry and os.geteuid() != 0:
543
        print >>sys.stderr, "Must be root to run install"
544
        print >>sys.stderr, "(I need to chown some files)."
545
        return 1
546
547
    # Create the target (install) directory
548
    action_mkdir(ivle_install_dir, dry)
549
550
    # Create bin and copy the compiled files there
551
    action_mkdir(os.path.join(ivle_install_dir, 'bin'), dry)
552
    tramppath = os.path.join(ivle_install_dir, 'bin/trampoline')
553
    action_copyfile('trampoline/trampoline', tramppath, dry)
554
    # chown trampoline to root and set setuid bit
555
    action_chown_setuid(tramppath, dry)
556
557
    # Copy the www directory using the list
558
    action_copylist(install_list.list_www, ivle_install_dir, dry)
559
560
    if not nojail:
561
        # Copy the local jail directory built by the build action
562
        # to the jails template directory (it will be used as a template
563
        # for all the students' jails).
564
        action_copytree('jail', os.path.join(jail_base, 'template'), dry)
565
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
566
    return 0
567
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
568
def updatejails(args):
569
    # Get "dry" variable from command line
570
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
571
    opts = dict(opts)
572
    dry = '-n' in opts or '--dry' in opts
573
574
    if dry:
575
        print "Dry run (no actions will be executed\n"
576
577
    if not dry and os.geteuid() != 0:
578
        print >>sys.stderr, "Must be root to run install"
579
        print >>sys.stderr, "(I need to chown some files)."
580
        return 1
581
582
    # Update the template jail directory in case it hasn't been installed
583
    # recently.
584
    action_copytree('jail', os.path.join(jail_base, 'template'), dry)
585
586
    # Re-link all the files in all students jails.
587
    for dir in os.listdir(jail_base):
588
        if dir == 'template': continue
589
        # First back up the student's home directory
590
        temp_home = os.tmpnam()
591
        action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
592
        # Delete the student's jail and relink the jail files
593
        action_linktree(os.path.join(jail_base, 'template'),
594
            os.path.join(jail_base, dir), dry)
595
        # Restore the student's home directory
596
        action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
597
        # Set up the user's home directory just in case they don't have a
598
        # directory for this yet
599
        action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
600
601
    return 0
602
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
603
# The actions call Python os functions but print actions and handle dryness.
604
# May still throw os exceptions if errors occur.
605
108 by mattgiuca
setup.py: Added RunError class. action_runprog now throws a RunError if the
606
class RunError:
607
    """Represents an error when running a program (nonzero return)."""
608
    def __init__(self, prog, retcode):
609
        self.prog = prog
610
        self.retcode = retcode
611
    def __str__(self):
612
        return str(self.prog) + " returned " + repr(self.retcode)
613
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
614
def action_runprog(prog, args, dry):
615
    """Runs a unix program. Searches in $PATH. Synchronous (waits for the
616
    program to return). Runs in the current environment. First prints the
617
    action as a "bash" line.
618
108 by mattgiuca
setup.py: Added RunError class. action_runprog now throws a RunError if the
619
    Throws a RunError with a retcode of the return value of the program,
620
    if the program did not return 0.
621
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
622
    prog: String. Name of the program. (No path required, if in $PATH).
623
    args: [String]. Arguments to the program.
624
    dry: Bool. If True, prints but does not execute.
625
    """
626
    print prog, string.join(args, ' ')
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
627
    if dry: return
628
    ret = os.spawnvp(os.P_WAIT, prog, args)
629
    if ret != 0:
630
        raise RunError(prog, ret)
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
631
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
632
def action_rename(src, dst, dry):
633
    """Calls rename. Deletes the target if it already exists."""
634
    if os.access(dst, os.F_OK):
635
        print "rm -r", dst
636
        if not dry:
637
            shutil.rmtree(dst, True)
638
    print "mv ", src, dst
639
    if dry: return
640
    try:
641
        os.rename(src, dst)
642
    except OSError, (err, msg):
643
        if err != errno.EEXIST:
644
            raise
645
116 by mattgiuca
setup.py: mkdir now properly obeys "dry".
646
def action_mkdir(path, dry):
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
647
    """Calls mkdir. Silently ignored if the directory already exists.
648
    Creates all parent directories as necessary."""
649
    print "mkdir -p", path
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
650
    if dry: return
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
651
    try:
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
652
        os.makedirs(path)
107 by mattgiuca
setup.py: Added "action" functions which encapsulate calling OS functions.
653
    except OSError, (err, msg):
654
        if err != errno.EEXIST:
655
            raise
656
118 by mattgiuca
setup.py: Added copytree and copylist actions.
657
def action_copytree(src, dst, dry):
658
    """Copies an entire directory tree. Symlinks are seen as normal files and
659
    copies of the entire file (not the link) are made. Creates all parent
660
    directories as necessary.
661
662
    See shutil.copytree."""
663
    if os.access(dst, os.F_OK):
664
        print "rm -r", dst
665
        if not dry:
666
            shutil.rmtree(dst, True)
667
    print "cp -r", src, dst
668
    if dry: return
132 by mattgiuca
setup.py: File copying is more robust - preserves symlinks and permissions
669
    shutil.copytree(src, dst, True)
118 by mattgiuca
setup.py: Added copytree and copylist actions.
670
252 by mattgiuca
setup.py: Added action "updatejails" which wipes all student jails, replacing
671
def action_linktree(src, dst, dry):
672
    """Hard-links an entire directory tree. Same as copytree but the created
673
    files are hard-links not actual copies. Removes the existing destination.
674
    """
675
    if os.access(dst, os.F_OK):
676
        print "rm -r", dst
677
        if not dry:
678
            shutil.rmtree(dst, True)
679
    print "<cp with hardlinks> -r", src, dst
680
    if dry: return
681
    common.makeuser.linktree(src, dst)
682
118 by mattgiuca
setup.py: Added copytree and copylist actions.
683
def action_copylist(srclist, dst, dry):
684
    """Copies all files in a list to a new location. The files in the list
685
    are read relative to the current directory, and their destinations are the
686
    same paths relative to dst. Creates all parent directories as necessary.
687
    """
688
    for srcfile in srclist:
689
        dstfile = os.path.join(dst, srcfile)
690
        dstdir = os.path.split(dstfile)[0]
691
        if not os.path.isdir(dstdir):
692
            action_mkdir(dstdir, dry)
693
        print "cp -f", srcfile, dstfile
694
        if not dry:
133 by mattgiuca
setup.py: Now allows IVLE to be installed over itself, in order to allow
695
            try:
696
                shutil.copyfile(srcfile, dstfile)
697
                shutil.copymode(srcfile, dstfile)
698
            except shutil.Error:
699
                pass
118 by mattgiuca
setup.py: Added copytree and copylist actions.
700
119 by mattgiuca
setup.py: Added install action. Completely works!
701
def action_copyfile(src, dst, dry):
702
    """Copies one file to a new location. Creates all parent directories
703
    as necessary.
704
    """
705
    dstdir = os.path.split(dst)[0]
706
    if not os.path.isdir(dstdir):
707
        action_mkdir(dstdir, dry)
708
    print "cp -f", src, dst
709
    if not dry:
133 by mattgiuca
setup.py: Now allows IVLE to be installed over itself, in order to allow
710
        try:
711
            shutil.copyfile(src, dst)
712
            shutil.copymode(src, dst)
713
        except shutil.Error:
714
            pass
119 by mattgiuca
setup.py: Added install action. Completely works!
715
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
716
def action_symlink(src, dst, dry):
717
    """Creates a symlink in a given location. Creates all parent directories
718
    as necessary.
719
    """
720
    dstdir = os.path.split(dst)[0]
721
    if not os.path.isdir(dstdir):
722
        action_mkdir(dstdir, dry)
131 by mattgiuca
setup.py:
723
    # Delete existing file
724
    if os.path.exists(dst):
725
        os.remove(dst)
726
    print "ln -fs", src, dst
122 by mattgiuca
setup.py: build action now copies all operating system files into the jail.
727
    if not dry:
728
        os.symlink(src, dst)
729
119 by mattgiuca
setup.py: Added install action. Completely works!
730
def action_chown_setuid(file, dry):
731
    """Chowns a file to root, and sets the setuid bit on the file.
732
    Calling this function requires the euid to be root.
733
    The actual mode of path is set to: rws--s--s
734
    """
735
    print "chown root:root", file
736
    if not dry:
737
        os.chown(file, 0, 0)
738
    print "chmod a+xs", file
739
    print "chmod u+rw", file
740
    if not dry:
741
        os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
742
            | stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
743
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
744
def query_user(default, prompt):
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
745
    """Prompts the user for a string, which is read from a line of stdin.
746
    Exits silently if EOF is encountered. Returns the string, with spaces
747
    removed from the beginning and end.
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
748
749
    Returns default if a 0-length line (after spaces removed) was read.
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
750
    """
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
751
    sys.stdout.write('%s\n    (default: "%s")\n>' % (prompt, default))
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
752
    try:
753
        val = sys.stdin.readline()
754
    except KeyboardInterrupt:
755
        # Ctrl+C
756
        sys.stdout.write("\n")
757
        sys.exit(1)
758
    sys.stdout.write("\n")
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
759
    # If EOF, exit
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
760
    if val == '': sys.exit(1)
113 by mattgiuca
setup.py: Now loads defaults, if possible, from the existing conf.py.
761
    # If empty line, return default
762
    val = val.strip()
763
    if val == '': return default
764
    return val
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
765
114 by mattgiuca
setup.py: Wrote listmake (and ancillary functions).
766
def filter_mutate(function, list):
767
    """Like built-in filter, but mutates the given list instead of returning a
768
    new one. Returns None."""
769
    i = len(list)-1
770
    while i >= 0:
771
        # Delete elements which do not match
772
        if not function(list[i]):
773
            del list[i]
774
        i -= 1
775
104 by mattgiuca
setup.py: Replaced the simple script with a full options processing script
776
if __name__ == "__main__":
777
    sys.exit(main())