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

« back to all changes in this revision

Viewing changes to setup.py

  • Committer: mattgiuca
  • Date: 2008-01-12 15:35:53 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:201
Added "test" directory.
Added make_date_test.py, a short script I wrote to test the date format
algorithm committed in the previous revision.

Show diffs side-by-side

added added

removed removed

Lines of Context:
31
31
# cutting a distribution, and the listfile it generates should be included in
32
32
# the distribution, avoiding the administrator having to run it.
33
33
 
34
 
# setup.py config [args]
 
34
# setup.py conf [args]
35
35
# Configures IVLE with machine-specific details, most notably, various paths.
36
36
# Either prompts the administrator for these details or accepts them as
37
37
# command-line args.
38
 
# Creates lib/conf/conf.py and trampoline/conf.h.
 
38
# Creates www/conf/conf.py and trampoline/conf.h.
39
39
 
40
40
# setup.py build
41
41
# Compiles all files and sets up a jail template in the source directory.
67
67
import mimetypes
68
68
import compileall
69
69
import getopt
70
 
import hashlib
71
 
import uuid
72
 
 
73
 
# Import modules from the website is tricky since they're in the www
74
 
# directory.
75
 
sys.path.append(os.path.join(os.getcwd(), 'lib'))
76
 
import conf
77
 
import common.makeuser
78
 
 
79
 
# Determine which Python version (2.4 or 2.5, for example) we are running,
80
 
# and use that as the filename to the Python directory.
81
 
# Just get the first 3 characters of sys.version.
82
 
PYTHON_VERSION = sys.version[0:3]
83
 
 
84
 
# Operating system files to copy over into the jail.
85
 
# These will be copied from the given place on the OS file system into the
86
 
# same place within the jail.
87
 
JAIL_FILES = [
88
 
    '/lib/ld-linux.so.2',
89
 
    '/lib/tls/i686/cmov/libc.so.6',
90
 
    '/lib/tls/i686/cmov/libdl.so.2',
91
 
    '/lib/tls/i686/cmov/libm.so.6',
92
 
    '/lib/tls/i686/cmov/libpthread.so.0',
93
 
    '/lib/tls/i686/cmov/libutil.so.1',
94
 
    '/etc/ld.so.conf',
95
 
    '/etc/ld.so.cache',
96
 
    # These 2 files do not exist in Ubuntu
97
 
    #'/etc/ld.so.preload',
98
 
    #'/etc/ld.so.nohwcap',
99
 
    # UNIX commands
100
 
    '/usr/bin/strace',
101
 
    '/bin/ls',
102
 
    '/bin/echo',
103
 
    # Needed by python
104
 
    '/usr/bin/python%s' % PYTHON_VERSION,
105
 
    # Needed by fileservice
106
 
    '/lib/libcom_err.so.2',
107
 
    '/lib/libcrypt.so.1',
108
 
    '/lib/libkeyutils.so.1',
109
 
    '/lib/libresolv.so.2',
110
 
    '/lib/librt.so.1',
111
 
    '/lib/libuuid.so.1',
112
 
    '/usr/lib/libapr-1.so.0',
113
 
    '/usr/lib/libaprutil-1.so.0',
114
 
    '/usr/lib/libdb-4.4.so',
115
 
    '/usr/lib/libexpat.so.1',
116
 
    '/usr/lib/libgcrypt.so.11',
117
 
    '/usr/lib/libgnutls.so.13',
118
 
    '/usr/lib/libgpg-error.so.0',
119
 
    '/usr/lib/libgssapi_krb5.so.2',
120
 
    '/usr/lib/libk5crypto.so.3',
121
 
    '/usr/lib/libkrb5.so.3',
122
 
    '/usr/lib/libkrb5support.so.0',
123
 
    '/usr/lib/liblber.so.2',
124
 
    '/usr/lib/libldap_r.so.2',
125
 
    '/usr/lib/libneon.so.26',
126
 
    '/usr/lib/libpq.so.5',
127
 
    '/usr/lib/libsasl2.so.2',
128
 
    '/usr/lib/libsqlite3.so.0',
129
 
    '/usr/lib/libsvn_client-1.so.1',
130
 
    '/usr/lib/libsvn_delta-1.so.1',
131
 
    '/usr/lib/libsvn_diff-1.so.1',
132
 
    '/usr/lib/libsvn_fs-1.so.1',
133
 
    '/usr/lib/libsvn_fs_base-1.so.1',
134
 
    '/usr/lib/libsvn_fs_fs-1.so.1',
135
 
    '/usr/lib/libsvn_ra-1.so.1',
136
 
    '/usr/lib/libsvn_ra_dav-1.so.1',
137
 
    '/usr/lib/libsvn_ra_local-1.so.1',
138
 
    '/usr/lib/libsvn_ra_svn-1.so.1',
139
 
    '/usr/lib/libsvn_repos-1.so.1',
140
 
    '/usr/lib/libsvn_subr-1.so.1',
141
 
    '/usr/lib/libsvn_wc-1.so.1',
142
 
    '/usr/lib/libtasn1.so.3',
143
 
    '/usr/lib/libxml2.so.2',
144
 
    # Needed by matplotlib
145
 
    '/usr/lib/i686/cmov/libssl.so.0.9.8',
146
 
    '/usr/lib/i686/cmov/libcrypto.so.0.9.8',
147
 
    '/lib/tls/i686/cmov/libnsl.so.1',
148
 
    '/usr/lib/libz.so.1',
149
 
    '/usr/lib/atlas/liblapack.so.3',
150
 
    '/usr/lib/atlas/libblas.so.3',
151
 
    '/usr/lib/libg2c.so.0',
152
 
    '/usr/lib/libstdc++.so.6',
153
 
    '/usr/lib/libfreetype.so.6',
154
 
    '/usr/lib/libpng12.so.0',
155
 
    '/usr/lib/libBLT.2.4.so.8.4',
156
 
    '/usr/lib/libtk8.4.so.0',
157
 
    '/usr/lib/libtcl8.4.so.0',
158
 
    '/usr/lib/tcl8.4/init.tcl',
159
 
    '/usr/lib/libX11.so.6',
160
 
    '/usr/lib/libXau.so.6',
161
 
    '/usr/lib/libXdmcp.so.6',
162
 
    '/lib/libgcc_s.so.1',
163
 
    '/etc/matplotlibrc',
164
 
    # Needed for resolv
165
 
    '/lib/libnss_dns.so.2',
166
 
    #'/lib/libnss_mdns4.so',
167
 
    '/etc/hosts',
168
 
    '/etc/resolv.conf',
169
 
    #'/etc/hosts.conf',
170
 
    #'/etc/hostname',
171
 
    '/etc/nsswitch.conf',
172
 
    '/lib/libnss_files.so.2',
173
 
]
174
 
