4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 """Module implementing the Ganeti locking code."""
23 # pylint: disable=W0212
25 # W0212 since e.g. LockSet methods use (a lot) the internals of
38 from ganeti import errors
39 from ganeti import utils
40 from ganeti import compat
41 from ganeti import query
44 _EXCLUSIVE_TEXT = "exclusive"
45 _SHARED_TEXT = "shared"
46 _DELETED_TEXT = "deleted"
50 #: Minimum timeout required to consider scheduling a pending acquisition
52 _LOCK_ACQUIRE_MIN_TIMEOUT = (1.0 / 1000)
54 # Internal lock acquisition modes for L{LockSet}
57 _LS_ACQUIRE_OPPORTUNISTIC) = range(1, 4)
59 _LS_ACQUIRE_MODES = compat.UniqueFrozenset([
62 _LS_ACQUIRE_OPPORTUNISTIC,
66 def ssynchronized(mylock, shared=0):
67 """Shared Synchronization decorator.
69 Calls the function holding the given lock, either in exclusive or shared
70 mode. It requires the passed lock to be a SharedLock (or support its
73 @type mylock: lockable object or string
74 @param mylock: lock to acquire or class member name of the lock to acquire
78 def sync_function(*args, **kwargs):
79 if isinstance(mylock, basestring):
80 assert args, "cannot ssynchronize on non-class method: self not found"
82 lock = getattr(args[0], mylock)
85 lock.acquire(shared=shared)
87 return fn(*args, **kwargs)
94 class _SingleNotifyPipeConditionWaiter(object):
95 """Helper class for SingleNotifyPipeCondition
103 def __init__(self, poller, fd):
104 """Constructor for _SingleNotifyPipeConditionWaiter
106 @type poller: select.poll
107 @param poller: Poller object
109 @param fd: File descriptor to wait for
112 object.__init__(self)
113 self._poller = poller
116 def __call__(self, timeout):
117 """Wait for something to happen on the pipe.
119 @type timeout: float or None
120 @param timeout: Timeout for waiting (can be None)
123 running_timeout = utils.RunningTimeout(timeout, True)
126 remaining_time = running_timeout.Remaining()
128 if remaining_time is not None:
129 if remaining_time < 0.0:
132 # Our calculation uses seconds, poll() wants milliseconds
133 remaining_time *= 1000
136 result = self._poller.poll(remaining_time)
137 except EnvironmentError, err:
138 if err.errno != errno.EINTR:
142 # Check whether we were notified
143 if result and result[0][0] == self._fd:
147 class _BaseCondition(object):
148 """Base class containing common code for conditions.
150 Some of this code is taken from python's threading module.
162 def __init__(self, lock):
163 """Constructor for _BaseCondition.
165 @type lock: threading.Lock
166 @param lock: condition base lock
169 object.__init__(self)
172 self._release_save = lock._release_save
173 except AttributeError:
174 self._release_save = self._base_release_save
176 self._acquire_restore = lock._acquire_restore
177 except AttributeError:
178 self._acquire_restore = self._base_acquire_restore
180 self._is_owned = lock.is_owned
181 except AttributeError:
182 self._is_owned = self._base_is_owned
186 # Export the lock's acquire() and release() methods
187 self.acquire = lock.acquire
188 self.release = lock.release
190 def _base_is_owned(self):
191 """Check whether lock is owned by current thread.
194 if self._lock.acquire(0):
199 def _base_release_save(self):
202 def _base_acquire_restore(self, _):
205 def _check_owned(self):
206 """Raise an exception if the current thread doesn't own the lock.
209 if not self._is_owned():
210 raise RuntimeError("cannot work with un-aquired lock")
213 class SingleNotifyPipeCondition(_BaseCondition):
214 """Condition which can only be notified once.
216 This condition class uses pipes and poll, internally, to be able to wait for
217 notification with a timeout, without resorting to polling. It is almost
218 compatible with Python's threading.Condition, with the following differences:
219 - notifyAll can only be called once, and no wait can happen after that
220 - notify is not supported, only notifyAll
232 _waiter_class = _SingleNotifyPipeConditionWaiter
234 def __init__(self, lock):
235 """Constructor for SingleNotifyPipeCondition
238 _BaseCondition.__init__(self, lock)
240 self._notified = False
242 self._write_fd = None
245 def _check_unnotified(self):
246 """Throws an exception if already notified.
250 raise RuntimeError("cannot use already notified condition")
253 """Cleanup open file descriptors, if any.
256 if self._read_fd is not None:
257 os.close(self._read_fd)
260 if self._write_fd is not None:
261 os.close(self._write_fd)
262 self._write_fd = None
265 def wait(self, timeout):
266 """Wait for a notification.
268 @type timeout: float or None
269 @param timeout: Waiting timeout (can be None)
273 self._check_unnotified()
277 if self._poller is None:
278 (self._read_fd, self._write_fd) = os.pipe()
279 self._poller = select.poll()
280 self._poller.register(self._read_fd, select.POLLHUP)
282 wait_fn = self._waiter_class(self._poller, self._read_fd)
283 state = self._release_save()
285 # Wait for notification
289 self._acquire_restore(state)
292 if self._nwaiters == 0:
295 def notifyAll(self): # pylint: disable=C0103
296 """Close the writing side of the pipe to notify all waiters.
300 self._check_unnotified()
301 self._notified = True
302 if self._write_fd is not None:
303 os.close(self._write_fd)
304 self._write_fd = None
307 class PipeCondition(_BaseCondition):
308 """Group-only non-polling condition with counters.
310 This condition class uses pipes and poll, internally, to be able to wait for
311 notification with a timeout, without resorting to polling. It is almost
312 compatible with Python's threading.Condition, but only supports notifyAll and
313 non-recursive locks. As an additional features it's able to report whether
314 there are any waiting threads.
322 _single_condition_class = SingleNotifyPipeCondition
324 def __init__(self, lock):
325 """Initializes this class.
328 _BaseCondition.__init__(self, lock)
329 self._waiters = set()
330 self._single_condition = self._single_condition_class(self._lock)
332 def wait(self, timeout):
333 """Wait for a notification.
335 @type timeout: float or None
336 @param timeout: Waiting timeout (can be None)
341 # Keep local reference to the pipe. It could be replaced by another thread
342 # notifying while we're waiting.
343 cond = self._single_condition
345 self._waiters.add(threading.currentThread())
350 self._waiters.remove(threading.currentThread())
352 def notifyAll(self): # pylint: disable=C0103
353 """Notify all currently waiting threads.
357 self._single_condition.notifyAll()
358 self._single_condition = self._single_condition_class(self._lock)
360 def get_waiting(self):
361 """Returns a list of all waiting threads.
368 def has_waiting(self):
369 """Returns whether there are active waiters.
374 return bool(self._waiters)
377 return ("<%s.%s waiters=%s at %#x>" %
378 (self.__class__.__module__, self.__class__.__name__,
379 self._waiters, id(self)))
382 class _PipeConditionWithMode(PipeCondition):
387 def __init__(self, lock, shared):
388 """Initializes this class.
392 PipeCondition.__init__(self, lock)
395 class SharedLock(object):
396 """Implements a shared lock.
398 Multiple threads can acquire the lock in a shared way by calling
399 C{acquire(shared=1)}. In order to acquire the lock in an exclusive way
400 threads can call C{acquire(shared=0)}.
402 Notes on data structures: C{__pending} contains a priority queue (heapq) of
403 all pending acquires: C{[(priority1: prioqueue1), (priority2: prioqueue2),
404 ...]}. Each per-priority queue contains a normal in-order list of conditions
405 to be notified when the lock can be acquired. Shared locks are grouped
406 together by priority and the condition for them is stored in
407 C{__pending_shared} if it already exists. C{__pending_by_prio} keeps
408 references for the per-priority queues indexed by priority for faster access.
411 @ivar name: the name of the lock
427 __condition_class = _PipeConditionWithMode
429 def __init__(self, name, monitor=None, _time_fn=time.time):
430 """Construct a new SharedLock.
432 @param name: the name of the lock
433 @type monitor: L{LockMonitor}
434 @param monitor: Lock monitor with which to register
437 object.__init__(self)
441 # Used for unittesting
442 self.__time_fn = _time_fn
445 self.__lock = threading.Lock()
447 # Queue containing waiting acquires
449 self.__pending_by_prio = {}
450 self.__pending_shared = {}
452 # Current lock holders
456 # is this lock in the deleted state?
457 self.__deleted = False
459 # Register with lock monitor
461 logging.debug("Adding lock %s to monitor", name)
462 monitor.RegisterLock(self)
465 return ("<%s.%s name=%s at %#x>" %
466 (self.__class__.__module__, self.__class__.__name__,
467 self.name, id(self)))
469 def GetLockInfo(self, requested):
470 """Retrieves information for querying locks.
473 @param requested: Requested information, see C{query.LQ_*}
476 self.__lock.acquire()
478 # Note: to avoid unintentional race conditions, no references to
479 # modifiable objects should be returned unless they were created in this
484 if query.LQ_MODE in requested:
487 assert not (self.__exc or self.__shr)
489 mode = _EXCLUSIVE_TEXT
493 # Current owner(s) are wanted
494 if query.LQ_OWNER in requested:
501 assert not self.__deleted
502 owner_names = [i.getName() for i in owner]
504 # Pending acquires are wanted
505 if query.LQ_PENDING in requested:
508 # Sorting instead of copying and using heaq functions for simplicity
509 for (_, prioqueue) in sorted(self.__pending):
510 for cond in prioqueue:
512 pendmode = _SHARED_TEXT
514 pendmode = _EXCLUSIVE_TEXT
516 # List of names will be sorted in L{query._GetLockPending}
517 pending.append((pendmode, [i.getName()
518 for i in cond.get_waiting()]))
522 return [(self.name, mode, owner_names, pending)]
524 self.__lock.release()
526 def __check_deleted(self):
527 """Raises an exception if the lock has been deleted.
531 raise errors.LockError("Deleted lock %s" % self.name)
533 def __is_sharer(self):
534 """Is the current thread sharing the lock at this time?
537 return threading.currentThread() in self.__shr
539 def __is_exclusive(self):
540 """Is the current thread holding the lock exclusively at this time?
543 return threading.currentThread() == self.__exc
545 def __is_owned(self, shared=-1):
546 """Is the current thread somehow owning the lock at this time?
548 This is a private version of the function, which presumes you're holding
553 return self.__is_sharer() or self.__is_exclusive()
555 return self.__is_sharer()
557 return self.__is_exclusive()
559 def is_owned(self, shared=-1):
560 """Is the current thread somehow owning the lock at this time?
563 - < 0: check for any type of ownership (default)
564 - 0: check for exclusive ownership
565 - > 0: check for shared ownership
568 self.__lock.acquire()
570 return self.__is_owned(shared=shared)
572 self.__lock.release()
574 #: Necessary to remain compatible with threading.Condition, which tries to
575 #: retrieve a locks' "_is_owned" attribute
578 def _count_pending(self):
579 """Returns the number of pending acquires.
584 self.__lock.acquire()
586 return sum(len(prioqueue) for (_, prioqueue) in self.__pending)
588 self.__lock.release()
590 def _check_empty(self):
591 """Checks whether there are any pending acquires.
596 self.__lock.acquire()
598 # Order is important: __find_first_pending_queue modifies __pending
599 (_, prioqueue) = self.__find_first_pending_queue()
601 return not (prioqueue or
603 self.__pending_by_prio or
604 self.__pending_shared)
606 self.__lock.release()
608 def __do_acquire(self, shared):
609 """Actually acquire the lock.
613 self.__shr.add(threading.currentThread())
615 self.__exc = threading.currentThread()
617 def __can_acquire(self, shared):
618 """Determine whether lock can be acquired.
622 return self.__exc is None
624 return len(self.__shr) == 0 and self.__exc is None
626 def __find_first_pending_queue(self):
627 """Tries to find the topmost queued entry with pending acquires.
629 Removes empty entries while going through the list.
632 while self.__pending:
633 (priority, prioqueue) = self.__pending[0]
636 return (priority, prioqueue)
639 heapq.heappop(self.__pending)
640 del self.__pending_by_prio[priority]
641 assert priority not in self.__pending_shared
645 def __is_on_top(self, cond):
646 """Checks whether the passed condition is on top of the queue.
648 The caller must make sure the queue isn't empty.
651 (_, prioqueue) = self.__find_first_pending_queue()
653 return cond == prioqueue[0]
655 def __acquire_unlocked(self, shared, timeout, priority):
656 """Acquire a shared lock.
658 @param shared: whether to acquire in shared mode; by default an
659 exclusive lock will be acquired
660 @param timeout: maximum waiting time before giving up
661 @type priority: integer
662 @param priority: Priority for acquiring lock
665 self.__check_deleted()
667 # We cannot acquire the lock if we already have it
668 assert not self.__is_owned(), ("double acquire() on a non-recursive lock"
671 # Remove empty entries from queue
672 self.__find_first_pending_queue()
674 # Check whether someone else holds the lock or there are pending acquires.
675 if not self.__pending and self.__can_acquire(shared):
676 # Apparently not, can acquire lock directly.
677 self.__do_acquire(shared)
680 # The lock couldn't be acquired right away, so if a timeout is given and is
681 # considered too short, return right away as scheduling a pending
682 # acquisition is quite expensive
683 if timeout is not None and timeout < _LOCK_ACQUIRE_MIN_TIMEOUT:
686 prioqueue = self.__pending_by_prio.get(priority, None)
689 # Try to re-use condition for shared acquire
690 wait_condition = self.__pending_shared.get(priority, None)
691 assert (wait_condition is None or
692 (wait_condition.shared and wait_condition in prioqueue))
694 wait_condition = None
696 if wait_condition is None:
697 if prioqueue is None:
698 assert priority not in self.__pending_by_prio
701 heapq.heappush(self.__pending, (priority, prioqueue))
702 self.__pending_by_prio[priority] = prioqueue
704 wait_condition = self.__condition_class(self.__lock, shared)
705 prioqueue.append(wait_condition)
708 # Keep reference for further shared acquires on same priority. This is
709 # better than trying to find it in the list of pending acquires.
710 assert priority not in self.__pending_shared
711 self.__pending_shared[priority] = wait_condition
713 wait_start = self.__time_fn()
717 # Wait until we become the topmost acquire in the queue or the timeout
720 if self.__is_on_top(wait_condition) and self.__can_acquire(shared):
721 self.__do_acquire(shared)
725 # A lot of code assumes blocking acquires always succeed, therefore we
726 # can never return False for a blocking acquire
727 if (timeout is not None and
728 utils.TimeoutExpired(wait_start, timeout, _time_fn=self.__time_fn)):
731 # Wait for notification
732 wait_condition.wait(timeout)
733 self.__check_deleted()
735 # Remove condition from queue if there are no more waiters
736 if not wait_condition.has_waiting():
737 prioqueue.remove(wait_condition)
738 if wait_condition.shared:
739 # Remove from list of shared acquires if it wasn't while releasing
740 # (e.g. on lock deletion)
741 self.__pending_shared.pop(priority, None)
745 def acquire(self, shared=0, timeout=None, priority=None,
747 """Acquire a shared lock.
749 @type shared: integer (0/1) used as a boolean
750 @param shared: whether to acquire in shared mode; by default an
751 exclusive lock will be acquired
753 @param timeout: maximum waiting time before giving up
754 @type priority: integer
755 @param priority: Priority for acquiring lock
756 @type test_notify: callable or None
757 @param test_notify: Special callback function for unittesting
761 priority = _DEFAULT_PRIORITY
763 self.__lock.acquire()
765 # We already got the lock, notify now
766 if __debug__ and callable(test_notify):
769 return self.__acquire_unlocked(shared, timeout, priority)
771 self.__lock.release()
774 """Changes the lock mode from exclusive to shared.
776 Pending acquires in shared mode on the same priority will go ahead.
779 self.__lock.acquire()
781 assert self.__is_owned(), "Lock must be owned"
783 if self.__is_exclusive():
784 # Do nothing if the lock is already acquired in shared mode
788 # Important: pending shared acquires should only jump ahead if there
789 # was a transition from exclusive to shared, otherwise an owner of a
790 # shared lock can keep calling this function to push incoming shared
792 (priority, prioqueue) = self.__find_first_pending_queue()
794 # Is there a pending shared acquire on this priority?
795 cond = self.__pending_shared.pop(priority, None)
798 assert cond in prioqueue
800 # Ensure shared acquire is on top of queue
801 if len(prioqueue) > 1:
802 prioqueue.remove(cond)
803 prioqueue.insert(0, cond)
808 assert not self.__is_exclusive()
809 assert self.__is_sharer()
813 self.__lock.release()
816 """Release a Shared Lock.
818 You must have acquired the lock, either in shared or in exclusive mode,
819 before calling this function.
822 self.__lock.acquire()
824 assert self.__is_exclusive() or self.__is_sharer(), \
825 "Cannot release non-owned lock"
827 # Autodetect release type
828 if self.__is_exclusive():
832 self.__shr.remove(threading.currentThread())
833 notify = not self.__shr
835 # Notify topmost condition in queue if there are no owners left (for
838 self.__notify_topmost()
840 self.__lock.release()
842 def __notify_topmost(self):
843 """Notifies topmost condition in queue of pending acquires.
846 (priority, prioqueue) = self.__find_first_pending_queue()
851 # Prevent further shared acquires from sneaking in while waiters are
853 self.__pending_shared.pop(priority, None)
855 def _notify_topmost(self):
856 """Exported version of L{__notify_topmost}.
859 self.__lock.acquire()
861 return self.__notify_topmost()
863 self.__lock.release()
865 def delete(self, timeout=None, priority=None):
866 """Delete a Shared Lock.
868 This operation will declare the lock for removal. First the lock will be
869 acquired in exclusive mode if you don't already own it, then the lock
870 will be put in a state where any future and pending acquire() fail.
873 @param timeout: maximum waiting time before giving up
874 @type priority: integer
875 @param priority: Priority for acquiring lock
879 priority = _DEFAULT_PRIORITY
881 self.__lock.acquire()
883 assert not self.__is_sharer(), "Cannot delete() a lock while sharing it"
885 self.__check_deleted()
887 # The caller is allowed to hold the lock exclusively already.
888 acquired = self.__is_exclusive()
891 acquired = self.__acquire_unlocked(0, timeout, priority)
894 assert self.__is_exclusive() and not self.__is_sharer(), \
895 "Lock wasn't acquired in exclusive mode"
897 self.__deleted = True
900 assert not (self.__exc or self.__shr), "Found owner during deletion"
902 # Notify all acquires. They'll throw an error.
903 for (_, prioqueue) in self.__pending:
904 for cond in prioqueue:
907 assert self.__deleted
911 self.__lock.release()
913 def _release_save(self):
914 shared = self.__is_sharer()
918 def _acquire_restore(self, shared):
919 self.acquire(shared=shared)
922 # Whenever we want to acquire a full LockSet we pass None as the value
923 # to acquire. Hide this behind this nicely named constant.
928 """Returns the number zero.
934 def _GetLsAcquireModeAndTimeouts(want_all, timeout, opportunistic):
935 """Determines modes and timeouts for L{LockSet.acquire}.
937 @type want_all: boolean
938 @param want_all: Whether all locks in set should be acquired
939 @param timeout: Timeout in seconds or C{None}
940 @param opportunistic: Whther locks should be acquired opportunistically
942 @return: Tuple containing mode to be passed to L{LockSet.__acquire_inner}
943 (one of L{_LS_ACQUIRE_MODES}), a function to calculate timeout for
944 acquiring the lockset-internal lock (might be C{None}) and a function to
945 calculate the timeout for acquiring individual locks
948 # Short circuit when no running timeout is needed
949 if opportunistic and not want_all:
950 assert timeout is None, "Got timeout for an opportunistic acquisition"
951 return (_LS_ACQUIRE_OPPORTUNISTIC, None, _TimeoutZero)
953 # We need to keep track of how long we spent waiting for a lock. The
954 # timeout passed to this function is over all lock acquisitions.
955 running_timeout = utils.RunningTimeout(timeout, False)
958 mode = _LS_ACQUIRE_ALL
959 ls_timeout_fn = running_timeout.Remaining
961 mode = _LS_ACQUIRE_EXACT
965 mode = _LS_ACQUIRE_OPPORTUNISTIC
966 timeout_fn = _TimeoutZero
968 timeout_fn = running_timeout.Remaining
970 return (mode, ls_timeout_fn, timeout_fn)
973 class _AcquireTimeout(Exception):
974 """Internal exception to abort an acquire on a timeout.
980 """Implements a set of locks.
982 This abstraction implements a set of shared locks for the same resource type,
983 distinguished by name. The user can lock a subset of the resources and the
984 LockSet will take care of acquiring the locks always in the same order, thus
987 All the locks needed in the same set must be acquired together, though.
990 @ivar name: the name of the lockset
993 def __init__(self, members, name, monitor=None):
994 """Constructs a new LockSet.
996 @type members: list of strings
997 @param members: initial members of the set
998 @type monitor: L{LockMonitor}
999 @param monitor: Lock monitor with which to register member locks
1002 assert members is not None, "members parameter is not a list"
1006 self.__monitor = monitor
1008 # Used internally to guarantee coherency
1009 self.__lock = SharedLock(self._GetLockName("[lockset]"), monitor=monitor)
1011 # The lockdict indexes the relationship name -> lock
1012 # The order-of-locking is implied by the alphabetical order of names
1013 self.__lockdict = {}
1015 for mname in members:
1016 self.__lockdict[mname] = SharedLock(self._GetLockName(mname),
1019 # The owner dict contains the set of locks each thread owns. For
1020 # performance each thread can access its own key without a global lock on
1021 # this structure. It is paramount though that *no* other type of access is
1022 # done to this structure (eg. no looping over its keys). *_owner helper
1023 # function are defined to guarantee access is correct, but in general never
1024 # do anything different than __owners[threading.currentThread()], or there
1028 def _GetLockName(self, mname):
1029 """Returns the name for a member lock.
1032 return "%s/%s" % (self.name, mname)
1034 def _get_lock(self):
1035 """Returns the lockset-internal lock.
1040 def _get_lockdict(self):
1041 """Returns the lockset-internal lock dictionary.
1043 Accessing this structure is only safe in single-thread usage or when the
1044 lockset-internal lock is held.
1047 return self.__lockdict
1050 """Is the current thread a current level owner?
1052 @note: Use L{check_owned} to check if a specific lock is held
1055 return threading.currentThread() in self.__owners
1057 def check_owned(self, names, shared=-1):
1058 """Check if locks are owned in a specific mode.
1060 @type names: sequence or string
1061 @param names: Lock names (or a single lock name)
1062 @param shared: See L{SharedLock.is_owned}
1064 @note: Use L{is_owned} to check if the current thread holds I{any} lock and
1065 L{list_owned} to get the names of all owned locks
1068 if isinstance(names, basestring):
1071 # Avoid check if no locks are owned anyway
1072 if names and self.is_owned():
1075 # Gather references to all locks (in case they're deleted in the meantime)
1078 lock = self.__lockdict[lname]
1080 raise errors.LockError("Non-existing lock '%s' in set '%s' (it may"
1081 " have been removed)" % (lname, self.name))
1083 candidates.append(lock)
1085 return compat.all(lock.is_owned(shared=shared) for lock in candidates)
1089 def owning_all(self):
1090 """Checks whether current thread owns internal lock.
1092 Holding the internal lock is equivalent with holding all locks in the set
1093 (the opposite does not necessarily hold as it can not be easily
1094 determined). L{add} and L{remove} require the internal lock.
1099 return self.__lock.is_owned()
1101 def _add_owned(self, name=None):
1102 """Note the current thread owns the given lock"""
1104 if not self.is_owned():
1105 self.__owners[threading.currentThread()] = set()
1108 self.__owners[threading.currentThread()].add(name)
1110 self.__owners[threading.currentThread()] = set([name])
1112 def _del_owned(self, name=None):
1113 """Note the current thread owns the given lock"""
1115 assert not (name is None and self.__lock.is_owned()), \
1116 "Cannot hold internal lock when deleting owner status"
1118 if name is not None:
1119 self.__owners[threading.currentThread()].remove(name)
1121 # Only remove the key if we don't hold the set-lock as well
1122 if not (self.__lock.is_owned() or
1123 self.__owners[threading.currentThread()]):
1124 del self.__owners[threading.currentThread()]
1126 def list_owned(self):
1127 """Get the set of resource names owned by the current thread"""
1129 return self.__owners[threading.currentThread()].copy()
1133 def _release_and_delete_owned(self):
1134 """Release and delete all resources owned by the current thread"""
1135 for lname in self.list_owned():
1136 lock = self.__lockdict[lname]
1139 self._del_owned(name=lname)
1142 """Return the current set of names.
1144 Only call this function while holding __lock and don't iterate on the
1145 result after releasing the lock.
1148 return self.__lockdict.keys()
1151 """Return a copy of the current set of elements.
1153 Used only for debugging purposes.
1156 # If we don't already own the set-level lock acquired
1157 # we'll get it and note we need to release it later.
1158 release_lock = False
1159 if not self.__lock.is_owned():
1161 self.__lock.acquire(shared=1)
1163 result = self.__names()
1166 self.__lock.release()
1169 def acquire(self, names, timeout=None, shared=0, priority=None,
1170 opportunistic=False, test_notify=None):
1171 """Acquire a set of resource locks.
1173 @note: When acquiring locks opportunistically, any number of locks might
1174 actually be acquired, even zero.
1176 @type names: list of strings (or string)
1177 @param names: the names of the locks which shall be acquired
1178 (special lock names, or instance/node names)
1179 @type shared: integer (0/1) used as a boolean
1180 @param shared: whether to acquire in shared mode; by default an
1181 exclusive lock will be acquired
1182 @type timeout: float or None
1183 @param timeout: Maximum time to acquire all locks; for opportunistic
1184 acquisitions, a timeout can only be given when C{names} is C{None}, in
1185 which case it is exclusively used for acquiring the L{LockSet}-internal
1186 lock; opportunistic acquisitions don't use a timeout for acquiring
1188 @type priority: integer
1189 @param priority: Priority for acquiring locks
1190 @type opportunistic: boolean
1191 @param opportunistic: Acquire locks opportunistically; use the return value
1192 to determine which locks were actually acquired
1193 @type test_notify: callable or None
1194 @param test_notify: Special callback function for unittesting
1196 @return: Set of all locks successfully acquired or None in case of timeout
1198 @raise errors.LockError: when any lock we try to acquire has
1199 been deleted before we succeed. In this case none of the
1200 locks requested will be acquired.
1203 assert timeout is None or timeout >= 0.0
1205 # Check we don't already own locks at this level
1206 assert not self.is_owned(), ("Cannot acquire locks in the same set twice"
1207 " (lockset %s)" % self.name)
1209 if priority is None:
1210 priority = _DEFAULT_PRIORITY
1213 if names is not None:
1214 assert timeout is None or not opportunistic, \
1215 ("Opportunistic acquisitions can only use a timeout if no"
1216 " names are given; see docstring for details")
1218 # Support passing in a single resource to acquire rather than many
1219 if isinstance(names, basestring):
1222 (mode, _, timeout_fn) = \
1223 _GetLsAcquireModeAndTimeouts(False, timeout, opportunistic)
1225 return self.__acquire_inner(names, mode, shared, priority,
1226 timeout_fn, test_notify)
1229 (mode, ls_timeout_fn, timeout_fn) = \
1230 _GetLsAcquireModeAndTimeouts(True, timeout, opportunistic)
1232 # If no names are given acquire the whole set by not letting new names
1233 # being added before we release, and getting the current list of names.
1234 # Some of them may then be deleted later, but we'll cope with this.
1236 # We'd like to acquire this lock in a shared way, as it's nice if
1237 # everybody else can use the instances at the same time. If we are
1238 # acquiring them exclusively though they won't be able to do this
1239 # anyway, though, so we'll get the list lock exclusively as well in
1240 # order to be able to do add() on the set while owning it.
1241 if not self.__lock.acquire(shared=shared, priority=priority,
1242 timeout=ls_timeout_fn()):
1243 raise _AcquireTimeout()
1246 # note we own the set-lock
1249 return self.__acquire_inner(self.__names(), mode, shared,
1250 priority, timeout_fn, test_notify)
1252 # We shouldn't have problems adding the lock to the owners list, but
1253 # if we did we'll try to release this lock and re-raise exception.
1254 # Of course something is going to be really wrong, after this.
1255 self.__lock.release()
1259 except _AcquireTimeout:
1262 def __acquire_inner(self, names, mode, shared, priority,
1263 timeout_fn, test_notify):
1264 """Inner logic for acquiring a number of locks.
1268 - C{_LS_ACQUIRE_ALL}: C{names} contains names of all locks in set, but
1269 deleted locks can be ignored as the whole set is being acquired with
1270 its internal lock held
1271 - C{_LS_ACQUIRE_EXACT}: The names listed in C{names} must be acquired;
1272 timeouts and deleted locks are fatal
1273 - C{_LS_ACQUIRE_OPPORTUNISTIC}: C{names} lists names of locks (potentially
1274 all within the set) which should be acquired opportunistically, that is
1275 failures are ignored
1277 @param names: Names of the locks to be acquired
1278 @param mode: Lock acquisition mode (one of L{_LS_ACQUIRE_MODES})
1279 @param shared: Whether to acquire in shared mode
1280 @param timeout_fn: Function returning remaining timeout (C{None} for
1281 opportunistic acquisitions)
1282 @param priority: Priority for acquiring locks
1283 @param test_notify: Special callback function for unittesting
1286 assert mode in _LS_ACQUIRE_MODES
1290 # First we look the locks up on __lockdict. We have no way of being sure
1291 # they will still be there after, but this makes it a lot faster should
1292 # just one of them be the already wrong. Using a sorted sequence to prevent
1294 for lname in sorted(frozenset(names)):
1296 lock = self.__lockdict[lname] # raises KeyError if lock is not there
1298 # We are acquiring the whole set, it doesn't matter if this particular
1299 # element is not there anymore. If, however, only certain names should
1300 # be acquired, not finding a lock is an error.
1301 if mode == _LS_ACQUIRE_EXACT:
1302 raise errors.LockError("Lock '%s' not found in set '%s' (it may have"
1303 " been removed)" % (lname, self.name))
1305 acquire_list.append((lname, lock))
1307 # This will hold the locknames we effectively acquired.
1311 # Now acquire_list contains a sorted list of resources and locks we
1312 # want. In order to get them we loop on this (private) list and
1313 # acquire() them. We gave no real guarantee they will still exist till
1314 # this is done but .acquire() itself is safe and will alert us if the
1315 # lock gets deleted.
1316 for (lname, lock) in acquire_list:
1317 if __debug__ and callable(test_notify):
1318 test_notify_fn = lambda: test_notify(lname)
1320 test_notify_fn = None
1322 timeout = timeout_fn()
1325 # raises LockError if the lock was deleted
1326 acq_success = lock.acquire(shared=shared, timeout=timeout,
1328 test_notify=test_notify_fn)
1329 except errors.LockError:
1330 if mode in (_LS_ACQUIRE_ALL, _LS_ACQUIRE_OPPORTUNISTIC):
1331 # We are acquiring the whole set, it doesn't matter if this
1332 # particular element is not there anymore.
1335 raise errors.LockError("Lock '%s' not found in set '%s' (it may have"
1336 " been removed)" % (lname, self.name))
1339 # Couldn't get lock or timeout occurred
1340 if mode == _LS_ACQUIRE_OPPORTUNISTIC:
1341 # Ignore timeouts on opportunistic acquisitions
1345 # This shouldn't happen as SharedLock.acquire(timeout=None) is
1347 raise errors.LockError("Failed to get lock %s (set %s)" %
1350 raise _AcquireTimeout()
1353 # now the lock cannot be deleted, we have it!
1354 self._add_owned(name=lname)
1358 # We shouldn't have problems adding the lock to the owners list, but
1359 # if we did we'll try to release this lock and re-raise exception.
1360 # Of course something is going to be really wrong after this.
1366 # Release all owned locks
1367 self._release_and_delete_owned()
1372 def downgrade(self, names=None):
1373 """Downgrade a set of resource locks from exclusive to shared mode.
1375 The locks must have been acquired in exclusive mode.
1378 assert self.is_owned(), ("downgrade on lockset %s while not owning any"
1379 " lock" % self.name)
1381 # Support passing in a single resource to downgrade rather than many
1382 if isinstance(names, basestring):
1385 owned = self.list_owned()
1391 assert owned.issuperset(names), \
1392 ("downgrade() on unheld resources %s (set %s)" %
1393 (names.difference(owned), self.name))
1395 for lockname in names:
1396 self.__lockdict[lockname].downgrade()
1398 # Do we own the lockset in exclusive mode?
1399 if self.__lock.is_owned(shared=0):
1400 # Have all locks been downgraded?
1401 if not compat.any(lock.is_owned(shared=0)
1402 for lock in self.__lockdict.values()):
1403 self.__lock.downgrade()
1404 assert self.__lock.is_owned(shared=1)
1408 def release(self, names=None):
1409 """Release a set of resource locks, at the same level.
1411 You must have acquired the locks, either in shared or in exclusive mode,
1412 before releasing them.
1414 @type names: list of strings, or None
1415 @param names: the names of the locks which shall be released
1416 (defaults to all the locks acquired at that level).
1419 assert self.is_owned(), ("release() on lock set %s while not owner" %
1422 # Support passing in a single resource to release rather than many
1423 if isinstance(names, basestring):
1427 names = self.list_owned()
1430 assert self.list_owned().issuperset(names), (
1431 "release() on unheld resources %s (set %s)" %
1432 (names.difference(self.list_owned()), self.name))
1434 # First of all let's release the "all elements" lock, if set.
1435 # After this 'add' can work again
1436 if self.__lock.is_owned():
1437 self.__lock.release()
1440 for lockname in names:
1441 # If we are sure the lock doesn't leave __lockdict without being
1442 # exclusively held we can do this...
1443 self.__lockdict[lockname].release()
1444 self._del_owned(name=lockname)
1446 def add(self, names, acquired=0, shared=0):
1447 """Add a new set of elements to the set
1449 @type names: list of strings
1450 @param names: names of the new elements to add
1451 @type acquired: integer (0/1) used as a boolean
1452 @param acquired: pre-acquire the new resource?
1453 @type shared: integer (0/1) used as a boolean
1454 @param shared: is the pre-acquisition shared?
1457 # Check we don't already own locks at this level
1458 assert not self.is_owned() or self.__lock.is_owned(shared=0), \
1459 ("Cannot add locks if the set %s is only partially owned, or shared" %
1462 # Support passing in a single resource to add rather than many
1463 if isinstance(names, basestring):
1466 # If we don't already own the set-level lock acquired in an exclusive way
1467 # we'll get it and note we need to release it later.
1468 release_lock = False
1469 if not self.__lock.is_owned():
1471 self.__lock.acquire()
1474 invalid_names = set(self.__names()).intersection(names)
1476 # This must be an explicit raise, not an assert, because assert is
1477 # turned off when using optimization, and this can happen because of
1478 # concurrency even if the user doesn't want it.
1479 raise errors.LockError("duplicate add(%s) on lockset %s" %
1480 (invalid_names, self.name))
1482 for lockname in names:
1483 lock = SharedLock(self._GetLockName(lockname), monitor=self.__monitor)
1486 # No need for priority or timeout here as this lock has just been
1488 lock.acquire(shared=shared)
1489 # now the lock cannot be deleted, we have it!
1491 self._add_owned(name=lockname)
1493 # We shouldn't have problems adding the lock to the owners list,
1494 # but if we did we'll try to release this lock and re-raise
1495 # exception. Of course something is going to be really wrong,
1496 # after this. On the other hand the lock hasn't been added to the
1497 # __lockdict yet so no other threads should be pending on it. This
1498 # release is just a safety measure.
1502 self.__lockdict[lockname] = lock
1505 # Only release __lock if we were not holding it previously.
1507 self.__lock.release()
1511 def remove(self, names):
1512 """Remove elements from the lock set.
1514 You can either not hold anything in the lockset or already hold a superset
1515 of the elements you want to delete, exclusively.
1517 @type names: list of strings
1518 @param names: names of the resource to remove.
1520 @return: a list of locks which we removed; the list is always
1521 equal to the names list if we were holding all the locks
1525 # Support passing in a single resource to remove rather than many
1526 if isinstance(names, basestring):
1529 # If we own any subset of this lock it must be a superset of what we want
1530 # to delete. The ownership must also be exclusive, but that will be checked
1531 # by the lock itself.
1532 assert not self.is_owned() or self.list_owned().issuperset(names), (
1533 "remove() on acquired lockset %s while not owning all elements" %
1539 # Calling delete() acquires the lock exclusively if we don't already own
1540 # it, and causes all pending and subsequent lock acquires to fail. It's
1541 # fine to call it out of order because delete() also implies release(),
1542 # and the assertion above guarantees that if we either already hold
1543 # everything we want to delete, or we hold none.
1545 self.__lockdict[lname].delete()
1546 removed.append(lname)
1547 except (KeyError, errors.LockError):
1548 # This cannot happen if we were already holding it, verify:
1549 assert not self.is_owned(), ("remove failed while holding lockset %s" %
1552 # If no LockError was raised we are the ones who deleted the lock.
1553 # This means we can safely remove it from lockdict, as any further or
1554 # pending delete() or acquire() will fail (and nobody can have the lock
1555 # since before our call to delete()).
1557 # This is done in an else clause because if the exception was thrown
1558 # it's the job of the one who actually deleted it.
1559 del self.__lockdict[lname]
1560 # And let's remove it from our private list if we owned it.
1562 self._del_owned(name=lname)
1567 # Locking levels, must be acquired in increasing order. Current rules are:
1568 # - At level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
1569 # acquired before performing any operation, either in shared or exclusive
1570 # mode. Acquiring the BGL in exclusive mode is discouraged and should be
1572 # - At levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks. If
1573 # you need more than one node, or more than one instance, acquire them at the
1575 # - LEVEL_NODE_RES is for node resources and should be used by operations with
1576 # possibly high impact on the node's disks.
1577 # - LEVEL_NODE_ALLOC blocks instance allocations for the whole cluster
1578 # ("NAL" is the only lock at this level). It should be acquired in shared
1579 # mode when an opcode blocks all or a significant amount of a cluster's
1580 # locks. Opcodes doing instance allocations should acquire in exclusive mode.
1581 # Once the set of acquired locks for an opcode has been reduced to the working
1582 # set, the NAL should be released as well to allow allocations to proceed.
1589 LEVEL_NETWORK) = range(0, 7)
1601 # Lock levels which are modifiable
1602 LEVELS_MOD = compat.UniqueFrozenset([
1610 #: Lock level names (make sure to use singular form)
1612 LEVEL_CLUSTER: "cluster",
1613 LEVEL_INSTANCE: "instance",
1614 LEVEL_NODE_ALLOC: "node-alloc",
1615 LEVEL_NODEGROUP: "nodegroup",
1617 LEVEL_NODE_RES: "node-res",
1618 LEVEL_NETWORK: "network",
1621 # Constant for the big ganeti lock
1624 #: Node allocation lock
1628 class GanetiLockManager:
1629 """The Ganeti Locking Library
1631 The purpose of this small library is to manage locking for ganeti clusters
1632 in a central place, while at the same time doing dynamic checks against
1633 possible deadlocks. It will also make it easier to transition to a different
1634 lock type should we migrate away from python threads.
1639 def __init__(self, nodes, nodegroups, instances, networks):
1640 """Constructs a new GanetiLockManager object.
1642 There should be only a GanetiLockManager object at any time, so this
1643 function raises an error if this is not the case.
1645 @param nodes: list of node names
1646 @param nodegroups: list of nodegroup uuids
1647 @param instances: list of instance names
1650 assert self.__class__._instance is None, \
1651 "double GanetiLockManager instance"
1653 self.__class__._instance = self
1655 self._monitor = LockMonitor()
1657 # The keyring contains all the locks, at their level and in the correct
1660 LEVEL_CLUSTER: LockSet([BGL], "cluster", monitor=self._monitor),
1661 LEVEL_NODE: LockSet(nodes, "node", monitor=self._monitor),
1662 LEVEL_NODE_RES: LockSet(nodes, "node-res", monitor=self._monitor),
1663 LEVEL_NODEGROUP: LockSet(nodegroups, "nodegroup", monitor=self._monitor),
1664 LEVEL_INSTANCE: LockSet(instances, "instance", monitor=self._monitor),
1665 LEVEL_NETWORK: LockSet(networks, "network", monitor=self._monitor),
1666 LEVEL_NODE_ALLOC: LockSet([NAL], "node-alloc", monitor=self._monitor),
1669 assert compat.all(ls.name == LEVEL_NAMES[level]
1670 for (level, ls) in self.__keyring.items()), \
1671 "Keyring name mismatch"
1673 def AddToLockMonitor(self, provider):
1674 """Registers a new lock with the monitor.
1676 See L{LockMonitor.RegisterLock}.
1679 return self._monitor.RegisterLock(provider)
1681 def QueryLocks(self, fields):
1682 """Queries information from all locks.
1684 See L{LockMonitor.QueryLocks}.
1687 return self._monitor.QueryLocks(fields)
1689 def _names(self, level):
1690 """List the lock names at the given level.
1692 This can be used for debugging/testing purposes.
1694 @param level: the level whose list of locks to get
1697 assert level in LEVELS, "Invalid locking level %s" % level
1698 return self.__keyring[level]._names()
1700 def is_owned(self, level):
1701 """Check whether we are owning locks at the given level
1704 return self.__keyring[level].is_owned()
1706 def list_owned(self, level):
1707 """Get the set of owned locks at the given level
1710 return self.__keyring[level].list_owned()
1712 def check_owned(self, level, names, shared=-1):
1713 """Check if locks at a certain level are owned in a specific mode.
1715 @see: L{LockSet.check_owned}
1718 return self.__keyring[level].check_owned(names, shared=shared)
1720 def owning_all(self, level):
1721 """Checks whether current thread owns all locks at a certain level.
1723 @see: L{LockSet.owning_all}
1726 return self.__keyring[level].owning_all()
1728 def _upper_owned(self, level):
1729 """Check that we don't own any lock at a level greater than the given one.
1732 # This way of checking only works if LEVELS[i] = i, which we check for in
1734 return compat.any((self.is_owned(l) for l in LEVELS[level + 1:]))
1736 def _BGL_owned(self): # pylint: disable=C0103
1737 """Check if the current thread owns the BGL.
1739 Both an exclusive or a shared acquisition work.
1742 return BGL in self.__keyring[LEVEL_CLUSTER].list_owned()
1745 def _contains_BGL(level, names): # pylint: disable=C0103
1746 """Check if the level contains the BGL.
1748 Check if acting on the given level and set of names will change
1749 the status of the Big Ganeti Lock.
1752 return level == LEVEL_CLUSTER and (names is None or BGL in names)
1754 def acquire(self, level, names, timeout=None, shared=0, priority=None,
1755 opportunistic=False):
1756 """Acquire a set of resource locks, at the same level.
1758 @type level: member of locking.LEVELS
1759 @param level: the level at which the locks shall be acquired
1760 @type names: list of strings (or string)
1761 @param names: the names of the locks which shall be acquired
1762 (special lock names, or instance/node names)
1763 @type shared: integer (0/1) used as a boolean
1764 @param shared: whether to acquire in shared mode; by default
1765 an exclusive lock will be acquired
1766 @type timeout: float
1767 @param timeout: Maximum time to acquire all locks
1768 @type priority: integer
1769 @param priority: Priority for acquiring lock
1770 @type opportunistic: boolean
1771 @param opportunistic: Acquire locks opportunistically; use the return value
1772 to determine which locks were actually acquired
1775 assert level in LEVELS, "Invalid locking level %s" % level
1777 # Check that we are either acquiring the Big Ganeti Lock or we already own
1778 # it. Some "legacy" opcodes need to be sure they are run non-concurrently
1779 # so even if we've migrated we need to at least share the BGL to be
1780 # compatible with them. Of course if we own the BGL exclusively there's no
1781 # point in acquiring any other lock, unless perhaps we are half way through
1782 # the migration of the current opcode.
1783 assert (self._contains_BGL(level, names) or self._BGL_owned()), (
1784 "You must own the Big Ganeti Lock before acquiring any other")
1786 # Check we don't own locks at the same or upper levels.
1787 assert not self._upper_owned(level), ("Cannot acquire locks at a level"
1788 " while owning some at a greater one")
1790 # Acquire the locks in the set.
1791 return self.__keyring[level].acquire(names, shared=shared, timeout=timeout,
1793 opportunistic=opportunistic)
1795 def downgrade(self, level, names=None):
1796 """Downgrade a set of resource locks from exclusive to shared mode.
1798 You must have acquired the locks in exclusive mode.
1800 @type level: member of locking.LEVELS
1801 @param level: the level at which the locks shall be downgraded
1802 @type names: list of strings, or None
1803 @param names: the names of the locks which shall be downgraded
1804 (defaults to all the locks acquired at the level)
1807 assert level in LEVELS, "Invalid locking level %s" % level
1809 return self.__keyring[level].downgrade(names=names)
1811 def release(self, level, names=None):
1812 """Release a set of resource locks, at the same level.
1814 You must have acquired the locks, either in shared or in exclusive
1815 mode, before releasing them.
1817 @type level: member of locking.LEVELS
1818 @param level: the level at which the locks shall be released
1819 @type names: list of strings, or None
1820 @param names: the names of the locks which shall be released
1821 (defaults to all the locks acquired at that level)
1824 assert level in LEVELS, "Invalid locking level %s" % level
1825 assert (not self._contains_BGL(level, names) or
1826 not self._upper_owned(LEVEL_CLUSTER)), (
1827 "Cannot release the Big Ganeti Lock while holding something"
1828 " at upper levels (%r)" %
1829 (utils.CommaJoin(["%s=%r" % (LEVEL_NAMES[i], self.list_owned(i))
1830 for i in self.__keyring.keys()]), ))
1832 # Release will complain if we don't own the locks already
1833 return self.__keyring[level].release(names)
1835 def add(self, level, names, acquired=0, shared=0):
1836 """Add locks at the specified level.
1838 @type level: member of locking.LEVELS_MOD
1839 @param level: the level at which the locks shall be added
1840 @type names: list of strings
1841 @param names: names of the locks to acquire
1842 @type acquired: integer (0/1) used as a boolean
1843 @param acquired: whether to acquire the newly added locks
1844 @type shared: integer (0/1) used as a boolean
1845 @param shared: whether the acquisition will be shared
1848 assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
1849 assert self._BGL_owned(), ("You must own the BGL before performing other"
1851 assert not self._upper_owned(level), ("Cannot add locks at a level"
1852 " while owning some at a greater one")
1853 return self.__keyring[level].add(names, acquired=acquired, shared=shared)
1855 def remove(self, level, names):
1856 """Remove locks from the specified level.
1858 You must either already own the locks you are trying to remove
1859 exclusively or not own any lock at an upper level.
1861 @type level: member of locking.LEVELS_MOD
1862 @param level: the level at which the locks shall be removed
1863 @type names: list of strings
1864 @param names: the names of the locks which shall be removed
1865 (special lock names, or instance/node names)
1868 assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
1869 assert self._BGL_owned(), ("You must own the BGL before performing other"
1871 # Check we either own the level or don't own anything from here
1872 # up. LockSet.remove() will check the case in which we don't own
1873 # all the needed resources, or we have a shared ownership.
1874 assert self.is_owned(level) or not self._upper_owned(level), (
1875 "Cannot remove locks at a level while not owning it or"
1876 " owning some at a greater one")
1877 return self.__keyring[level].remove(names)
1880 def _MonitorSortKey((item, idx, num)):
1881 """Sorting key function.
1883 Sort by name, registration order and then order of information. This provides
1884 a stable sort order over different providers, even if they return the same
1888 (name, _, _, _) = item
1890 return (utils.NiceSortKey(name), num, idx)
1893 class LockMonitor(object):
1894 _LOCK_ATTR = "_lock"
1897 """Initializes this class.
1900 self._lock = SharedLock("LockMonitor")
1902 # Counter for stable sorting
1903 self._counter = itertools.count(0)
1905 # Tracked locks. Weak references are used to avoid issues with circular
1906 # references and deletion.
1907 self._locks = weakref.WeakKeyDictionary()
1909 @ssynchronized(_LOCK_ATTR)
1910 def RegisterLock(self, provider):
1911 """Registers a new lock.
1913 @param provider: Object with a callable method named C{GetLockInfo}, taking
1914 a single C{set} containing the requested information items
1915 @note: It would be nicer to only receive the function generating the
1916 requested information but, as it turns out, weak references to bound
1917 methods (e.g. C{self.GetLockInfo}) are tricky; there are several
1918 workarounds, but none of the ones I found works properly in combination
1919 with a standard C{WeakKeyDictionary}
1922 assert provider not in self._locks, "Duplicate registration"
1924 # There used to be a check for duplicate names here. As it turned out, when
1925 # a lock is re-created with the same name in a very short timeframe, the
1926 # previous instance might not yet be removed from the weakref dictionary.
1927 # By keeping track of the order of incoming registrations, a stable sort
1928 # ordering can still be guaranteed.
1930 self._locks[provider] = self._counter.next()
1932 def _GetLockInfo(self, requested):
1933 """Get information from all locks.
1936 # Must hold lock while getting consistent list of tracked items
1937 self._lock.acquire(shared=1)
1939 items = self._locks.items()
1941 self._lock.release()
1943 return [(info, idx, num)
1944 for (provider, num) in items
1945 for (idx, info) in enumerate(provider.GetLockInfo(requested))]
1947 def _Query(self, fields):
1948 """Queries information from all locks.
1950 @type fields: list of strings
1951 @param fields: List of fields to return
1954 qobj = query.Query(query.LOCK_FIELDS, fields)
1956 # Get all data with internal lock held and then sort by name and incoming
1958 lockinfo = sorted(self._GetLockInfo(qobj.RequestedData()),
1959 key=_MonitorSortKey)
1961 # Extract lock information and build query data
1962 return (qobj, query.LockQueryData(map(compat.fst, lockinfo)))
1964 def QueryLocks(self, fields):
1965 """Queries information from all locks.
1967 @type fields: list of strings
1968 @param fields: List of fields to return
1971 (qobj, ctx) = self._Query(fields)
1973 # Prepare query response
1974 return query.GetQueryResponse(qobj, ctx)