57
57
# Copy www/ to $target.
58
58
# Copy jail/ to jails template directory (unless --nojail specified).
60
# TODO: List in help, and handle, args for the conf operation
71
# Import modules from the website is tricky since they're in the www
73
sys.path.append(os.path.join(os.getcwd(), 'www'))
75
import common.makeuser
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]
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.
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',
94
# These 2 files do not exist in Ubuntu
95
#'/etc/ld.so.preload',
96
#'/etc/ld.so.nohwcap',
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',
124
# Symlinks to make within the jail. Src mapped to dst.
126
'python%s' % PYTHON_VERSION: 'jail/usr/bin/python',
128
# Trees to copy. Src mapped to dst (these will be passed to action_copytree).
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',
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
145
comment: (Long) comment string stored in conf.py. Each line of this
146
string should begin with a '#'.
148
self.option_name = option_name
149
self.default = default
151
self.comment = comment
153
# Configuration options, defaults and descriptions
155
config_options.append(ConfigOption("root_dir", "/ivle",
156
"""Root directory where IVLE is located (in URL space):""",
158
# In URL space, where in the site is IVLE located. (All URLs will be prefixed
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 '
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):""",
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):""",
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("public_host", "public.localhost",
183
"""Hostname which will cause the server to go into "public mode",
184
providing login-free access to student's published work:""",
186
# The server goes into "public mode" if the browser sends a request with this
187
# host. This is for security reasons - we only serve public student files on a
188
# separate domain to the main IVLE site.
189
# Public mode does not use cookies, and serves only public content.
190
# Private mode (normal mode) requires login, and only serves files relevant to
191
# the logged-in user."""))
192
config_options.append(ConfigOption("allowed_uids", "33",
193
"""UID of the web server process which will run IVLE.
194
Only this user may execute the trampoline. May specify multiple users as
195
a comma-separated list.
198
# The User-ID of the web server process which will run IVLE, and any other
199
# users who are allowed to run the trampoline. This is stores as a string of
200
# comma-separated integers, simply because it is not used within Python, only
201
# used by the setup program to write to conf.h (see setup.py config)."""))
202
config_options.append(ConfigOption("db_host", "localhost",
203
"""PostgreSQL Database config
204
==========================
205
Hostname of the DB server:""",
207
### PostgreSQL Database config ###
208
# Database server hostname"""))
209
config_options.append(ConfigOption("db_port", "5432",
210
"""Port of the DB server:""",
212
# Database server port"""))
213
config_options.append(ConfigOption("db_dbname", "ivle",
214
"""Database name:""",
217
config_options.append(ConfigOption("db_user", "postgres",
218
"""Username for DB server login:""",
220
# Database username"""))
221
config_options.append(ConfigOption("db_password", "",
222
"""Password for DB server login:
223
(Caution: This password is stored in plaintext in www/conf/conf.py)""",
225
# Database password"""))
68
227
# Try importing existing conf, but if we can't just set up defaults
69
228
# The reason for this is that these settings are used by other phases
71
230
# Also this allows you to hit Return to accept the existing value.
73
232
confmodule = __import__("www/conf/conf")
74
root_dir = confmodule.root_dir
75
ivle_install_dir = confmodule.ivle_install_dir
76
jail_base = confmodule.jail_base
233
for opt in config_options:
235
globals()[opt.option_name] = confmodule.__dict__[opt.option_name]
237
globals()[opt.option_name] = opt.default
77
238
except ImportError:
78
239
# Just set reasonable defaults
80
ivle_install_dir = "/opt/ivle"
81
jail_base = "/home/informatics/jails"
240
for opt in config_options:
241
globals()[opt.option_name] = opt.default
243
# Try importing install_list, but don't fail if we can't, because listmake can
244
# function without it.
250
# Mime types which will automatically be placed in the list by listmake.
251
# Note that listmake is not intended to be run by the final user (the system
252
# administrator who installs this), so the developers can customize the list
253
# as necessary, and include it in the distribution.
254
listmake_mimetypes = ['text/x-python', 'text/html',
255
'application/x-javascript', 'application/javascript',
256
'text/css', 'image/png', 'application/xml']
85
258
# Main function skeleton from Guido van Rossum
86
259
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
88
class Usage(Exception):
89
def __init__(self, msg):
92
261
def main(argv=None):
158
326
if operation == 'help':
159
327
print """python setup.py help [operation]
160
328
Prints the usage message or detailed help on an operation, then exits."""
161
elif operation == 'conf':
162
print """python setup.py conf [args]
329
elif operation == 'listmake':
330
print """python setup.py listmake
331
(For developer use only)
332
Recurses through the source tree and builds a list of all files which should
333
be copied upon installation. This should be run by the developer before
334
cutting a distribution, and the listfile it generates should be included in
335
the distribution, avoiding the administrator having to run it."""
336
elif operation == 'config':
337
print """python setup.py config [args]
163
338
Configures IVLE with machine-specific details, most notably, various paths.
164
339
Either prompts the administrator for these details or accepts them as
340
command-line args. Will be interactive only if there are no arguments given.
341
Takes defaults from existing conf file if it exists.
343
To run IVLE out of the source directory (allowing development without having
344
to rebuild/install), just provide ivle_install_dir as the IVLE trunk
345
directory, and run build/install one time.
166
347
Creates www/conf/conf.py and trampoline/conf.h.
350
for opt in config_options:
351
print " --" + opt.option_name
352
print """As explained in the interactive prompt or conf.py.
169
354
elif operation == 'build':
170
print """python setup.py build
355
print """python -O setup.py build [--dry|-n]
171
356
Compiles all files and sets up a jail template in the source directory.
357
-O is recommended to cause compilation to be optimised.
173
359
Compiles (GCC) trampoline/trampoline.c to trampoline/trampoline.
289
506
Please hit Ctrl+C now if you do not wish to do this.
290
507
""" % (conffile, conf_hfile)
292
# Get information from the administrator
293
# If EOF is encountered at any time during the questioning, just exit
509
# Get information from the administrator
510
# If EOF is encountered at any time during the questioning, just exit
296
root_dir = query_user(root_dir,
297
"""Root directory where IVLE is located (in URL space):""")
298
ivle_install_dir = query_user(ivle_install_dir,
299
'Root directory where IVLE will be installed (on the local file '
301
jail_base = query_user(jail_base,
302
"""Root directory where the jails (containing user files) are stored
303
(on the local file system):""")
304
allowed_uids = query_user(allowed_uids,
305
"""UID of the web server process which will run IVLE.
306
Only this user may execute the trampoline. May specify multiple users as
307
a comma-separated list.
513
for opt in config_options:
514
globals()[opt.option_name] = \
515
query_user(globals()[opt.option_name], opt.prompt)
518
# Non-interactive mode. Parse the options.
519
for opt in config_options:
520
if '--' + opt.option_name in opts:
521
globals()[opt.option_name] = opts['--' + opt.option_name]
310
523
# Error handling on input values
313
allowed_uids = map(int, allowed_uids.split(','))
525
allowed_uids_list = map(int, allowed_uids.split(','))
314
526
except ValueError:
315
527
print >>sys.stderr, (
316
528
"Invalid UID list (%s).\n"
317
529
"Must be a comma-separated list of integers." % allowed_uids)
532
db_port = int(db_port)
533
if db_port < 0 or db_port >= 65536: raise ValueError()
535
print >>sys.stderr, (
536
"Invalid DB port (%s).\n"
537
"Must be an integer between 0 and 65535." % repr(db_port))
320
540
# Write www/conf/conf.py
398
dry = False # Set to True later if --dry
601
# Get "dry" variable from command line
602
(opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
604
dry = '-n' in opts or '--dry' in opts
607
print "Dry run (no actions will be executed\n"
400
609
# Compile the trampoline
401
action_runprog('gcc', ['-Wall', '-o', 'trampoline/trampoline',
402
'trampoline/trampoline.c'], dry)
611
os.chdir('trampoline')
612
action_runprog('make', [], dry)
404
615
# Create the jail and its subdirectories
406
action_mkdir('jail/bin')
407
action_mkdir('jail/lib')
408
action_mkdir('jail/usr/bin')
409
action_mkdir('jail/usr/lib')
410
action_mkdir('jail/opt/ivle')
411
action_mkdir('jail/home')
412
action_mkdir('jail/tmp')
414
# TODO: Copy console into the jail
415
# TODO: Copy operating system files into the jail
416
# TODO: Compile .py files into .pyc files
616
# Note: Other subdirs will be made by copying files
617
action_mkdir('jail', dry)
618
action_mkdir('jail/home', dry)
619
action_mkdir('jail/tmp', dry)
621
# Copy all console and operating system files into the jail
622
action_copylist(install_list.list_console, 'jail/opt/ivle', dry)
623
copy_os_files_jail(dry)
624
# Chmod the python console
625
action_chmod_x('jail/opt/ivle/console/python-console', dry)
628
# Compile .py files into .pyc or .pyo files
629
compileall.compile_dir('www', quiet=True)
630
compileall.compile_dir('console', quiet=True)
634
def copy_os_files_jail(dry):
635
"""Copies necessary Operating System files from their usual locations
636
into the jail/ directory of the cwd."""
637
# Currently source paths are configured for Ubuntu.
638
for filename in JAIL_FILES:
639
copy_file_to_jail(filename, dry)
640
for src, dst in JAIL_LINKS.items():
641
action_symlink(src, dst, dry)
642
for src, dst in JAIL_COPYTREES.items():
643
action_copytree(src, dst, dry)
645
def copy_file_to_jail(src, dry):
646
"""Copies a single file from an absolute location into the same location
647
within the jail. src must begin with a '/'. The jail will be located
648
in a 'jail' subdirectory of the current path."""
649
action_copyfile(src, 'jail' + src, dry)
420
651
def install(args):
652
# Get "dry" and "nojail" variables from command line
653
(opts, args) = getopt.gnu_getopt(args, "n",
654
['dry', 'nojail', 'nosubjects'])
656
dry = '-n' in opts or '--dry' in opts
657
nojail = '--nojail' in opts
658
nosubjects = '--nosubjects' in opts
661
print "Dry run (no actions will be executed\n"
663
if not dry and os.geteuid() != 0:
664
print >>sys.stderr, "Must be root to run install"
665
print >>sys.stderr, "(I need to chown some files)."
668
# Create the target (install) directory
669
action_mkdir(ivle_install_dir, dry)
671
# Create bin and copy the compiled files there
672
action_mkdir(os.path.join(ivle_install_dir, 'bin'), dry)
673
tramppath = os.path.join(ivle_install_dir, 'bin/trampoline')
674
action_copyfile('trampoline/trampoline', tramppath, dry)
675
# chown trampoline to root and set setuid bit
676
action_chown_setuid(tramppath, dry)
678
# Copy the www directory using the list
679
action_copylist(install_list.list_www, ivle_install_dir, dry)
682
# Copy the local jail directory built by the build action
683
# to the jails template directory (it will be used as a template
684
# for all the students' jails).
685
action_copytree('jail', os.path.join(jail_base, 'template'), dry)
687
# Copy the subjects directory across
688
action_copylist(install_list.list_subjects, subjects_base, dry,
691
# Append IVLE path to ivle.pth in python site packages
692
# (Unless it's already there)
693
ivle_pth = os.path.join(sys.prefix,
694
"lib/python%s/site-packages/ivle.pth" % PYTHON_VERSION)
695
ivle_www = os.path.join(ivle_install_dir, "www")
696
write_ivle_pth = True
698
file = open(ivle_pth, 'r')
700
if line.strip() == ivle_www:
701
write_ivle_pth = False
703
except (IOError, OSError):
706
action_append(ivle_pth, ivle_www)
710
def updatejails(args):
711
# Get "dry" variable from command line
712
(opts, args) = getopt.gnu_getopt(args, "n", ['dry'])
714
dry = '-n' in opts or '--dry' in opts
717
print "Dry run (no actions will be executed\n"
719
if not dry and os.geteuid() != 0:
720
print >>sys.stderr, "Must be root to run install"
721
print >>sys.stderr, "(I need to chown some files)."
724
# Update the template jail directory in case it hasn't been installed
726
action_copytree('jail', os.path.join(jail_base, 'template'), dry)
728
# Re-link all the files in all students jails.
729
for dir in os.listdir(jail_base):
730
if dir == 'template': continue
731
# First back up the student's home directory
732
temp_home = os.tmpnam()
733
action_rename(os.path.join(jail_base, dir, 'home'), temp_home, dry)
734
# Delete the student's jail and relink the jail files
735
action_linktree(os.path.join(jail_base, 'template'),
736
os.path.join(jail_base, dir), dry)
737
# Restore the student's home directory
738
action_rename(temp_home, os.path.join(jail_base, dir, 'home'), dry)
739
# Set up the user's home directory just in case they don't have a
740
# directory for this yet
741
action_mkdir(os.path.join(jail_base, dir, 'home', dir), dry)
424
745
# The actions call Python os functions but print actions and handle dryness.
461
796
if err != errno.EEXIST:
799
def action_copytree(src, dst, dry):
800
"""Copies an entire directory tree. Symlinks are seen as normal files and
801
copies of the entire file (not the link) are made. Creates all parent
802
directories as necessary.
804
See shutil.copytree."""
805
if os.access(dst, os.F_OK):
808
shutil.rmtree(dst, True)
809
print "cp -r", src, dst
811
shutil.copytree(src, dst, True)
813
def action_linktree(src, dst, dry):
814
"""Hard-links an entire directory tree. Same as copytree but the created
815
files are hard-links not actual copies. Removes the existing destination.
817
if os.access(dst, os.F_OK):
820
shutil.rmtree(dst, True)
821
print "<cp with hardlinks> -r", src, dst
823
common.makeuser.linktree(src, dst)
825
def action_copylist(srclist, dst, dry, srcdir="."):
826
"""Copies all files in a list to a new location. The files in the list
827
are read relative to the current directory, and their destinations are the
828
same paths relative to dst. Creates all parent directories as necessary.
829
srcdir is "." by default, can be overridden.
831
for srcfile in srclist:
832
dstfile = os.path.join(dst, srcfile)
833
srcfile = os.path.join(srcdir, srcfile)
834
dstdir = os.path.split(dstfile)[0]
835
if not os.path.isdir(dstdir):
836
action_mkdir(dstdir, dry)
837
print "cp -f", srcfile, dstfile
840
shutil.copyfile(srcfile, dstfile)
841
shutil.copymode(srcfile, dstfile)
845
def action_copyfile(src, dst, dry):
846
"""Copies one file to a new location. Creates all parent directories
848
Warn if file not found.
850
dstdir = os.path.split(dst)[0]
851
if not os.path.isdir(dstdir):
852
action_mkdir(dstdir, dry)
853
print "cp -f", src, dst
856
shutil.copyfile(src, dst)
857
shutil.copymode(src, dst)
858
except (shutil.Error, IOError), e:
859
print "Warning: " + str(e)
861
def action_symlink(src, dst, dry):
862
"""Creates a symlink in a given location. Creates all parent directories
865
dstdir = os.path.split(dst)[0]
866
if not os.path.isdir(dstdir):
867
action_mkdir(dstdir, dry)
868
# Delete existing file
869
if os.path.exists(dst):
871
print "ln -fs", src, dst
875
def action_append(ivle_pth, ivle_www):
876
file = open(ivle_pth, 'a+')
877
file.write(ivle_www + '\n')
880
def action_chown_setuid(file, dry):
881
"""Chowns a file to root, and sets the setuid bit on the file.
882
Calling this function requires the euid to be root.
883
The actual mode of path is set to: rws--s--s
885
print "chown root:root", file
888
print "chmod a+xs", file
889
print "chmod u+rw", file
891
os.chmod(file, stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
892
| stat.S_ISUID | stat.S_IRUSR | stat.S_IWUSR)
894
def action_chmod_x(file, dry):
895
"""Chmod 755 a file (sets permissions to rwxr-xr-x)."""
896
print "chmod 755", file
898
os.chmod(file, stat.S_IXUSR | stat.S_IRUSR | stat.S_IWUSR
899
| stat.S_IXGRP | stat.S_IRGRP | stat.S_IXOTH | stat.S_IROTH)
464
901
def query_user(default, prompt):
465
902
"""Prompts the user for a string, which is read from a line of stdin.
466
903
Exits silently if EOF is encountered. Returns the string, with spaces