# Symlinks to make within the jail. Src mapped to dst.
175
 
JAIL_LINKS = {
176
 
    'python%s' % PYTHON_VERSION: 'jail/usr/bin/python',
177
 
}
178
 
# Trees to copy. Src mapped to dst (these will be passed to action_copytree).
179
 
JAIL_COPYTREES = {
180
 
    '/usr/lib/python%s' % PYTHON_VERSION:
181
 
        'jail/usr/lib/python%s' % PYTHON_VERSION,
182
 
    '/usr/share/matplotlib': 'jail/usr/share/matplotlib',
183
 
    '/etc/ld.so.conf.d': 'jail/etc/ld.so.conf.d',
184
 
}
185
 
 
186
 
class ConfigOption:
187
 
    """A configuration option; one of the things written to conf.py."""
188
 
    def __init__(self, option_name, default, prompt, comment):
189
 
        """Creates a configuration option.
190
 
        option_name: Name of the variable in conf.py. Also name of the
191
 
            command-line argument to setup.py conf.
192
 
        default: Default value for this variable.
193
 
        prompt: (Short) string presented during the interactive prompt in
194
 
            setup.py conf.
195
 
        comment: (Long) comment string stored in conf.py. Each line of this
196
 
            string should begin with a '#'.
197
 
        """
198
 
        self.option_name = option_name
199
 
        self.default = default
200
 
        self.prompt = prompt
201
 
        self.comment = comment
202
 
 
203
 
# Configuration options, defaults and descriptions
204
 
config_options = []
205
 
config_options.append(ConfigOption("root_dir", "/",
206
 
    """Root directory where IVLE is located (in URL space):""",
207
 
    """
208
 
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
209
 
# with this).
210
 
# eg. "/" or "/ivle"."""))
211
 
config_options.append(ConfigOption("ivle_install_dir", "/opt/ivle",
212
 
    'Root directory where IVLE will be installed (on the local file '
213
 
    'system):',
214
 
    """
215
 
# In the local file system, where IVLE is actually installed.
216
 
# This directory should contain the "www" and "bin" directories."""))
217
 
config_options.append(ConfigOption("jail_base", "/home/informatics/jails",
218
 
    """Location of Directories
219
 
=======================
220
 
Root directory where the jails (containing user files) are stored
221
 
(on the local file system):""",
222
 
    """
223
 
# In the local file system, where are the student/user file spaces located.
224
 
# The user jails are expected to be located immediately in subdirectories of
225
 
# this location."""))
226
 
config_options.append(ConfigOption("subjects_base",
227
 
    "/home/informatics/subjects",
228
 
    """Root directory where the subject directories (containing worksheets
229
 
and other per-subject files) are stored (on the local file system):""",
230
 
    """
231
 
# In the local file system, where are the per-subject file spaces located.
232
 
# The individual subject directories are expected to be located immediately
233
 
# in subdirectories of this location."""))
234
 
config_options.append(ConfigOption("exercises_base",
235
 
    "/home/informatics/exercises",
236
 
    """Root directory where the exercise directories (containing
237
 
subject-independent exercise sheets) are stored (on the local file
238
 
system):""",
239
 
    """
240
 
# In the local file system, where are the subject-independent exercise sheet
241
 
# file spaces located."""))
242
 
config_options.append(ConfigOption("tos_path",
243
 
    "/home/informatics/tos.html",
244
 
    """Location where the Terms of Service document is stored (on the local
245
 
    file system):""",
246
 
    """
247
 
# In the local file system, where is the Terms of Service document located."""))
248
 
config_options.append(ConfigOption("public_host", "public.localhost",
249
 
    """Hostname which will cause the server to go into "public mode",
250
 
providing login-free access to student's published work:""",
251
 
    """
252
 
# The server goes into "public mode" if the browser sends a request with this
253
 
# host. This is for security reasons - we only serve public student files on a
254
 
# separate domain to the main IVLE site.
255
 
# Public mode does not use cookies, and serves only public content.
256
 
# Private mode (normal mode) requires login, and only serves files relevant to
257
 
# the logged-in user."""))
258
 
config_options.append(ConfigOption("allowed_uids", "33",
259
 
    """UID of the web server process which will run IVLE.
260
 
Only this user may execute the trampoline. May specify multiple users as
261
 
a comma-separated list.
262
 
    (eg. "1002,78")""",
263
 
    """
264
 
# The User-ID of the web server process which will run IVLE, and any other
265
 
# users who are allowed to run the trampoline. This is stores as a string of
266
 
# comma-separated integers, simply because it is not used within Python, only
267
 
# used by the setup program to write to conf.h (see setup.py config)."""))
268
 
config_options.append(ConfigOption("db_host", "localhost",
269
 
    """PostgreSQL Database config
270
 
==========================
271
 
Hostname of the DB server:""",
272
 
    """
273
 
### PostgreSQL Database config ###
274
 
# Database server hostname"""))
275
 
config_options.append(ConfigOption("db_port", "5432",
276
 
    """Port of the DB server:""",
277
 
    """
278
 
# Database server port"""))
279
 
config_options.append(ConfigOption("db_dbname", "ivle",
280
 
    """Database name:""",
281
 
    """
282
 
# Database name"""))
283
 
config_options.append(ConfigOption("db_forumdbname", "ivle_forum",
284
 
    """Forum Database name:""",
285
 
    """
286
 
# Forum Database name"""))
287
 
config_options.append(ConfigOption("db_user", "postgres",
288
 
    """Username for DB server login:""",
289
 
    """
290
 
# Database username"""))
291
 
