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

« back to all changes in this revision

Viewing changes to bin/ivle-loadsampledata

  • Committer: William Grant
  • Date: 2009-12-17 05:36:03 UTC
  • Revision ID: me@williamgrant.id.au-20091217053603-duup7h948uzvmwid
Hook in the unversioned icon.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
# IVLE - Informatics Virtual Learning Environment
 
3
# Copyright (C) 2007-2009 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
"""
 
20
Script to load the sample data into a fresh IVLE instance, for testing or
 
21
experimentation.
 
22
"""
 
23
 
 
24
import sys
 
25
import os
 
26
import shutil
 
27
import optparse
 
28
import subprocess
 
29
import logging
 
30
import readline
 
31
import warnings
 
32
 
 
33
import psycopg2
 
34
 
 
35
from ivle.config import Config
 
36
import ivle.svn
 
37
 
 
38
logging.basicConfig(
 
39
    format='%(asctime)s %(levelname)s %(message)s',
 
40
    level=logging.INFO)
 
41
 
 
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.
 
46
    """
 
47
    proc = subprocess.Popen(*popenargs, stderr=subprocess.PIPE, **kwargs)
 
48
    _, stderr = proc.communicate()
 
49
    if proc.returncode == 0:
 
50
        return None
 
51
    else:
 
52
        return stderr
 
53
 
 
54
if os.getuid() != 0:
 
55
    print "Must run %s as root." % os.path.basename(sys.argv[0])
 
56
    sys.exit(1)
 
57
 
 
58
usage = """usage: %prog [OPTIONS] <SQL-FILE>
 
59
Loads the sample data into the installed IVLE instance."""
 
60
 
 
61
parser = optparse.OptionParser(usage)
 
62
parser.add_option("-f", "--force",
 
63
    action="store_true", dest="force",
 
64
    help="destroy all data without prompting",
 
65
    default=False
 
66
    )
 
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)",
 
71
    default="postgres"
 
72
    )
 
73
 
 
74
(options, args) = parser.parse_args()
 
75
 
 
76
if len(args) != 1:
 
77
    parser.error("incorrect number of arguments")
 
78
 
 
79
sqlfile = args[0]
 
80
 
 
81
dbconfig = Config()['database']
 
82
 
 
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
 
93
        if not options.force:
 
94
            try:
 
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):
 
98
                print
 
99
                sys.exit(1)
 
100
            if drop.strip().lower() != "yes":
 
101
                sys.exit(1)
 
102
        # OK, here we go
 
103
 
 
104
        # Unmount all the jails
 
105
        logging.info("Unmounting all users.")
 
106
        subprocess.check_call(["bin/ivle-mountallusers", "-u"])
 
107
 
 
108
        # Drop database
 
109
        logging.info("Dropping database \"%s\"." % dbconfig["name"])
 
110
        errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
 
111
                                        "dropdb", dbconfig["name"]])
 
112
        # Re-create database
 
113
        logging.info("Creating database \"%s\"." % dbconfig["name"])
 
114
        errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
 
115
                                        "createdb", "-O",dbconfig["username"],
 
116
                                        dbconfig["name"]])
 
117
    else:
 
118
        logging.error(errmsg.strip())
 
119
        sys.exit(1)
 
120
 
 
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"]])
 
125
 
 
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())
 
135
schemafile.close()
 
136
 
 
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"])
 
140
 
 
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"])
 
145
 
 
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"]],
 
150
                        stdin=file)
 
151
if proc.wait() != 0:
 
152
    file.close()
 
153
    sys.exit(1)
 
154
file.close()
 
155
 
 
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"])
 
160
 
 
161
config = Config()
 
162
dbconfig = config['database']
 
163
 
 
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.
 
168
    """
 
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)
 
176
    return tempdir
 
177
 
 
178
logging.info("Populating student repositories")
 
179
 
 
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):
 
185
    os.makedirs(dirname)
 
186
svnclient.add(dirname, force=True)
 
187
# XXX Copy files from a sample directory
 
188
f = open(filename, "w")
 
189
f.write("""\
 
190
# Hello IVLE, by Alice Student
 
191
# CGI program -- Prints CGI headers, then HTML output
 
192
 
 
193
print "Content-Type: text/html"
 
194
print
 
195
print "<html><body><p>Hello, world!</p></body></html>"
 
196
""")
 
197
f.close()
 
198
svnclient.add(filename, force=True)
 
199
svnclient.checkin(workspace, "Added some files")
 
200
shutil.rmtree(workspace)