2
# IVLE - Informatics Virtual Learning Environment
3
# Copyright (C) 2007-2009 The University of Melbourne
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.
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.
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
20
Script to load the sample data into a fresh IVLE instance, for testing or
35
from ivle.config import Config
39
format='%(asctime)s %(levelname)s %(message)s',
42
def runprog_stderr(*popenargs, **kwargs):
43
"""Run a program, using subprocess.Popen.
44
Return None if the program had a 0 return code.
45
Return the string stderr if the program failed.
47
proc = subprocess.Popen(*popenargs, stderr=subprocess.PIPE, **kwargs)
48
_, stderr = proc.communicate()
49
if proc.returncode == 0:
55
print "Must run %s as root." % os.path.basename(sys.argv[0])
58
usage = """usage: %prog [OPTIONS] <SQL-FILE>
59
Loads the sample data into the installed IVLE instance."""
61
parser = optparse.OptionParser(usage)
62
parser.add_option("-f", "--force",
63
action="store_true", dest="force",
64
help="destroy all data without prompting",
67
parser.add_option("--pg-user",
68
action="store", dest="pg_user",
69
help="database super-user (for dropping and creating db) "
70
"(default: postgres)",
74
(options, args) = parser.parse_args()
77
parser.error("incorrect number of arguments")
81
dbconfig = Config()['database']
83
# Try creating the database (if it succeeds, no harm)
84
logging.info("Creating database \"%s\"." % dbconfig["name"])
85
errmsg = runprog_stderr(["sudo", "-u", options.pg_user, "createdb", "-O",
86
dbconfig["username"], dbconfig["name"]])
87
if errmsg is not None:
88
# Couldn't create the DB
89
if errmsg.strip().endswith("already exists"):
90
logging.info("Database already exists.")
91
# The database already exists (most common error)
92
# Drop and re-create the database, if the user is absolutely sure
95
drop = raw_input("Do you want to delete all existing data? "
96
"THIS WILL DROP YOUR DATABASE!\n[yes/no]> ")
97
except (KeyboardInterrupt, EOFError):
100
if drop.strip().lower() != "yes":
104
# Unmount all the jails
105
logging.info("Unmounting all users.")
106
subprocess.check_call(["bin/ivle-mountallusers", "-u"])
109
logging.info("Dropping database \"%s\"." % dbconfig["name"])
110
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
111
"dropdb", dbconfig["name"]])
113
logging.info("Creating database \"%s\"." % dbconfig["name"])
114
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
115
"createdb", "-O",dbconfig["username"],
118
logging.error(errmsg.strip())
121
# Create "plpgsql" language
122
logging.info("Creating language plpgsql.")
123
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user, "createlang",
124
"plpgsql", dbconfig["name"]])
126
# Populate with database schema
127
logging.info("Populating database with schema.")
128
ivleconn = psycopg2.connect(
129
host='localhost', database=dbconfig['name'], user=dbconfig['username'],
130
password=dbconfig['password'])
131
ivlecursor = ivleconn.cursor()
132
logging.info("Populating database with schema.")
133
schemafile = open("userdb/users.sql")
134
ivlecursor.execute(schemafile.read())
137
# Build or rebuild all of the users' filesystems and subversion repos
138
logging.info("Creating data directories.")
139
subprocess.check_call(["bin/ivle-createdatadirs"])
141
# Move all of the users' filesystems and subversion repos out of the way
142
# (This will clean out the user dirs because there are no users in the DB.)
143
logging.info("Moving existing user filesystems and repos out of the way.")
144
subprocess.check_call(["bin/ivle-refreshfilesystem"])
146
# Populate with sample data
147
logging.info("Populating database with sample data.")
148
file = open("examples/db/sample.sql")
149
proc = subprocess.Popen(["sudo", "-u", "postgres", "psql", dbconfig["name"]],
156
# Build all of the users' filesystems and subversion repos
157
# (This will create fresh user dirs and repos because the jails were empty.)
158
logging.info("Building sample users' filesystems and repos.")
159
subprocess.check_call(["bin/ivle-refreshfilesystem"])
162
dbconfig = config['database']
164
# Populate some of the users' Subversion repos
165
def temp_checkout(svnclient, username):
166
"""Checkout user `username`'s repo to a temporary directory.
167
@return: The temporary workspace directory.
169
# Do the checkout over HTTP, since we then use the user's own credentials
170
repourl = config['urls']['svn_addr'] + '/users/' + username
171
# Ignore warnings about the use of tempnam
172
warnings.simplefilter('ignore')
173
tempdir = os.tempnam()
174
warnings.resetwarnings()
175
svnclient.checkout(repourl, tempdir)
178
logging.info("Populating student repositories")
180
svnclient = ivle.svn.create_auth_svn_client_autopass("studenta")
181
workspace = temp_checkout(svnclient, "studenta")
182
dirname = os.path.join(workspace, "stuff")
183
filename = os.path.join(dirname, "hello.py")
184
if not os.path.isdir(dirname):
186
svnclient.add(dirname, force=True)
187
# XXX Copy files from a sample directory
188
f = open(filename, "w")
190
# Hello IVLE, by Alice Student
191
# CGI program -- Prints CGI headers, then HTML output
193
print "Content-Type: text/html"
195
print "<html><body><p>Hello, world!</p></body></html>"
198
svnclient.add(filename, force=True)
199
svnclient.checkin(workspace, "Added some files")
200
shutil.rmtree(workspace)