config_options.append(ConfigOption("db_password", "",
292
 
    """Password for DB server login:
293
 
    (Caution: This password is stored in plaintext in lib/conf/conf.py)""",
294
 
    """
295
 
# Database password"""))
296
 
config_options.append(ConfigOption("auth_modules", "ldap_auth",
297
 
    """Authentication config
298
 
=====================
299
 
Comma-separated list of authentication modules. Only "ldap" is available
300
 
by default.""",
301
 
    """
302
 
# Comma-separated list of authentication modules.
303
 
# These refer to importable Python modules in the www/auth directory.
304
 
# Modules "ldap" and "guest" are available in the source tree, but
305
 
# other modules may be plugged in to auth against organisation-specific
306
 
# auth backends."""))
307
 
config_options.append(ConfigOption("ldap_url", "ldaps://www.example.com",
308
 
    """(LDAP options are only relevant if "ldap" is included in the list of
309
 
auth modules).
310
 
URL for LDAP authentication server:""",
311
 
    """
312
 
# URL for LDAP authentication server"""))
313
 
config_options.append(ConfigOption("ldap_format_string",
314
 
    "uid=%s,ou=users,o=example",
315
 
    """Format string for LDAP auth request:
316
 
    (Must contain a single "%s" for the user's login name)""",
317
 
    """
318
 
# Format string for LDAP auth request
319
 
# (Must contain a single "%s" for the user's login name)"""))
320
 
config_options.append(ConfigOption("svn_addr", "http://svn.localhost/",
321
 
    """Subversion config
322
 
=================
323
 
The base url for accessing subversion repositories:""",
324
 
    """
325
 
# The base url for accessing subversion repositories."""))
326
 
config_options.append(ConfigOption("svn_conf", "/opt/ivle/svn/svn.conf",
327
 
    """The location of the subversion configuration file used by apache
328
 
to host the user repositories:""",
329
 
    """
330
 
# The location of the subversion configuration file used by
331
 
# apache to host the user repositories."""))
332
 
config_options.append(ConfigOption("svn_repo_path", "/home/informatics/repositories",
333
 
    """The root directory for the subversion repositories:""",
334
 
    """
335
 
# The root directory for the subversion repositories."""))
336
 
config_options.append(ConfigOption("svn_auth_ivle", "/opt/ivle/svn/ivle.auth",
337
 
    """The location of the password file used to authenticate users
338
 
of the subversion repository from the ivle server:""",
339
 
    """
340
 
# The location of the password file used to authenticate users
341
 
# of the subversion repository from the ivle server."""))
342
 
config_options.append(ConfigOption("svn_auth_local", "/opt/ivle/svn/local.auth",
343
 
    """The location of the password file used to authenticate local users
344
 
of the subversion repository:""",
345
 
    """
346
 
# The location of the password file used to authenticate local users
347
 
# of the subversion repository."""))
348
 
config_options.append(ConfigOption("usrmgt_host", "localhost",
349
 
    """User Management Server config
350
 
============================
351
 
The hostname where the usrmgt-server runs:""",
352
 
    """
353
 
# The hostname where the usrmgt-server runs."""))
354
 
config_options.append(ConfigOption("usrmgt_port", "2178",
355
 
    """The port where the usrmgt-server runs:""",
356
 
    """
357
 
# The port where the usrmgt-server runs."""))
358
 
config_options.append(ConfigOption("usrmgt_magic", "",
359
 
    """The password for the usrmgt-server:""",
360
 
    """
361
 
# The password for the usrmgt-server."""))
362
70
 
363
71
# Try importing existing conf, but if we can't just set up defaults
364
72
# The reason for this is that these settings are used by other phases
365
73
# of setup besides conf, so we need to know them.
366
74
# Also this allows you to hit Return to accept the existing value.
367
75
try:
368
 
    confmodule = __import__("lib/conf/conf")
369
 
    for opt in config_options:
370
 
        try:
371
 
            globals()[opt.option_name] = confmodule.__dict__[opt.option_name]
372
 
        except:
373
 
            globals()[opt.option_name] = opt.default
 
76
    confmodule = __import__("www/conf/conf")
 
77
    try:
 
78
        root_dir = confmodule.root_dir
 
79
    except:
 
80
        root_dir = "/ivle"
 
81
    try:
 
82
        ivle_install_dir = confmodule.ivle_install_dir
 
83
    except:
 
84
        ivle_install_dir = "/opt/ivle"
 
85
    try:
 
86
        jail_base = confmodule.jail_base
 
87
    except:
 
88
        jail_base = "/home/informatics/jails"
374
89
except ImportError:
375
90
    # Just set reasonable defaults
376
 
    for opt in config_options:
377
 
        globals()[opt.option_name] = opt.default
 
91
    root_dir = "/ivle"
 
92
    ivle_install_dir = "/opt/ivle"
 
93
    jail_base = "/home/informatics/jails"
 
94
# Always defaults
 
95
allowed_uids = "0"
378
96
 
379
97
# Try importing install_list, but don't fail if we can't, because listmake can
380
98
# function without it.
389
107
# as necessary, and include it in the distribution.
390
108
listmake_mimetypes = ['text/x-python', 'text/html',
391
109
    'application/x-javascript', 'application/javascript',
392
 
    'text/css', 'image/png', 'image/gif', 'application/xml']
 
110
    'text/css', 'image/png']
393
111
 
394
112
# Main function skeleton from Guido van Rossum
395
113
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
418
136
        return 1
419
137
 
420
138
    # Disallow run as root unless installing
421
 
    if (operation != 'install' and operation != 'updatejails'
422
 
        and os.geteuid() == 0):
 
139
    if operation != 'install' and os.geteuid() == 0:
423
140
        print >>sys.stderr, "I do not want to run this stage as root."
424
141
        print >>sys.stderr, "Please run as a normal user."
425
142
        return 1
427
144
    try:
428
145
        oper_func = {
429
146
            'help' : help,
430
 
            'config' : conf,
 
147
            'conf' : conf,
431
148
            'build' : build,
432
149
            'listmake' : listmake,
433
150
            'install' : install,
434
 
            'updatejails' : updatejails,
435
151
        }[operation]
