From c4beba1cf08d17076824131c73d89f0ef5f414dc Mon Sep 17 00:00:00 2001
From: Iustin Pop <iustin@google.com>
Date: Wed, 23 Jul 2008 10:06:08 +0000
Subject: [PATCH] Make the job storage init reuse a serial file

This will be needed for master failover. If we don't have a valid queue
directory, we need to reinitialize it, but we should keep the existing
serial number.

As such, we abstract the reading of the serial and if we find a valid
serial, we do not reset it.

Reviewed-by: imsnah
---
 lib/jqueue.py | 34 +++++++++++++++++++++++++++-------
 1 file changed, 27 insertions(+), 7 deletions(-)

diff --git a/lib/jqueue.py b/lib/jqueue.py
index e8a2bd525..01ba10e3b 100644
--- a/lib/jqueue.py
+++ b/lib/jqueue.py
@@ -309,12 +309,31 @@ class JobStorage(object):
     finally:
       version_fd.close()
 
-    serial_fd = open(constants.JOB_QUEUE_SERIAL_FILE, "r")
+    self._last_serial = self._ReadSerial()
+    if self._last_serial is None:
+      raise errors.ConfigurationError("Can't read/parse the job queue serial"
+                                      " file")
+
+  @staticmethod
+  def _ReadSerial():
+    """Try to read the job serial file.
+
+    @rtype: None or int
+    @return: If the serial can be read, then it is returned. Otherwise None
+             is returned.
+
+    """
     try:
-      # Read last serial
-      self._last_serial = int(serial_fd.read(1024).strip())
-    finally:
-      serial_fd.close()
+      serial_fd = open(constants.JOB_QUEUE_SERIAL_FILE, "r")
+      try:
+        # Read last serial
+        serial = int(serial_fd.read(1024).strip())
+      finally:
+        serial_fd.close()
+    except (ValueError, EnvironmentError):
+      serial = None
+
+    return serial
 
   def Close(self):
     assert self.lock_fd, "Queue should be open"
@@ -327,8 +346,9 @@ class JobStorage(object):
 
     utils.WriteFile(constants.JOB_QUEUE_VERSION_FILE,
                     data="%s\n" % constants.JOB_QUEUE_VERSION)
-    utils.WriteFile(constants.JOB_QUEUE_SERIAL_FILE,
-                    data="%s\n" % 0)
+    if self._ReadSerial() is None:
+      utils.WriteFile(constants.JOB_QUEUE_SERIAL_FILE,
+                      data="%s\n" % 0)
 
   def _NewSerialUnlocked(self):
     """Generates a new job identifier.
-- 
GitLab