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
21 # Disable "Invalid name ..." message
22 # pylint: disable-msg=C0103
24 """Module implementing the Ganeti locking code."""
32 from ganeti import errors
33 from ganeti import utils
36 def ssynchronized(lock, shared=0):
37 """Shared Synchronization decorator.
39 Calls the function holding the given lock, either in exclusive or shared
40 mode. It requires the passed lock to be a SharedLock (or support its
45 def sync_function(*args, **kwargs):
46 lock.acquire(shared=shared)
48 return fn(*args, **kwargs)
55 class _SingleNotifyPipeConditionWaiter(object):
56 """Helper class for SingleNotifyPipeCondition
64 def __init__(self, poller, fd):
65 """Constructor for _SingleNotifyPipeConditionWaiter
67 @type poller: select.poll
68 @param poller: Poller object
70 @param fd: File descriptor to wait for
77 def __call__(self, timeout):
78 """Wait for something to happen on the pipe.
80 @type timeout: float or None
81 @param timeout: Timeout for waiting (can be None)
84 start_time = time.time()
85 remaining_time = timeout
87 while timeout is None or remaining_time > 0:
89 result = self._poller.poll(remaining_time)
90 except EnvironmentError, err:
91 if err.errno != errno.EINTR:
95 # Check whether we were notified
96 if result and result[0][0] == self._fd:
99 # Re-calculate timeout if necessary
100 if timeout is not None:
101 remaining_time = start_time + timeout - time.time()
104 class _BaseCondition(object):
105 """Base class containing common code for conditions.
107 Some of this code is taken from python's threading module.
116 def __init__(self, lock):
117 """Constructor for _BaseCondition.
119 @type lock: threading.Lock
120 @param lock: condition base lock
123 object.__init__(self)
125 # Recursive locks are not supported
126 assert not hasattr(lock, "_acquire_restore")
127 assert not hasattr(lock, "_release_save")
131 # Export the lock's acquire() and release() methods
132 self.acquire = lock.acquire
133 self.release = lock.release
136 """Check whether lock is owned by current thread.
139 if self._lock.acquire(0):
145 def _check_owned(self):
146 """Raise an exception if the current thread doesn't own the lock.
149 if not self._is_owned():
150 raise RuntimeError("cannot work with un-aquired lock")
153 class SingleNotifyPipeCondition(_BaseCondition):
154 """Condition which can only be notified once.
156 This condition class uses pipes and poll, internally, to be able to wait for
157 notification with a timeout, without resorting to polling. It is almost
158 compatible with Python's threading.Condition, with the following differences:
159 - notifyAll can only be called once, and no wait can happen after that
160 - notify is not supported, only notifyAll
164 __slots__ = _BaseCondition.__slots__ + [
172 _waiter_class = _SingleNotifyPipeConditionWaiter
174 def __init__(self, lock):
175 """Constructor for SingleNotifyPipeCondition
178 _BaseCondition.__init__(self, lock)
180 self._notified = False
182 self._write_fd = None
185 def _check_unnotified(self):
186 """Throws an exception if already notified.
190 raise RuntimeError("cannot use already notified condition")
193 """Cleanup open file descriptors, if any.
196 if self._read_fd is not None:
197 os.close(self._read_fd)
200 if self._write_fd is not None:
201 os.close(self._write_fd)
202 self._write_fd = None
205 def wait(self, timeout=None):
206 """Wait for a notification.
208 @type timeout: float or None
209 @param timeout: Waiting timeout (can be None)
213 self._check_unnotified()
217 if self._poller is None:
218 (self._read_fd, self._write_fd) = os.pipe()
219 self._poller = select.poll()
220 self._poller.register(self._read_fd, select.POLLHUP)
222 wait_fn = self._waiter_class(self._poller, self._read_fd)
225 # Wait for notification
232 if self._nwaiters == 0:
236 """Close the writing side of the pipe to notify all waiters.
240 self._check_unnotified()
241 self._notified = True
242 if self._write_fd is not None:
243 os.close(self._write_fd)
244 self._write_fd = None
247 class PipeCondition(_BaseCondition):
248 """Group-only non-polling condition with counters.
250 This condition class uses pipes and poll, internally, to be able to wait for
251 notification with a timeout, without resorting to polling. It is almost
252 compatible with Python's threading.Condition, but only supports notifyAll and
253 non-recursive locks. As an additional features it's able to report whether
254 there are any waiting threads.
257 __slots__ = _BaseCondition.__slots__ + [
262 _single_condition_class = SingleNotifyPipeCondition
264 def __init__(self, lock):
265 """Initializes this class.
268 _BaseCondition.__init__(self, lock)
270 self._single_condition = self._single_condition_class(self._lock)
272 def wait(self, timeout=None):
273 """Wait for a notification.
275 @type timeout: float or None
276 @param timeout: Waiting timeout (can be None)
281 # Keep local reference to the pipe. It could be replaced by another thread
282 # notifying while we're waiting.
283 my_condition = self._single_condition
285 assert self._nwaiters >= 0
288 my_condition.wait(timeout)
290 assert self._nwaiters > 0
294 """Notify all currently waiting threads.
298 self._single_condition.notifyAll()
299 self._single_condition = self._single_condition_class(self._lock)
301 def has_waiting(self):
302 """Returns whether there are active waiters.
307 return bool(self._nwaiters)
310 class _CountingCondition(object):
311 """Wrapper for Python's built-in threading.Condition class.
313 This wrapper keeps a count of active waiters. We can't access the internal
314 "__waiters" attribute of threading.Condition because it's not thread-safe.
322 def __init__(self, lock):
323 """Initializes this class.
326 object.__init__(self)
327 self._cond = threading.Condition(lock=lock)
331 """Notifies the condition.
334 return self._cond.notifyAll()
336 def wait(self, timeout=None):
337 """Waits for the condition to be notified.
339 @type timeout: float or None
340 @param timeout: Waiting timeout (can be None)
343 assert self._nwaiters >= 0
347 return self._cond.wait(timeout=timeout)
351 def has_waiting(self):
352 """Returns whether there are active waiters.
355 return bool(self._nwaiters)
358 class SharedLock(object):
359 """Implements a shared lock.
361 Multiple threads can acquire the lock in a shared way, calling
362 acquire_shared(). In order to acquire the lock in an exclusive way threads
363 can call acquire_exclusive().
365 The lock prevents starvation but does not guarantee that threads will acquire
366 the shared lock in the order they queued for it, just that they will
380 __condition_class = PipeCondition
383 """Construct a new SharedLock.
386 object.__init__(self)
389 self.__lock = threading.Lock()
391 # Queue containing waiting acquires
394 # Active and inactive conditions for shared locks
395 self.__active_shr_c = self.__condition_class(self.__lock)
396 self.__inactive_shr_c = self.__condition_class(self.__lock)
398 # Current lock holders
402 # is this lock in the deleted state?
403 self.__deleted = False
405 def __check_deleted(self):
406 """Raises an exception if the lock has been deleted.
410 raise errors.LockError("Deleted lock")
412 def __is_sharer(self):
413 """Is the current thread sharing the lock at this time?
416 return threading.currentThread() in self.__shr
418 def __is_exclusive(self):
419 """Is the current thread holding the lock exclusively at this time?
422 return threading.currentThread() == self.__exc
424 def __is_owned(self, shared=-1):
425 """Is the current thread somehow owning the lock at this time?
427 This is a private version of the function, which presumes you're holding
432 return self.__is_sharer() or self.__is_exclusive()
434 return self.__is_sharer()
436 return self.__is_exclusive()
438 def _is_owned(self, shared=-1):
439 """Is the current thread somehow owning the lock at this time?
442 - < 0: check for any type of ownership (default)
443 - 0: check for exclusive ownership
444 - > 0: check for shared ownership
447 self.__lock.acquire()
449 return self.__is_owned(shared=shared)
451 self.__lock.release()
453 def _count_pending(self):
454 """Returns the number of pending acquires.
459 self.__lock.acquire()
461 return len(self.__pending)
463 self.__lock.release()
465 def __do_acquire(self, shared):
466 """Actually acquire the lock.
470 self.__shr.add(threading.currentThread())
472 self.__exc = threading.currentThread()
474 def __can_acquire(self, shared):
475 """Determine whether lock can be acquired.
479 return self.__exc is None
481 return len(self.__shr) == 0 and self.__exc is None
483 def __is_on_top(self, cond):
484 """Checks whether the passed condition is on top of the queue.
486 The caller must make sure the queue isn't empty.
489 return self.__pending[0] == cond
491 def __acquire_unlocked(self, shared, timeout):
492 """Acquire a shared lock.
494 @param shared: whether to acquire in shared mode; by default an
495 exclusive lock will be acquired
496 @param timeout: maximum waiting time before giving up
499 self.__check_deleted()
501 # We cannot acquire the lock if we already have it
502 assert not self.__is_owned(), "double acquire() on a non-recursive lock"
504 # Check whether someone else holds the lock or there are pending acquires.
505 if not self.__pending and self.__can_acquire(shared):
506 # Apparently not, can acquire lock directly.
507 self.__do_acquire(shared)
511 wait_condition = self.__active_shr_c
513 # Check if we're not yet in the queue
514 if wait_condition not in self.__pending:
515 self.__pending.append(wait_condition)
517 wait_condition = self.__condition_class(self.__lock)
518 # Always add to queue
519 self.__pending.append(wait_condition)
522 # Wait until we become the topmost acquire in the queue or the timeout
524 while not (self.__is_on_top(wait_condition) and
525 self.__can_acquire(shared)):
526 # Wait for notification
527 wait_condition.wait(timeout)
528 self.__check_deleted()
530 # A lot of code assumes blocking acquires always succeed. Loop
531 # internally for that case.
532 if timeout is not None:
535 if self.__is_on_top(wait_condition) and self.__can_acquire(shared):
536 self.__do_acquire(shared)
539 # Remove condition from queue if there are no more waiters
540 if not wait_condition.has_waiting() and not self.__deleted:
541 self.__pending.remove(wait_condition)
545 def acquire(self, shared=0, timeout=None, test_notify=None):
546 """Acquire a shared lock.
549 @param shared: whether to acquire in shared mode; by default an
550 exclusive lock will be acquired
552 @param timeout: maximum waiting time before giving up
553 @type test_notify: callable or None
554 @param test_notify: Special callback function for unittesting
557 self.__lock.acquire()
559 # We already got the lock, notify now
560 if __debug__ and callable(test_notify):
563 return self.__acquire_unlocked(shared, timeout)
565 self.__lock.release()
568 """Release a Shared Lock.
570 You must have acquired the lock, either in shared or in exclusive mode,
571 before calling this function.
574 self.__lock.acquire()
576 assert self.__is_exclusive() or self.__is_sharer(), \
577 "Cannot release non-owned lock"
579 # Autodetect release type
580 if self.__is_exclusive():
583 self.__shr.remove(threading.currentThread())
585 # Notify topmost condition in queue
587 first_condition = self.__pending[0]
588 first_condition.notifyAll()
590 if first_condition == self.__active_shr_c:
591 self.__active_shr_c = self.__inactive_shr_c
592 self.__inactive_shr_c = first_condition
595 self.__lock.release()
597 def delete(self, timeout=None):
598 """Delete a Shared Lock.
600 This operation will declare the lock for removal. First the lock will be
601 acquired in exclusive mode if you don't already own it, then the lock
602 will be put in a state where any future and pending acquire() fail.
605 @param timeout: maximum waiting time before giving up
608 self.__lock.acquire()
610 assert not self.__is_sharer(), "Cannot delete() a lock while sharing it"
612 self.__check_deleted()
614 # The caller is allowed to hold the lock exclusively already.
615 acquired = self.__is_exclusive()
618 acquired = self.__acquire_unlocked(0, timeout)
620 assert self.__is_exclusive() and not self.__is_sharer(), \
621 "Lock wasn't acquired in exclusive mode"
624 self.__deleted = True
627 # Notify all acquires. They'll throw an error.
628 while self.__pending:
629 self.__pending.pop().notifyAll()
633 self.__lock.release()
636 # Whenever we want to acquire a full LockSet we pass None as the value
637 # to acquire. Hide this behind this nicely named constant.
641 class _AcquireTimeout(Exception):
642 """Internal exception to abort an acquire on a timeout.
648 """Implements a set of locks.
650 This abstraction implements a set of shared locks for the same resource type,
651 distinguished by name. The user can lock a subset of the resources and the
652 LockSet will take care of acquiring the locks always in the same order, thus
655 All the locks needed in the same set must be acquired together, though.
658 def __init__(self, members=None):
659 """Constructs a new LockSet.
661 @param members: initial members of the set
664 # Used internally to guarantee coherency.
665 self.__lock = SharedLock()
667 # The lockdict indexes the relationship name -> lock
668 # The order-of-locking is implied by the alphabetical order of names
671 if members is not None:
673 self.__lockdict[name] = SharedLock()
675 # The owner dict contains the set of locks each thread owns. For
676 # performance each thread can access its own key without a global lock on
677 # this structure. It is paramount though that *no* other type of access is
678 # done to this structure (eg. no looping over its keys). *_owner helper
679 # function are defined to guarantee access is correct, but in general never
680 # do anything different than __owners[threading.currentThread()], or there
685 """Is the current thread a current level owner?"""
686 return threading.currentThread() in self.__owners
688 def _add_owned(self, name=None):
689 """Note the current thread owns the given lock"""
691 if not self._is_owned():
692 self.__owners[threading.currentThread()] = set()
695 self.__owners[threading.currentThread()].add(name)
697 self.__owners[threading.currentThread()] = set([name])
699 def _del_owned(self, name=None):
700 """Note the current thread owns the given lock"""
703 self.__owners[threading.currentThread()].remove(name)
705 # Only remove the key if we don't hold the set-lock as well
706 if (not self.__lock._is_owned() and
707 not self.__owners[threading.currentThread()]):
708 del self.__owners[threading.currentThread()]
710 def _list_owned(self):
711 """Get the set of resource names owned by the current thread"""
713 return self.__owners[threading.currentThread()].copy()
717 def _release_and_delete_owned(self):
718 """Release and delete all resources owned by the current thread"""
719 for lname in self._list_owned():
720 self.__lockdict[lname].release()
721 self._del_owned(name=lname)
724 """Return the current set of names.
726 Only call this function while holding __lock and don't iterate on the
727 result after releasing the lock.
730 return self.__lockdict.keys()
733 """Return a copy of the current set of elements.
735 Used only for debugging purposes.
738 # If we don't already own the set-level lock acquired
739 # we'll get it and note we need to release it later.
741 if not self.__lock._is_owned():
743 self.__lock.acquire(shared=1)
745 result = self.__names()
748 self.__lock.release()
751 def acquire(self, names, timeout=None, shared=0, test_notify=None):
752 """Acquire a set of resource locks.
754 @param names: the names of the locks which shall be acquired
755 (special lock names, or instance/node names)
756 @param shared: whether to acquire in shared mode; by default an
757 exclusive lock will be acquired
758 @type timeout: float or None
759 @param timeout: Maximum time to acquire all locks
760 @type test_notify: callable or None
761 @param test_notify: Special callback function for unittesting
763 @return: Set of all locks successfully acquired or None in case of timeout
765 @raise errors.LockError: when any lock we try to acquire has
766 been deleted before we succeed. In this case none of the
767 locks requested will be acquired.
770 assert timeout is None or timeout >= 0.0
772 # Check we don't already own locks at this level
773 assert not self._is_owned(), "Cannot acquire locks in the same set twice"
775 # We need to keep track of how long we spent waiting for a lock. The
776 # timeout passed to this function is over all lock acquires.
777 remaining_timeout = timeout
780 calc_remaining_timeout = lambda: None
783 calc_remaining_timeout = lambda: (start + timeout) - time.time()
785 want_all = names is None
788 # If no names are given acquire the whole set by not letting new names
789 # being added before we release, and getting the current list of names.
790 # Some of them may then be deleted later, but we'll cope with this.
792 # We'd like to acquire this lock in a shared way, as it's nice if
793 # everybody else can use the instances at the same time. If are acquiring
794 # them exclusively though they won't be able to do this anyway, though,
795 # so we'll get the list lock exclusively as well in order to be able to
796 # do add() on the set while owning it.
797 self.__lock.acquire(shared=shared, timeout=remaining_timeout)
799 # note we own the set-lock
801 names = self.__names()
803 # We shouldn't have problems adding the lock to the owners list, but
804 # if we did we'll try to release this lock and re-raise exception.
805 # Of course something is going to be really wrong, after this.
806 self.__lock.release()
809 # Re-calculate timeout
810 remaining_timeout = calc_remaining_timeout()
814 # Support passing in a single resource to acquire rather than many
815 if isinstance(names, basestring):
818 names = sorted(names)
821 # First we look the locks up on __lockdict. We have no way of being sure
822 # they will still be there after, but this makes it a lot faster should
823 # just one of them be the already wrong
824 for lname in utils.UniqueSequence(names):
826 lock = self.__lockdict[lname] # raises KeyError if lock is not there
827 acquire_list.append((lname, lock))
830 # We are acquiring all the set, it doesn't matter if this
831 # particular element is not there anymore.
834 raise errors.LockError("Non-existing lock in set (%s)" % lname)
836 # This will hold the locknames we effectively acquired.
839 # Now acquire_list contains a sorted list of resources and locks we
840 # want. In order to get them we loop on this (private) list and
841 # acquire() them. We gave no real guarantee they will still exist till
842 # this is done but .acquire() itself is safe and will alert us if the
844 for (lname, lock) in acquire_list:
845 if __debug__ and callable(test_notify):
846 test_notify_fn = lambda: test_notify(lname)
848 test_notify_fn = None
851 if timeout is not None and remaining_timeout < 0:
852 raise _AcquireTimeout()
854 # raises LockError if the lock was deleted
855 if not lock.acquire(shared=shared, timeout=remaining_timeout,
856 test_notify=test_notify_fn):
857 # Couldn't get lock or timeout occurred
859 # This shouldn't happen as SharedLock.acquire(timeout=None) is
861 raise errors.LockError("Failed to get lock %s" % lname)
863 raise _AcquireTimeout()
865 # Re-calculate timeout
866 remaining_timeout = calc_remaining_timeout()
868 # now the lock cannot be deleted, we have it!
869 self._add_owned(name=lname)
872 except _AcquireTimeout:
873 # Release all acquired locks
874 self._release_and_delete_owned()
877 except errors.LockError:
879 # We are acquiring all the set, it doesn't matter if this
880 # particular element is not there anymore.
883 self._release_and_delete_owned()
885 raise errors.LockError("Non-existing lock in set (%s)" % lname)
888 # We shouldn't have problems adding the lock to the owners list, but
889 # if we did we'll try to release this lock and re-raise exception.
890 # Of course something is going to be really wrong, after this.
896 # If something went wrong and we had the set-lock let's release it...
898 self.__lock.release()
901 except _AcquireTimeout:
909 def release(self, names=None):
910 """Release a set of resource locks, at the same level.
912 You must have acquired the locks, either in shared or in exclusive mode,
913 before releasing them.
915 @param names: the names of the locks which shall be released
916 (defaults to all the locks acquired at that level).
919 assert self._is_owned(), "release() on lock set while not owner"
921 # Support passing in a single resource to release rather than many
922 if isinstance(names, basestring):
926 names = self._list_owned()
929 assert self._list_owned().issuperset(names), (
930 "release() on unheld resources %s" %
931 names.difference(self._list_owned()))
933 # First of all let's release the "all elements" lock, if set.
934 # After this 'add' can work again
935 if self.__lock._is_owned():
936 self.__lock.release()
939 for lockname in names:
940 # If we are sure the lock doesn't leave __lockdict without being
941 # exclusively held we can do this...
942 self.__lockdict[lockname].release()
943 self._del_owned(name=lockname)
945 def add(self, names, acquired=0, shared=0):
946 """Add a new set of elements to the set
948 @param names: names of the new elements to add
949 @param acquired: pre-acquire the new resource?
950 @param shared: is the pre-acquisition shared?
953 # Check we don't already own locks at this level
954 assert not self._is_owned() or self.__lock._is_owned(shared=0), \
955 "Cannot add locks if the set is only partially owned, or shared"
957 # Support passing in a single resource to add rather than many
958 if isinstance(names, basestring):
961 # If we don't already own the set-level lock acquired in an exclusive way
962 # we'll get it and note we need to release it later.
964 if not self.__lock._is_owned():
966 self.__lock.acquire()
969 invalid_names = set(self.__names()).intersection(names)
971 # This must be an explicit raise, not an assert, because assert is
972 # turned off when using optimization, and this can happen because of
973 # concurrency even if the user doesn't want it.
974 raise errors.LockError("duplicate add() (%s)" % invalid_names)
976 for lockname in names:
980 lock.acquire(shared=shared)
981 # now the lock cannot be deleted, we have it!
983 self._add_owned(name=lockname)
985 # We shouldn't have problems adding the lock to the owners list,
986 # but if we did we'll try to release this lock and re-raise
987 # exception. Of course something is going to be really wrong,
988 # after this. On the other hand the lock hasn't been added to the
989 # __lockdict yet so no other threads should be pending on it. This
990 # release is just a safety measure.
994 self.__lockdict[lockname] = lock
997 # Only release __lock if we were not holding it previously.
999 self.__lock.release()
1003 def remove(self, names):
1004 """Remove elements from the lock set.
1006 You can either not hold anything in the lockset or already hold a superset
1007 of the elements you want to delete, exclusively.
1009 @param names: names of the resource to remove.
1011 @return: a list of locks which we removed; the list is always
1012 equal to the names list if we were holding all the locks
1016 # Support passing in a single resource to remove rather than many
1017 if isinstance(names, basestring):
1020 # If we own any subset of this lock it must be a superset of what we want
1021 # to delete. The ownership must also be exclusive, but that will be checked
1022 # by the lock itself.
1023 assert not self._is_owned() or self._list_owned().issuperset(names), (
1024 "remove() on acquired lockset while not owning all elements")
1029 # Calling delete() acquires the lock exclusively if we don't already own
1030 # it, and causes all pending and subsequent lock acquires to fail. It's
1031 # fine to call it out of order because delete() also implies release(),
1032 # and the assertion above guarantees that if we either already hold
1033 # everything we want to delete, or we hold none.
1035 self.__lockdict[lname].delete()
1036 removed.append(lname)
1037 except (KeyError, errors.LockError):
1038 # This cannot happen if we were already holding it, verify:
1039 assert not self._is_owned(), "remove failed while holding lockset"
1041 # If no LockError was raised we are the ones who deleted the lock.
1042 # This means we can safely remove it from lockdict, as any further or
1043 # pending delete() or acquire() will fail (and nobody can have the lock
1044 # since before our call to delete()).
1046 # This is done in an else clause because if the exception was thrown
1047 # it's the job of the one who actually deleted it.
1048 del self.__lockdict[lname]
1049 # And let's remove it from our private list if we owned it.
1050 if self._is_owned():
1051 self._del_owned(name=lname)
1056 # Locking levels, must be acquired in increasing order.
1057 # Current rules are:
1058 # - at level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
1059 # acquired before performing any operation, either in shared or in exclusive
1060 # mode. acquiring the BGL in exclusive mode is discouraged and should be
1062 # - at levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks.
1063 # If you need more than one node, or more than one instance, acquire them at
1069 LEVELS = [LEVEL_CLUSTER,
1073 # Lock levels which are modifiable
1074 LEVELS_MOD = [LEVEL_NODE, LEVEL_INSTANCE]
1077 LEVEL_CLUSTER: "cluster",
1078 LEVEL_INSTANCE: "instance",
1082 # Constant for the big ganeti lock
1086 class GanetiLockManager:
1087 """The Ganeti Locking Library
1089 The purpose of this small library is to manage locking for ganeti clusters
1090 in a central place, while at the same time doing dynamic checks against
1091 possible deadlocks. It will also make it easier to transition to a different
1092 lock type should we migrate away from python threads.
1097 def __init__(self, nodes=None, instances=None):
1098 """Constructs a new GanetiLockManager object.
1100 There should be only a GanetiLockManager object at any time, so this
1101 function raises an error if this is not the case.
1103 @param nodes: list of node names
1104 @param instances: list of instance names
1107 assert self.__class__._instance is None, \
1108 "double GanetiLockManager instance"
1110 self.__class__._instance = self
1112 # The keyring contains all the locks, at their level and in the correct
1115 LEVEL_CLUSTER: LockSet([BGL]),
1116 LEVEL_NODE: LockSet(nodes),
1117 LEVEL_INSTANCE: LockSet(instances),
1120 def _names(self, level):
1121 """List the lock names at the given level.
1123 This can be used for debugging/testing purposes.
1125 @param level: the level whose list of locks to get
1128 assert level in LEVELS, "Invalid locking level %s" % level
1129 return self.__keyring[level]._names()
1131 def _is_owned(self, level):
1132 """Check whether we are owning locks at the given level
1135 return self.__keyring[level]._is_owned()
1137 is_owned = _is_owned
1139 def _list_owned(self, level):
1140 """Get the set of owned locks at the given level
1143 return self.__keyring[level]._list_owned()
1145 def _upper_owned(self, level):
1146 """Check that we don't own any lock at a level greater than the given one.
1149 # This way of checking only works if LEVELS[i] = i, which we check for in
1151 return utils.any((self._is_owned(l) for l in LEVELS[level + 1:]))
1153 def _BGL_owned(self):
1154 """Check if the current thread owns the BGL.
1156 Both an exclusive or a shared acquisition work.
1159 return BGL in self.__keyring[LEVEL_CLUSTER]._list_owned()
1161 def _contains_BGL(self, level, names):
1162 """Check if the level contains the BGL.
1164 Check if acting on the given level and set of names will change
1165 the status of the Big Ganeti Lock.
1168 return level == LEVEL_CLUSTER and (names is None or BGL in names)
1170 def acquire(self, level, names, timeout=None, shared=0):
1171 """Acquire a set of resource locks, at the same level.
1173 @param level: the level at which the locks shall be acquired;
1174 it must be a member of LEVELS.
1175 @param names: the names of the locks which shall be acquired
1176 (special lock names, or instance/node names)
1177 @param shared: whether to acquire in shared mode; by default
1178 an exclusive lock will be acquired
1179 @type timeout: float
1180 @param timeout: Maximum time to acquire all locks
1183 assert level in LEVELS, "Invalid locking level %s" % level
1185 # Check that we are either acquiring the Big Ganeti Lock or we already own
1186 # it. Some "legacy" opcodes need to be sure they are run non-concurrently
1187 # so even if we've migrated we need to at least share the BGL to be
1188 # compatible with them. Of course if we own the BGL exclusively there's no
1189 # point in acquiring any other lock, unless perhaps we are half way through
1190 # the migration of the current opcode.
1191 assert (self._contains_BGL(level, names) or self._BGL_owned()), (
1192 "You must own the Big Ganeti Lock before acquiring any other")
1194 # Check we don't own locks at the same or upper levels.
1195 assert not self._upper_owned(level), ("Cannot acquire locks at a level"
1196 " while owning some at a greater one")
1198 # Acquire the locks in the set.
1199 return self.__keyring[level].acquire(names, shared=shared, timeout=timeout)
1201 def release(self, level, names=None):
1202 """Release a set of resource locks, at the same level.
1204 You must have acquired the locks, either in shared or in exclusive
1205 mode, before releasing them.
1207 @param level: the level at which the locks shall be released;
1208 it must be a member of LEVELS
1209 @param names: the names of the locks which shall be released
1210 (defaults to all the locks acquired at that level)
1213 assert level in LEVELS, "Invalid locking level %s" % level
1214 assert (not self._contains_BGL(level, names) or
1215 not self._upper_owned(LEVEL_CLUSTER)), (
1216 "Cannot release the Big Ganeti Lock while holding something"
1219 # Release will complain if we don't own the locks already
1220 return self.__keyring[level].release(names)
1222 def add(self, level, names, acquired=0, shared=0):
1223 """Add locks at the specified level.
1225 @param level: the level at which the locks shall be added;
1226 it must be a member of LEVELS_MOD.
1227 @param names: names of the locks to acquire
1228 @param acquired: whether to acquire the newly added locks
1229 @param shared: whether the acquisition will be shared
1232 assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
1233 assert self._BGL_owned(), ("You must own the BGL before performing other"
1235 assert not self._upper_owned(level), ("Cannot add locks at a level"
1236 " while owning some at a greater one")
1237 return self.__keyring[level].add(names, acquired=acquired, shared=shared)
1239 def remove(self, level, names):
1240 """Remove locks from the specified level.
1242 You must either already own the locks you are trying to remove
1243 exclusively or not own any lock at an upper level.
1245 @param level: the level at which the locks shall be removed;
1246 it must be a member of LEVELS_MOD
1247 @param names: the names of the locks which shall be removed
1248 (special lock names, or instance/node names)
1251 assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
1252 assert self._BGL_owned(), ("You must own the BGL before performing other"
1254 # Check we either own the level or don't own anything from here
1255 # up. LockSet.remove() will check the case in which we don't own
1256 # all the needed resources, or we have a shared ownership.
1257 assert self._is_owned(level) or not self._upper_owned(level), (
1258 "Cannot remove locks at a level while not owning it or"
1259 " owning some at a greater one")
1260 return self.__keyring[level].remove(names)