436
152
    except KeyError:
437
153
        print >>sys.stderr, (
448
164
Operation (and args) can be:
449
165
    help [operation]
450
166
    listmake (developer use only)
451
 
    config [args]
 
167
    conf [args]
452
168
    build
453
 
    install [--nojail] [--nosubjects] [-n|--dry]
 
169
    install [--nojail] [-n|--dry]
454
170
"""
455
171
        return 1
456
172
    elif len(args) != 1:
469
185
be copied upon installation. This should be run by the developer before
470
186
cutting a distribution, and the listfile it generates should be included in
471
187
the distribution, avoiding the administrator having to run it."""
472
 
    elif operation == 'config':
473
 
        print """python setup.py config [args]
 
188
    elif operation == 'conf':
 
189
        print """python setup.py conf [args]
474
190
Configures IVLE with machine-specific details, most notably, various paths.
475
191
Either prompts the administrator for these details or accepts them as
476
192
command-line args. Will be interactive only if there are no arguments given.
480
196
to rebuild/install), just provide ivle_install_dir as the IVLE trunk
481
197
directory, and run build/install one time.
482
198
 
483
 
Creates lib/conf/conf.py and trampoline/conf.h.
 
199
Creates www/conf/conf.py and trampoline/conf.h.
484
200
 
485
 
Args are:"""
486
 
        for opt in config_options:
487
 
            print "    --" + opt.option_name
488
 
        print """As explained in the interactive prompt or conf.py.
 
201
Args are:
 
202
    --root_dir
 
203
    --ivle_install_dir
 
204
    --jail_base
 
205
    --allowed_uids
 
206
As explained in the interactive prompt or conf.py.
489
207
"""
490
208
    elif operation == 'build':
491
209
        print """python -O setup.py build [--dry|-n]
502
220
 
503
221
--dry | -n  Print out the actions but don't do anything."""
504
222
    elif operation == 'install':
505
 
        print """sudo python setup.py install [--nojail] [--nosubjects][--dry|-n]
 
223
        print """sudo python setup.py install [--nojail] [--dry|-n]
506
224
(Requires root)
507
225
Create target install directory ($target).
508
226
Create $target/bin.
510
228
chown and chmod the installed trampoline.
511
229
Copy www/ to $target.
512
230
Copy jail/ to jails template directory (unless --nojail specified).
513
 
Copy subjects/ to subjects directory (unless --nosubjects specified).
514
 
 
515
 
--nojail        Do not copy the jail.
516
 
--nosubjects    Do not copy the subjects and exercises directories.
517
 
--dry | -n  Print out the actions but don't do anything."""
518
 
    elif operation == 'updatejails':
519
 
        print """sudo python setup.py updatejails [--dry|-n]
520
 
(Requires root)
521
 
Copy jail/ to each subdirectory in jails directory.
522
 
 
 
231
 
 
232
--nojail    Do not copy the jail.
523
233
--dry | -n  Print out the actions but don't do anything."""
524
234
    else:
525
235
        print >>sys.stderr, (
530
240
def listmake(args):
531
241
    # We build two separate lists, by walking www and console
532
242
    list_www = build_list_py_files('www')
533
 
    list_lib = build_list_py_files('lib')
534
 
    list_subjects = build_list_py_files('subjects', no_top_level=True)
535
 
    list_exercises = build_list_py_files('exercises', no_top_level=True)
536
 
    list_scripts = [
537
 
        "scripts/python-console",
538
 
        "scripts/fileservice",
539
 
        "scripts/serveservice",
540
 
        "scripts/usrmgt-server",
541
 
        "scripts/diffservice",
542
 
    ]
 
243
    list_console = build_list_py_files('console')
543
244
    # Make sure that the files generated by conf are in the list
544
245
    # (since listmake is typically run before conf)
545
 
    if "lib/conf/conf.py" not in list_lib:
546
 
        list_lib.append("lib/conf/conf.py")
 
246
    if "www/conf/conf.py" not in list_www:
 
247
        list_www.append("www/conf/conf.py")
 
248
    # Make sure that console/python-console is in the list
 
249
    if "console/python-console" not in list_console:
 
250
        list_console.append("console/python-console")
547
251
    # Write these out to a file
548
252
    cwd = os.getcwd()
549
253
    # the files that will be created/overwritten
563
267
list_www = """)
564
268
        writelist_pretty(file, list_www)
565
269
        file.write("""
566
 
# List of all installable files in lib directory.
567
 
list_lib = """)
568
 
        writelist_pretty(file, list_lib)
569
 
        file.write("""
570
 
# List of all installable files in scripts directory.
571
 
list_scripts = """)
572
 
        writelist_pretty(file, list_scripts)
573
 
        file.write("""
574
 
# List of all installable files in subjects directory.
575
 
# This is to install sample subjects and material.
576
 
list_subjects = """)
577
 
        writelist_pretty(file, list_subjects)
578
 
        file.write("""
579
 
# List of all installable files in exercises directory.
580
 
# This is to install sample exercise material.
581
 
list_exercises = """)
582
 
        writelist_pretty(file, list_exercises)
 
270
# List of all installable files in console directory.
 
271
list_console = """)
 
272
        writelist_pretty(file, list_console)
583
273
 
584
274
        file.close()
585
275
    except IOError, (errno, strerror):
596
286
 
597
287
    return 0
598
288
 
599
 
def build_list_py_files(dir, no_top_level=False):
 
289
def build_list_py_files(dir):
600
290
    """Builds a list of all py files found in a directory and its
601
 
    subdirectories. Returns this as a list of strings.
602
 
    no_top_level=True means the file paths will not include the top-level
603
 
    directory.
604
 
    """
 
