]> git.decadent.org.uk Git - dak.git/blob - dak/update_db.py
e59a558c5344418cf3f4b554152ed8672878ae8e
[dak.git] / dak / update_db.py
1 #!/usr/bin/env python
2
3 # Debian Archive Kit Database Update Script
4 # Copyright (C) 2008  Michael Casadevall <mcasadevall@debian.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # <Ganneff> when do you have it written?
23 # <NCommander> Ganneff, after you make my debian account
24 # <Ganneff> blackmail wont work
25 # <NCommander> damn it
26
27 ################################################################################
28
29 import psycopg2, sys, fcntl, os
30 import apt_pkg
31 import time
32 from daklib import database
33 from daklib import utils
34
35 ################################################################################
36
37 Cnf = None
38 projectB = None
39 required_database_schema = 1
40
41 ################################################################################
42
43 class UpdateDB:
44     def usage (self, exit_code=0):
45         print """Usage: dak update-db
46 Updates dak's database schema to the lastest version. You should disable crontabs while this is running
47
48   -h, --help                show this help and exit."""
49         sys.exit(exit_code)
50
51
52 ################################################################################
53
54     def update_db_to_zero(self):
55         # This function will attempt to update a pre-zero database schema to zero
56
57         # First, do the sure thing, and create the configuration table
58         try:
59             print "Creating configuration table ..."
60             c = self.db.cursor()
61             c.execute("""CREATE TABLE config (
62                                   id SERIAL PRIMARY KEY NOT NULL,
63                                   name TEXT UNIQUE NOT NULL,
64                                   value TEXT
65                                 );""")
66             c.execute("INSERT INTO config VALUES ( nextval('config_id_seq'), 'db_revision', '0')");
67             self.db.commit()
68
69         except psycopg2.ProgrammingError:
70             self.db.rollback()
71             print "Failed to create configuration table."
72             print "Can the projectB user CREATE TABLE?"
73             print ""
74             print "Aborting update."
75             sys.exit(-255)
76
77 ################################################################################
78
79     def get_db_rev(self):
80         global projectB
81
82         # We keep database revision info the config table
83         # Try and access it
84
85         try:
86             c = self.db.cursor()
87             q = c.execute("SELECT value FROM config WHERE name = 'db_revision';");
88             return c.fetchone()[0]
89
90         except psycopg2.ProgrammingError:
91             # Whoops .. no config table ...
92             self.db.rollback()
93             print "No configuration table found, assuming dak database revision to be pre-zero"
94             return -1
95
96 ################################################################################
97
98     def update_db(self):
99         # Ok, try and find the configuration table
100         print "Determining dak database revision ..."
101
102         try:
103             # Build a connect string
104             connect_str = "dbname=%s"% (Cnf["DB::Name"])
105             if Cnf["DB::Host"] != '': connect_str += " host=%s" % (Cnf["DB::Host"])
106             if Cnf["DB::Port"] != '-1': connect_str += " port=%d" % (int(Cnf["DB::Port"]))
107
108             self.db = psycopg2.connect(connect_str)
109
110         except:
111             print "FATAL: Failed connect to database"
112             pass
113
114         database_revision = int(self.get_db_rev())
115
116         if database_revision == -1:
117             print "dak database schema predates update-db."
118             print ""
119             print "This script will attempt to upgrade it to the lastest, but may fail."
120             print "Please make sure you have a database backup handy. If you don't, press Ctrl-C now!"
121             print ""
122             print "Continuing in five seconds ..."
123             time.sleep(5)
124             print ""
125             print "Attempting to upgrade pre-zero database to zero"
126
127             self.update_db_to_zero()
128             database_revision = 0
129
130         print "dak database schema at " + str(database_revision)
131         print "dak version requires schema " + str(required_database_schema)
132
133         if database_revision == required_database_schema:
134             print "no updates required"
135             sys.exit(0)
136
137         for i in range (database_revision, required_database_schema):
138             print "updating databse schema from " + str(database_revision) + " to " + str(i+1)
139             dakdb = __import__("dakdb", globals(), locals(), ['update'+str(i+1)])
140             update_module = getattr(dakdb, "update"+str(i+1))
141             update_module.do_update(self)
142             database_revision += 1
143
144 ################################################################################
145
146     def init (self):
147         global Cnf, projectB
148
149         Cnf = utils.get_conf()
150         arguments = [('h', "help", "Update-DB::Options::Help")]
151         for i in [ "help" ]:
152             if not Cnf.has_key("Update-DB::Options::%s" % (i)):
153                 Cnf["Update-DB::Options::%s" % (i)] = ""
154
155         arguments = apt_pkg.ParseCommandLine(Cnf, arguments, sys.argv)
156
157         options = Cnf.SubTree("Update-DB::Options")
158         if options["Help"]:
159             self.usage()
160         elif arguments:
161             utils.warn("dak update-db takes no arguments.")
162             self.usage(exit_code=1)
163
164
165         self.update_db()
166
167         try:
168             lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
169             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
170         except IOError, e:
171             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
172                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-unchecked' is already running.")
173
174
175 ################################################################################
176
177 if __name__ == '__main__':
178     app = UpdateDB()
179     app.init()
180
181 def main():
182     app = UpdateDB()
183     app.init()