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

« back to all changes in this revision

Viewing changes to bin/ivle-loadsampledata

  • Committer: David Coles
  • Date: 2009-12-09 01:40:49 UTC
  • Revision ID: coles.david@gmail.com-20091209014049-cii7hntudzuo7to9
Remove diagnostic print from ivle-config

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 optparse
 
27
import subprocess
 
28
import logging
 
29
import readline
 
30
 
 
31
from ivle.config import Config
 
32
 
 
33
logging.basicConfig(
 
34
    format='%(asctime)s %(levelname)s %(message)s',
 
35
    level=logging.INFO)
 
36
 
 
37
def runprog_stderr(*popenargs, **kwargs):
 
38
    """Run a program, using subprocess.Popen.
 
39
    Return None if the program had a 0 return code.
 
40
    Return the string stderr if the program failed.
 
41
    """
 
42
    proc = subprocess.Popen(*popenargs, stderr=subprocess.PIPE, **kwargs)
 
43
    _, stderr = proc.communicate()
 
44
    if proc.returncode == 0:
 
45
        return None
 
46
    else:
 
47
        return stderr
 
48
 
 
49
if os.getuid() != 0:
 
50
    print "Must run %s as root." % os.path.basename(sys.argv[0])
 
51
    sys.exit(1)
 
52
 
 
53
usage = """usage: %prog [OPTIONS] <SQL-FILE>
 
54
Loads the sample data into the installed IVLE instance."""
 
55
 
 
56
parser = optparse.OptionParser(usage)
 
57
parser.add_option("-f", "--force",
 
58
    action="store_true", dest="force",
 
59
    help="destroy all data without prompting",
 
60
    default=False
 
61
    )
 
62
parser.add_option("--pg-user",
 
63
    action="store", dest="pg_user",
 
64
    help="database super-user (for dropping and creating db) "
 
65
        "(default: postgres)",
 
66
    default="postgres"
 
67
    )
 
68
 
 
69
(options, args) = parser.parse_args()
 
70
 
 
71
if len(args) != 1:
 
72
    parser.error("incorrect number of arguments")
 
73
 
 
74
sqlfile = args[0]
 
75
 
 
76
dbconfig = Config()['database']
 
77
 
 
78
# Try creating the database (if it succeeds, no harm)
 
79
logging.info("Creating database \"%s\"." % dbconfig["name"])
 
80
errmsg = runprog_stderr(["sudo", "-u", options.pg_user, "createdb", "-O",
 
81
                         dbconfig["username"], dbconfig["name"]])
 
82
if errmsg is not None:
 
83
    # Couldn't create the DB
 
84
    if errmsg.strip().endswith("already exists"):
 
85
        logging.info("Database already exists.")
 
86
        # The database already exists (most common error)
 
87
        # Drop and re-create the database, if the user is absolutely sure
 
88
        if not options.force:
 
89
            try:
 
90
                drop = raw_input("Do you want to delete all existing data? "
 
91
                            "THIS WILL DROP YOUR DATABASE!\n[yes/no]> ")
 
92
            except (KeyboardInterrupt, EOFError):
 
93
                print
 
94
                sys.exit(1)
 
95
            if drop.strip().lower() != "yes":
 
96
                sys.exit(1)
 
97
        # OK, here we go
 
98
 
 
99
        # Unmount all the jails
 
100
        logging.info("Unmounting all users.")
 
101
        subprocess.check_call(["bin/ivle-mountallusers", "-u"])
 
102
 
 
103
        # Drop database
 
104
        logging.info("Dropping database \"%s\"." % dbconfig["name"])
 
105
        errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
 
106
                                        "dropdb", dbconfig["name"]])
 
107
        # Re-create database
 
108
        logging.info("Creating database \"%s\"." % dbconfig["name"])
 
109
        errmsg = subprocess.check_call(["sudo", "-u", options.pg_user,
 
110
                                        "createdb", "-O",dbconfig["username"],
 
111
                                        dbconfig["name"]])
 
112
    else:
 
113
        logging.error(errmsg.strip())
 
114
        sys.exit(1)
 
115
 
 
116
# Create "plpgsql" language
 
117
logging.info("Creating language plpgsql.")
 
118
errmsg = subprocess.check_call(["sudo", "-u", options.pg_user, "createlang",
 
119
                         "plpgsql", dbconfig["name"]])
 
120
 
 
121
# Populate with database schema
 
122
logging.info("Populating database with schema.")
 
123
file = open("userdb/users.sql")
 
124
proc = subprocess.Popen(["psql", "-h", "localhost", "-W", dbconfig["name"],
 
125
                           dbconfig["username"]], stdin=file)
 
126
if proc.wait() != 0:
 
127
    file.close()
 
128
    sys.exit(1)
 
129
file.close()
 
130
 
 
131
# Build or rebuild all of the users' filesystems and subversion repos
 
132
logging.info("Creating data directories.")
 
133
subprocess.check_call(["bin/ivle-createdatadirs"])
 
134
 
 
135
# Move all of the users' filesystems and subversion repos out of the way
 
136
# (This will clean out the user dirs because there are no users in the DB.)
 
137
logging.info("Moving existing user filesystems and repos out of the way.")
 
138
subprocess.check_call(["bin/ivle-refreshfilesystem"])
 
139
 
 
140
# Populate with sample data
 
141
logging.info("Populating database with sample data.")
 
142
file = open("examples/db/sample.sql")
 
143
proc = subprocess.Popen(["sudo", "-u", "postgres", "psql", dbconfig["name"]],
 
144
                        stdin=file)
 
145
if proc.wait() != 0:
 
146
    file.close()
 
147
    sys.exit(1)
 
148
file.close()
 
149
 
 
150
# Build all of the users' filesystems and subversion repos
 
151
# (This will create fresh user dirs and repos because the jails were empty.)
 
152
logging.info("Building sample users' filesystems and repos.")
 
153
subprocess.check_call(["bin/ivle-refreshfilesystem"])