291
    subdirectories. Returns this as a list of strings."""
605
292
    pylist = []
606
293
    for (dirpath, dirnames, filenames) in os.walk(dir):
607
294
        # Exclude directories beginning with a '.' (such as '.svn')
609
296
        # All *.py files are added to the list
610
297
        pylist += [os.path.join(dirpath, item) for item in filenames
611
298
            if mimetypes.guess_type(item)[0] in listmake_mimetypes]
612
 
    if no_top_level:
613
 
        for i in range(0, len(pylist)):
614
 
            _, pylist[i] = pylist[i].split(os.sep, 1)
615
299
    return pylist
616
300
 
617
301
def writelist_pretty(file, list):
625
309
        file.write(']\n')
626
310
 
627
311
def conf(args):
628
 
    global db_port, usrmgt_port
 
312
    global root_dir, ivle_install_dir, jail_base, allowed_uids
629
313
    # Set up some variables
630
314
 
631
315
    cwd = os.getcwd()
632
316
    # the files that will be created/overwritten
633
 
    conffile = os.path.join(cwd, "lib/conf/conf.py")
634
 
    jailconffile = os.path.join(cwd, "lib/conf/jailconf.py")
 
317
    conffile = os.path.join(cwd, "www/conf/conf.py")
635
318
    conf_hfile = os.path.join(cwd, "trampoline/conf.h")
636
 
    phpBBconffile = os.path.join(cwd, "www/php/phpBB3/config.php")
637
319
 
638
320
    # Get command-line arguments to avoid asking questions.
639
321
 
640
 
    optnames = []
641
 
    for opt in config_options:
642
 
        optnames.append(opt.option_name + "=")
643
 
    (opts, args) = getopt.gnu_getopt(args, "", optnames)
 
322
    (opts, args) = getopt.gnu_getopt(args, "", ['root_dir=',
 
323
                    'ivle_install_dir=', 'jail_base=', 'allowed_uids='])
644
324
 
645
325
    if args != []:
646
326
        print >>sys.stderr, "Invalid arguments:", string.join(args, ' ')
652
332
        print """This tool will create the following files:
653
333
    %s
654
334
    %s
655
 
    %s
656
 
    %s
657
335
prompting you for details about your configuration. The file will be
658
336
overwritten if it already exists. It will *not* install or deploy IVLE.
659
337
 
660
338
Please hit Ctrl+C now if you do not wish to do this.
661
 
""" % (conffile, jailconffile, conf_hfile, phpBBconffile)
 
339
""" % (conffile, conf_hfile)
662
340
 
663
341
        # Get information from the administrator
664
342
        # If EOF is encountered at any time during the questioning, just exit
665
343
        # silently
666
344
 
667
 
        for opt in config_options:
668
 
            globals()[opt.option_name] = \
669
 
                query_user(globals()[opt.option_name], opt.prompt)
 
345
        root_dir = query_user(root_dir,
 
346
        """Root directory where IVLE is located (in URL space):""")
 
347
        ivle_install_dir = query_user(ivle_install_dir,
 
348
        'Root directory where IVLE will be installed (on the local file '
 
349
        'system):')
 
350
        jail_base = query_user(jail_base,
 
351
        """Root directory where the jails (containing user files) are stored
 
352
(on the local file system):""")
 
353
        allowed_uids = query_user(allowed_uids,
 
354
        """UID of the web server process which will run IVLE.
 
355
Only this user may execute the trampoline. May specify multiple users as
 
356
a comma-separated list.
 
357
    (eg. "1002,78")""")
 
358
 
670
359
    else:
671
360
        opts = dict(opts)
672
361
        # Non-interactive mode. Parse the options.
673
 
        for opt in config_options:
674
 
            if '--' + opt.option_name in opts:
675
 
                globals()[opt.option_name] = opts['--' + opt.option_name]
 
362
        if '--root_dir' in opts:
 
363
            root_dir = opts['--root_dir']
 
364
        if '--ivle_install_dir' in opts:
 
365
            ivle_install_dir = opts['--ivle_install_dir']
 
366
        if '--jail_base' in opts:
 
367
            jail_base = opts['--jail_base']
 
368
        if '--allowed_uids' in opts:
 
369
            allowed_uids = opts['--allowed_uids']
676
370
 
677
371
    # Error handling on input values
678
372
    try:
679
 
        allowed_uids_list = map(int, allowed_uids.split(','))
 
373
        allowed_uids = map(int, allowed_uids.split(','))
680
374
    except ValueError:
681
375
        print >>sys.stderr, (
682
376
        "Invalid UID list (%s).\n"
683
377
        "Must be a comma-separated list of integers." % allowed_uids)
684
378
        return 1
685
 
    try:
686
 
        db_port = int(db_port)
687
 
        if db_port < 0 or db_port >= 65536: raise ValueError()
688
 
    except ValueError:
689
 
        print >>sys.stderr, (
690
 
        "Invalid DB port (%s).\n"
691
 
        "Must be an integer between 0 and 65535." % repr(db_port))
692
 
        return 1
693
 
    try:
694
 
        usrmgt_port = int(usrmgt_port)
695
 
        if usrmgt_port < 0 or usrmgt_port >= 65536: raise ValueError()
696
 
    except ValueError:
697
 
        print >>sys.stderr, (
698
 
        "Invalid user management port (%s).\n"
699
 
        "Must be an integer between 0 and 65535." % repr(usrmgt_port))
700
 
        return 1
701
 
 
702
 
    # Generate the forum secret
703
 
    forum_secret = hashlib.md5(uuid.uuid4().bytes).hexdigest()
704
 
 
705
 
    # Write lib/conf/conf.py
 
379
 
 
380
    # Write www/conf/conf.py
706
381
 
707
382
    try:
708
383
        conf = open(conffile, "w")
711
386
# conf.py
712
387
# Miscellaneous application settings
713
388
 
714
 
""")
715
 
        for opt in config_options:
716
 
            conf.write('%s\n%s = %s\n' % (opt.comment, opt.option_name,
717
 
                repr(globals()[opt.option_name])))
718
 
 
719
 
        # Add the forum secret to the config file (regenerated each config)
720
 
        conf.write('forum_secret = "%s"\n' % (forum_secret))
721
 
 
722
 
        conf.close()
723
 
    except IOError, (errno, strerror):
724
 
        print "IO error(%s): %s" % (errno, strerror)
725
 
        sys.exit(1)
726
 
 
727
 
    print "Successfully wrote lib/conf/conf.py"
728
 
 
729
 
    # Write conf/jailconf.py
730
 
 
731
 
    try:
732
 
        conf = open(jailconffile, "w")
733
 
 
734
 
        # In the "in-jail" version of conf, we don't need MOST of the details
735
 
        # (it would be a security risk to have them here).
736
 
        # So we just write root_dir, and jail_base is "/".
737
 
        # (jail_base being "/" means "jail-relative" paths are relative to "/"
738
 
        # when inside the jail.)
739
 
        conf.write("""# IVLE Configuration File
