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
33
from ivle.config import Config
36
format='%(asctime)s %(levelname)s %(message)s',
39
def runprog_stderr(*popenargs, **kwargs):
40
"""Run a program, using subprocess.Popen.
41
Return None if the program had a 0 return code.
42
Return the string stderr if the program failed.
44
proc = subprocess.Popen(*popenargs, stderr=subprocess.PIPE, **kwargs)
45
_, stderr = proc.communicate()
46
if proc.returncode == 0:
52
print "Must run %s as root." % os.path.basename(sys.argv[0])
55
usage = """usage: %prog [OPTIONS] <SQL-FILE>
56
Loads the sample data into the installed IVLE instance."""
58
parser = optparse.OptionParser(usage)
59
parser.add_option("-f", "--force",
60
action="store_true", dest="force",
61
help="destroy all data without prompting",
64
parser.add_option("--pg-user",
65
action="store", dest="pg_user",
66
help="database super-user (for dropping and creating db) "
67
"(default: postgres)",
71
(options, args) = parser.parse_args()
74
parser.error("incorrect number of arguments")
78
dbconfig = Config()['database']
80
# Try creating the database (if it succeeds, no harm)
81
logging.info("Creating database \"%s\"." % dbconfig["name"])
82
errmsg = runprog_stderr(["sudo", "-u", options.pg_user, "createdb", "-O",
83
dbconfig["username"], dbconfig["name"]])
84
if errmsg is not None:
85
# Couldn't create the DB
86
if errmsg.strip().endswith("already exists"):
87
logging.info("Database already exists.")
88
# The database already exists (most common error)
89
# Drop and re-create the database, if the user is absolutely sure
92
drop = raw_input("Do you want to delete all existing data? "
93
"THIS WILL DROP YOUR DATABASE!\n[yes/no]> ")
94
except (KeyboardInterrupt, EOFError):
97
if drop.strip().lower() != "yes":
101
# Unmount all the jails
102
logging.info("Unmounting all users.")
103
subprocess.check_call(["bin/ivle-mountallusers", "-u"])
106
logging.info("Dropping database \"%s\"." % dbconfig["name"])
107
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
108
"dropdb", dbconfig["name"]])
110
logging.info("Creating database \"%s\"." % dbconfig["name"])
111
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
112
"createdb", "-O",dbconfig["username"],
115
logging.error(errmsg.strip())
118
# Create "plpgsql" language
119
logging.info("Creating language plpgsql.")
120
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user, "createlang",
121
"plpgsql", dbconfig["name"]])
123
# Populate with database schema
124
logging.info("Populating database with schema.")
125
ivleconn = psycopg2.connect(
126
host='localhost', database=dbconfig['name'], user=dbconfig['username'],
127
password=dbconfig['password'])
128
ivlecursor = ivleconn.cursor()
129
logging.info("Populating database with schema.")
130
schemafile = open("userdb/users.sql")
131
ivlecursor.execute(schemafile.read())
134
# Build or rebuild all of the users' filesystems and subversion repos
135
logging.info("Creating data directories.")
136
subprocess.check_call(["bin/ivle-createdatadirs"])
138
# Move all of the users' filesystems and subversion repos out of the way
139
# (This will clean out the user dirs because there are no users in the DB.)
140
logging.info("Moving existing user filesystems and repos out of the way.")
141
subprocess.check_call(["bin/ivle-refreshfilesystem"])
143
# Populate with sample data
144
logging.info("Populating database with sample data.")
145
file = open("examples/db/sample.sql")
146
proc = subprocess.Popen(["sudo", "-u", "postgres", "psql", dbconfig["name"]],
153
# Build all of the users' filesystems and subversion repos
154
# (This will create fresh user dirs and repos because the jails were empty.)
155
logging.info("Building sample users' filesystems and repos.")
156
subprocess.check_call(["bin/ivle-refreshfilesystem"])