]> git.decadent.org.uk Git - dak.git/blobdiff - dak/update_db.py
Merge remote branch 'mhy/master' into merge
[dak.git] / dak / update_db.py
index 7cb8a2752b65afc341c8702b1db109f6d482ba3a..3effa47741362500138fd6a18df0b8821837b362 100755 (executable)
@@ -1,7 +1,11 @@
 #!/usr/bin/env python
 
-# Debian Archive Kit Database Update Script
+""" Database Update Main Script
+
+@contact: Debian FTP Master <ftpmaster@debian.org>
 # Copyright (C) 2008  Michael Casadevall <mcasadevall@debian.org>
+@license: GNU General Public License version 2 or later
+"""
 
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
 
 ################################################################################
 
-import psycopg2, sys, fcntl, os
+import psycopg2
+import sys
+import fcntl
+import os
 import apt_pkg
 import time
-from daklib import database
+import errno
+
 from daklib import utils
+from daklib.config import Config
+from daklib.dak_exceptions import DBUpdateError
+from daklib.daklog import Logger
 
 ################################################################################
 
 Cnf = None
-projectB = None
-required_database_schema = 1
+required_database_schema = 48
 
 ################################################################################
 
@@ -52,7 +62,7 @@ Updates dak's database schema to the lastest version. You should disable crontab
 ################################################################################
 
     def update_db_to_zero(self):
-        # This function will attempt to update a pre-zero database schema to zero
+        """ This function will attempt to update a pre-zero database schema to zero """
 
         # First, do the sure thing, and create the configuration table
         try:
@@ -63,7 +73,7 @@ Updates dak's database schema to the lastest version. You should disable crontab
                                   name TEXT UNIQUE NOT NULL,
                                   value TEXT
                                 );""")
-            c.execute("INSERT INTO config VALUES ( nextval('config_id_seq'), 'db_revision', '0')");
+            c.execute("INSERT INTO config VALUES ( nextval('config_id_seq'), 'db_revision', '0')")
             self.db.commit()
 
         except psycopg2.ProgrammingError:
@@ -77,14 +87,12 @@ Updates dak's database schema to the lastest version. You should disable crontab
 ################################################################################
 
     def get_db_rev(self):
-        global projectB
-
         # We keep database revision info the config table
         # Try and access it
 
         try:
             c = self.db.cursor()
-            q = c.execute("SELECT value FROM config WHERE name = 'db_revision';");
+            q = c.execute("SELECT value FROM config WHERE name = 'db_revision';")
             return c.fetchone()[0]
 
         except psycopg2.ProgrammingError:
@@ -93,20 +101,43 @@ Updates dak's database schema to the lastest version. You should disable crontab
             print "No configuration table found, assuming dak database revision to be pre-zero"
             return -1
 
+################################################################################
+
+    def get_transaction_id(self):
+        '''
+        Returns the current transaction id as a string.
+        '''
+        cursor = self.db.cursor()
+        cursor.execute("SELECT txid_current();")
+        id = cursor.fetchone()[0]
+        cursor.close()
+        return id
+
 ################################################################################
 
     def update_db(self):
         # Ok, try and find the configuration table
         print "Determining dak database revision ..."
+        cnf = Config()
+        logger = Logger(cnf.Cnf, 'update-db')
 
         try:
-            self.db = psycopg2.connect("dbname='" + Cnf["DB::Name"] + "' host='" + Cnf["DB::Host"] + "' port='" + str(Cnf["DB::Port"]) + "'")
+            # Build a connect string
+            if cnf["DB::Service"]:
+                connect_str = "service=%s" % cnf["DB::Service"]
+            else:
+                connect_str = "dbname=%s"% (cnf["DB::Name"])
+                if cnf["DB::Host"] != '': connect_str += " host=%s" % (cnf["DB::Host"])
+                if cnf["DB::Port"] != '-1': connect_str += " port=%d" % (int(cnf["DB::Port"]))
+
+            self.db = psycopg2.connect(connect_str)
 
         except:
             print "FATAL: Failed connect to database"
             pass
 
         database_revision = int(self.get_db_rev())
+        logger.log(['transaction id before update: %s' % self.get_transaction_id()])
 
         if database_revision == -1:
             print "dak database schema predates update-db."
@@ -122,50 +153,59 @@ Updates dak's database schema to the lastest version. You should disable crontab
             self.update_db_to_zero()
             database_revision = 0
 
-        print "dak database schema at " + str(database_revision)
-        print "dak version requires schema " + str(required_database_schema)
+        print "dak database schema at %d" % database_revision
+        print "dak version requires schema %d"  % required_database_schema
 
         if database_revision == required_database_schema:
             print "no updates required"
+            logger.log(["no updates required"])
             sys.exit(0)
 
         for i in range (database_revision, required_database_schema):
-            print "updating databse schema from " + str(database_revision) + " to " + str(i+1)
-            dakdb = __import__("dakdb", globals(), locals(), ['update'+str(i+1)])
-            update_module = getattr(dakdb, "update"+str(i+1))
-            update_module.do_update(self)
-            database_revision =+ 1
+            try:
+                dakdb = __import__("dakdb", globals(), locals(), ['update'+str(i+1)])
+                update_module = getattr(dakdb, "update"+str(i+1))
+                update_module.do_update(self)
+                message = "updated database schema from %d to %d" % (database_revision, i+1)
+                print message
+                logger.log([message])
+            except DBUpdateError, e:
+                # Seems the update did not work.
+                print "Was unable to update database schema from %d to %d." % (database_revision, i+1)
+                print "The error message received was %s" % (e)
+                logger.log(["DB Schema upgrade failed"])
+                logger.close()
+                utils.fubar("DB Schema upgrade failed")
+            database_revision += 1
+        logger.close()
 
 ################################################################################
 
     def init (self):
-        global Cnf, projectB
-
-        Cnf = utils.get_conf()
+        cnf = Config()
         arguments = [('h', "help", "Update-DB::Options::Help")]
         for i in [ "help" ]:
-            if not Cnf.has_key("Update-DB::Options::%s" % (i)):
-                Cnf["Update-DB::Options::%s" % (i)] = ""
+            if not cnf.has_key("Update-DB::Options::%s" % (i)):
+                cnf["Update-DB::Options::%s" % (i)] = ""
 
-        arguments = apt_pkg.ParseCommandLine(Cnf, arguments, sys.argv)
+        arguments = apt_pkg.ParseCommandLine(cnf.Cnf, arguments, sys.argv)
 
-        options = Cnf.SubTree("Update-DB::Options")
+        options = cnf.SubTree("Update-DB::Options")
         if options["Help"]:
-            usage()
+            self.usage()
         elif arguments:
             utils.warn("dak update-db takes no arguments.")
-            usage(exit_code=1)
-
-
-        self.update_db()
+            self.usage(exit_code=1)
 
         try:
-            lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
+            lock_fd = os.open(cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
         except IOError, e:
             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
                 utils.fubar("Couldn't obtain lock; assuming another 'dak process-unchecked' is already running.")
 
+        self.update_db()
+
 
 ################################################################################