740
 
# conf.py
741
 
# Miscellaneous application settings
742
 
# (User jail version)
743
 
 
744
389
 
745
390
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
746
391
# with this).
747
392
# eg. "/" or "/ivle".
748
 
root_dir = %s
 
393
root_dir = "%s"
 
394
 
 
395
# In the local file system, where IVLE is actually installed.
 
396
# This directory should contain the "www" and "bin" directories.
 
397
ivle_install_dir = "%s"
749
398
 
750
399
# In the local file system, where are the student/user file spaces located.
751
400
# The user jails are expected to be located immediately in subdirectories of
752
401
# this location.
753
 
jail_base = '/'
754
 
 
755
 
# The hostname for serving publicly accessible pages
756
 
public_host = %s
757
 
""" % (repr(root_dir),repr(public_host)))
 
402
jail_base = "%s"
 
403
""" % (root_dir, ivle_install_dir, jail_base))
758
404
 
759
405
        conf.close()
760
406
    except IOError, (errno, strerror):
761
407
        print "IO error(%s): %s" % (errno, strerror)
762
408
        sys.exit(1)
763
409
 
764
 
    print "Successfully wrote lib/conf/jailconf.py"
 
410
    print "Successfully wrote www/conf/conf.py"
765
411
 
766
412
    # Write trampoline/conf.h
767
413
 
786
432
 * (Note that root is an implicit member of this list).
787
433
 */
788
434
static const int allowed_uids[] = { %s };
789
 
""" % (repr(jail_base)[1:-1], repr(allowed_uids_list)[1:-1]))
790
 
    # Note: The above uses PYTHON reprs, not C reprs
791
 
    # However they should be the same with the exception of the outer
792
 
    # characters, which are stripped off and replaced
 
435
""" % (jail_base, repr(allowed_uids)[1:-1]))
793
436
 
794
437
        conf.close()
795
438
    except IOError, (errno, strerror):
798
441
 
799
442
    print "Successfully wrote trampoline/conf.h"
800
443
 
801
 
    # Write www/php/phpBB3/config.php
802
 
 
803
 
    try:
804
 
        conf = open(phpBBconffile, "w")
805
 
        
806
 
        # php-pg work around
807
 
        if db_host == 'localhost':
808
 
            forumdb_host = '127.0.0.1'
809
 
        else:
810
 
            forumdb_host = db_host
811
 
 
812
 
        conf.write( """<?php
813
 
// phpBB 3.0.x auto-generated configuration file
814
 
// Do not change anything in this file!
815
 
$dbms = 'postgres';
816
 
$dbhost = '""" + forumdb_host + """';
817
 
$dbport = '""" + str(db_port) + """';
818
 
$dbname = '""" + db_forumdbname + """';
819
 
$dbuser = '""" + db_user + """';
820
 
$dbpasswd = '""" + db_password + """';
821
 
 
822
 
$table_prefix = 'phpbb_';
823
 
$acm_type = 'file';
824
 
$load_extensions = '';
825
 
@define('PHPBB_INSTALLED', true);
826
 
// @define('DEBUG', true);
827
 
//@define('DEBUG_EXTRA', true);
828
 
 
829
 
$forum_secret = '""" + forum_secret +"""';
830
 
?>"""   )
831
 
    
832
 
        conf.close()
833
 
    except IOError, (errno, strerror):
834
 
        print "IO error(%s): %s" % (errno, strerror)
835
 
        sys.exit(1)
836
 
 
837
 
    print "Successfully wrote www/php/phpBB3/config.php"
838
 
 
839
444
    print
840
445
    print "You may modify the configuration at any time by editing"
841
446
    print conffile
842
 
    print jailconffile
843
447
    print conf_hfile
844
 
    print phpBBconffile
845
448
    print
846
449
    return 0
847
450
 
855
458
        print "Dry run (no actions will be executed\n"
856
459
 
857
460
    # Compile the trampoline
858
 
    curdir = os.getcwd()
859
 
    os.chdir('trampoline')
860
 
    action_runprog('make', [], dry)
861
 
    os.chdir(curdir)
 
461
    action_runprog('gcc', ['-Wall', '-o', 'trampoline/trampoline',
 
462
        'trampoline/trampoline.c'], dry)
862
463
 
863
464
    # Create the jail and its subdirectories
864
465
    # Note: Other subdirs will be made by copying files
866
467
    action_mkdir('jail/home', dry)
867
468
    action_mkdir('jail/tmp', dry)
868
469
 
869
 
    # Chmod the tmp directory to world writable
870
 
    action_chmod_w('jail/tmp', dry)
871
 
 
872
470
    # Copy all console and operating system files into the jail
873
 
    action_copylist(install_list.list_scripts, 'jail/opt/ivle', dry)
 
471
    action_copylist(install_list.list_console, 'jail/opt/ivle', dry)
874
472
    copy_os_files_jail(dry)
875
 
    # Chmod the python console
876
 
    action_chmod_x('jail/opt/ivle/scripts/python-console', dry)
877
 
    action_chmod_x('jail/opt/ivle/scripts/fileservice', dry)
878
 
    action_chmod_x('jail/opt/ivle/scripts/serveservice', dry)
879
 
    
880
 
    # Also copy the IVLE lib directory into the jail
881
 
    # This is necessary for running certain scripts
882
 
    action_copylist(install_list.list_lib, 'jail/opt/ivle', dry)
883
 
    # IMPORTANT: The file jail/opt/ivle/lib/conf/conf.py contains details
884
 
    # which could compromise security if left in the jail (such as the DB
885
 
    # password).
886
 
    # The "safe" version is in jailconf.py. Delete conf.py and replace it with
887
 
    # jailconf.py.
888
 
    action_copyfile('lib/conf/jailconf.py',
889
 
        'jail/opt/ivle/lib/conf/conf.py', dry)
