4 # Copyright (C) 2006, 2007 Google Inc.
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.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
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., 51 Franklin Street, Fifth Floor, Boston, MA
22 """Module implementing the job queue handling."""
26 from ganeti import constants
27 from ganeti import errors
28 from ganeti import utils
31 def _ReadNumericFile(file_name):
32 """Reads a file containing a number.
35 @return: None if file is not found, otherwise number
39 return int(utils.ReadFile(file_name))
40 except EnvironmentError, err:
41 if err.errno in (errno.ENOENT, ):
47 """Read the serial file.
49 The queue should be locked while this function is called.
52 return _ReadNumericFile(constants.JOB_QUEUE_SERIAL_FILE)
56 """Read the queue version.
58 The queue should be locked while this function is called.
61 return _ReadNumericFile(constants.JOB_QUEUE_VERSION_FILE)
64 def InitAndVerifyQueue(must_lock):
65 """Open and lock job queue.
67 If necessary, the queue is automatically initialized.
70 @param must_lock: Whether an exclusive lock must be held.
71 @rtype: utils.FileLock
72 @return: Lock object for the queue. This can be used to change the
76 dirs = [(d, constants.JOB_QUEUE_DIRS_MODE) for d in constants.JOB_QUEUE_DIRS]
77 utils.EnsureDirs(dirs)
80 queue_lock = utils.FileLock.Open(constants.JOB_QUEUE_LOCK_FILE)
82 # The queue needs to be locked in exclusive mode to write to the serial and
85 queue_lock.Exclusive(blocking=True)
89 queue_lock.Exclusive(blocking=False)
91 except errors.LockError:
92 # Ignore errors and assume the process keeping the lock checked
98 version = ReadVersion()
100 # Write new version file
101 utils.WriteFile(constants.JOB_QUEUE_VERSION_FILE,
102 data="%s\n" % constants.JOB_QUEUE_VERSION)
105 version = ReadVersion()
107 if version != constants.JOB_QUEUE_VERSION:
108 raise errors.JobQueueError("Found job queue version %s, expected %s",
109 version, constants.JOB_QUEUE_VERSION)
111 serial = ReadSerial()
113 # Write new serial file
114 utils.WriteFile(constants.JOB_QUEUE_SERIAL_FILE,
118 serial = ReadSerial()
121 # There must be a serious problem
122 raise errors.JobQueueError("Can't read/parse the job queue"
126 # There's no need for more error handling. Closing the lock
127 # file below in case of an error will unlock it anyway.