890
473
 
891
474
    # Compile .py files into .pyc or .pyo files
892
475
    compileall.compile_dir('www', quiet=True)
893
 
    compileall.compile_dir('lib', quiet=True)
894
 
    compileall.compile_dir('scripts', quiet=True)
895
 
    compileall.compile_dir('jail/opt/ivle/lib', quiet=True)
896
 
 
897
 
    # Set up ivle.pth inside the jail
898
 
    # Need to set /opt/ivle/lib to be on the import path
899
 
    ivle_pth = \
900
 
        "jail/usr/lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION
901
 
    f = open(ivle_pth, 'w')
902
 
    f.write('/opt/ivle/lib\n')
903
 
    f.close()
 
476
    compileall.compile_dir('console', quiet=True)
904
477
 
905
478
    return 0
906
479
 
908
481
    """Copies necessary Operating System files from their usual locations
909
482
    into the jail/ directory of the cwd."""
910
483
    # Currently source paths are configured for Ubuntu.
911
 
    for filename in JAIL_FILES:
912
 
        copy_file_to_jail(filename, dry)
913
 
    for src, dst in JAIL_LINKS.items():
914
 
        action_symlink(src, dst, dry)
915
 
    for src, dst in JAIL_COPYTREES.items():
916
 
        action_copytree(src, dst, dry)
 
484
    copy_file_to_jail('/lib/ld-linux.so.2', dry)
 
485
    copy_file_to_jail('/lib/tls/i686/cmov/libc.so.6', dry)
 
486
    copy_file_to_jail('/lib/tls/i686/cmov/libdl.so.2', dry)
 
487
    copy_file_to_jail('/lib/tls/i686/cmov/libm.so.6', dry)
 
488
    copy_file_to_jail('/lib/tls/i686/cmov/libpthread.so.0', dry)
 
489
    copy_file_to_jail('/lib/tls/i686/cmov/libutil.so.1', dry)
 
490
    copy_file_to_jail('/usr/bin/python2.5', dry)
 
491
    action_symlink('python2.5', 'jail/usr/bin/python', dry)
 
492
    action_copytree('/usr/lib/python2.5', 'jail/usr/lib/python2.5', dry)
917
493
 
918
494
def copy_file_to_jail(src, dry):
919
495
    """Copies a single file from an absolute location into the same location
923
499
 
924
500
def install(args):
925
501
    # Get "dry" and "nojail" variables from command line
926
 
    (opts, args) = getopt.gnu_getopt(args, "n",
927
 
        ['dry', 'nojail', 'nosubjects'])
 
502
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry', 'nojail'])
928
503
    opts = dict(opts)
929
504
    dry = '-n' in opts or '--dry' in opts
930
505
    nojail = '--nojail' in opts
931
 
    nosubjects = '--nosubjects' in opts
932
506
 
933
507
    if dry:
934
508
        print "Dry run (no actions will be executed\n"
948
522
    # chown trampoline to root and set setuid bit
949
523
    action_chown_setuid(tramppath, dry)
950
524
 
951
 
    # Create a scripts directory to put the usrmgt-server in.
952
 
    action_mkdir(os.path.join(ivle_install_dir, 'scripts'), dry)
953
 
    usrmgtpath = os.path.join(ivle_install_dir, 'scripts/usrmgt-server')
954
 
    action_copyfile('scripts/usrmgt-server', usrmgtpath, dry)
955
 
    action_chmod_x(usrmgtpath, dry)
956
 
 
957
 
    # Copy the www and lib directories using the list
 
525
    # Copy the www directory using the list
958
526
    action_copylist(install_list.list_www, ivle_install_dir, dry)
959
 
    action_copylist(install_list.list_lib, ivle_install_dir, dry)
960
 
    
961
 
    # Copy the php directory
962
 
    action_copytree('www/php/phpBB3',os.path.join(ivle_install_dir,'www/php/phpBB3'), 
963
 
    dry)
964
527
 
965
528
    if not nojail:
966
529
        # Copy the local jail directory built by the build action
967
530
        # to the jails template directory (it will be used as a template
968
531
        # for all the students' jails).
969
532
        action_copytree('jail', os.path.join(jail_base, 'template'), dry)
970
 
    if not nosubjects:
971
 
        # Copy the subjects and exercises directories across
972
 
        action_copylist(install_list.list_subjects, subjects_base, dry,
973
 
            srcdir="./subjects")
974
 
        action_copylist(install_list.list_exercises, exercises_base, dry,
975
 
            srcdir="./exercises")
976
 
 
977
 
    # Append IVLE path to ivle.pth in python site packages
978
 
    # (Unless it's already there)
979
 
    ivle_pth = os.path.join(sys.prefix,
980
 
        "lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION)
981
 
    ivle_www = os.path.join(ivle_install_dir, "www")
982
 
    ivle_lib = os.path.join(ivle_install_dir, "lib")
983
 
    write_ivle_pth = True
984
 
    write_ivle_lib_pth = True
985
 
    try:
986
 
        file = open(ivle_pth, 'r')
987
 
        for line in file:
988
 
            if line.strip() == ivle_www:
989
 
                write_ivle_pth = False
990
 
            elif line.strip() == ivle_lib:
991
 
                write_ivle_lib_pth = False
992
 
        file.close()
993
 
    except (IOError, OSError):
994
 
        pass
995
 
    if write_ivle_pth:
996
 
        action_append(ivle_pth, ivle_www)
997
 
    if write_ivle_lib_pth:
998
 
        action_append(ivle_pth, ivle_lib)
999
 
 
1000
 
    return 0
1001
 
 
1002
 
def updatejails(args):
1003
 
    # Get "dry" variable from command line
1004
 
    (opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
1005
 
    opts = dict(opts)
1006
 
    dry = '-n' in opts or '--dry' in opts
1007
 
 
1008
 
    if dry:
1009
 
        print "Dry run (no actions will be executed\n"
1010
 
 
1011
 
    if not dry and os.geteuid() != 0:
1012
 
        print >>sys.stderr, "Must be root to run install"
1013
 
        print >>sys.stderr, "(I need to chown some files)."
1014
 
        return 1
1015
 
 
1016
 
    # Update the template jail directory in case it hasn't been installed
1017
 
    # recently.
1018
 
    action_copytree('jail', os.path.join(jail_base, 'template'), dry)
1019
 
 
1020
 
    # Re-link all the files in all students jails.
1021
 
    for dir in os.listdir(jail_base):
1022
 
        if dir == 'template': continue
1023
 
        # First back up the student's home directory
1024
 
        temp_home = os.tmpnam()
1025
 
        action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
1026
 
        # Delete the student's jail and relink the jail files
1027
 
        action_linktree(os.path.join(jail_base, 'template'),
1028
 
            os.path.join(jail_base, dir), dry)
1029
 
        # Restore the student's home directory
1030
 
        action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
1031
 
        # Set up the user's home directory just in case they don't have a
1032
 
        # directory for this yet
1033
 
        action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
1034
533
 
1035
534
    return 0
1036
535
 
1063
562
    if ret != 0:
1064
563
        raise RunError(prog, ret)
1065
564
 
1066
 
def action_remove(path, dry):
1067
 
    """Calls rmtree, deleting the target file if it exists."""
1068
 
    try:
1069
 
        print "rm -r", path
1070
 
        if not dry:
1071
 
            shutil.rmtree(path, True)
1072
 
    except OSError, (err, msg):
1073
 
        if err != errno.EEXIST:
1074
 
            raise
1075
 
        # Otherwise, didn't exist, so we don't care
1076
 
 
1077
 
def action_rename(src, dst, dry):
1078
 
    """Calls rename. Deletes the target if it already exists."""
1079
 
    action_remove(dst, dry)
1080
 
    print "mv ", src, dst
1081
 
    if dry: return
1082
 
    try:
1083
 
        os.rename(src, dst)
1084
 
    except OSError, (err, msg):
1085
 
        if err != errno.EEXIST:
1086
 
            raise
1087
 
 
1088
565
def action_mkdir(path, dry):
1089
566
    """Calls mkdir. Silently ignored if the directory already exists.
1090
567
    Creates all parent directories as necessary."""
1102
579
    directories as necessary.
1103
580
 
1104
581
    See shutil.copytree."""
1105
 
    # Allow copying over itself
1106
 
    if (os.path.normpath(os.path.join(os.getcwd(),src)) ==
1107
 
        os.path.normpath(os.path.join(os.getcwd(),dst))):
1108
 
        return
1109
 
    action_remove(dst, dry)
 
582
    if os.access(dst, os.F_OK):
 
583
        print "rm -r", dst
 
584
        if not dry:
 
585
            shutil.rmtree(dst, True)
1110
586
    print "cp -r", src, dst
1111
587
    if dry: return
1112
588
    shutil.copytree(src, dst, True)
1113
589
 
1114
 
def action_linktree(src, dst, dry):
1115
 
    """Hard-links an entire directory tree. Same as copytree but the created
1116
 
    files are hard-links not actual copies. Removes the existing destination.
1117
 
    """
1118
 
    action_remove(dst, dry)
1119
 
    print "<cp with hardlinks> -r", src, dst
1120
 
    if dry: return
1121
 
    common.makeuser.linktree(src, dst)
1122
 
 
1123
 
def action_copylist(srclist, dst, dry, srcdir="."):
 
590
def action_copylist(srclist, dst, dry):
1124
591
    """Copies all files in a list to a new location. The files in the list
1125
592
    are read relative to the current directory, and their destinations are the
1126
593
    same paths relative to dst. Creates all parent directories as necessary.
1127
 
    srcdir is "." by default, can be overridden.
1128
594
    """
1129
595
    for srcfile in srclist:
1130
596
        dstfile = os.path.join(dst, srcfile)
1131
 
        srcfile = os.path.join(srcdir, srcfile)
1132
597
        dstdir = os.path.split(dstfile)[0]
1133
598
        if not os.path.isdir(dstdir):
1134
599
            action_mkdir(dstdir, dry)
1143
608
def action_copyfile(src, dst, dry):
1144
609
    """Copies one file to a new location. Creates all parent directories
1145
610
    as necessary.
1146
 
    Warn if file not found.
1147
611
    """
1148
612
    dstdir = os.path.split(dst)[0]
1149
613
    if not os.path.isdir(dstdir):
1153
617
        try:
1154
618
            shutil.copyfile(src, dst)
1155
619
            shutil.copymode(src, dst)
1156
 
        except (shutil.Error, IOError), e:
1157
 
            print "Warning: " + str(e)
 
620
        except shutil.Error:
 
621
            pass
1158
622
 
1159
623
def action_symlink(src, dst, dry):
1160
624
    """Creates a symlink in a given location. Creates all parent directories
1170
634
    if not dry:
1171
635
        os.symlink(src, dst)
1172
636
 
1173
 
def action_append(ivle_pth, ivle_www):
1174
 
    file = open(ivle_pth, 'a+')
1175
 
    file.write(ivle_www + '\n')
1176
 
    file.close()
1177
 
 
1178
637
def action_chown_setuid(file, dry):
1179
638
    """Chowns a file to root, and sets the setuid bit on the file.
1180
639
    Calling this function requires the euid to be root.
1189
648
        os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
1190
649
            | stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
1191
650
 
1192
 
def action_chmod_x(file, dry):
1193
 
    """Chmod 755 a file (sets permissions to rwxr-xr-x)."""
1194
 
    print "chmod 755", file
1195
 
    if not dry:
1196
 
        os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
1197
 
            | stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH | stat.S_IROTH)
1198
 
 
1199
 
 
1200
 
def action_chmod_w(file, dry):
1201
 
    """Chmod 777 a file (sets permissions to rwxrwxrwx)."""
1202
 
    print "chmod 777", file
1203
 
    if not dry:
1204
 
        os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
1205
 
            | stat.S_IXGRP | stat.S_IWGRP | stat.S_IRGRP | stat.S_IXOTH
1206
 
            | stat.S_IWOTH | stat.S_IROTH)
1207
 
 
1208
651
def query_user(default, prompt):
1209
652
    """Prompts the user for a string, which is read from a line of stdin.
1210
653
    Exits silently if EOF is encountered. Returns the string, with spaces