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 """Module implementing the Ganeti locking code."""
23 # pylint: disable-msg=W0613,W0201
26 # Wouldn't it be better to define LockingError in the locking module?
27 # Well, for now that's how the rest of the code does it...
28 from ganeti import errors
29 from ganeti import utils
33 """Implements a shared lock.
35 Multiple threads can acquire the lock in a shared way, calling
36 acquire_shared(). In order to acquire the lock in an exclusive way threads
37 can call acquire_exclusive().
39 The lock prevents starvation but does not guarantee that threads will acquire
40 the shared lock in the order they queued for it, just that they will
45 """Construct a new SharedLock"""
46 # we have two conditions, c_shr and c_exc, sharing the same lock.
47 self.__lock = threading.Lock()
48 self.__turn_shr = threading.Condition(self.__lock)
49 self.__turn_exc = threading.Condition(self.__lock)
51 # current lock holders
60 # is this lock in the deleted state?
61 self.__deleted = False
63 def __is_sharer(self):
64 """Is the current thread sharing the lock at this time?"""
65 return threading.currentThread() in self.__shr
67 def __is_exclusive(self):
68 """Is the current thread holding the lock exclusively at this time?"""
69 return threading.currentThread() == self.__exc
71 def __is_owned(self, shared=-1):
72 """Is the current thread somehow owning the lock at this time?
74 This is a private version of the function, which presumes you're holding
79 return self.__is_sharer() or self.__is_exclusive()
81 return self.__is_sharer()
83 return self.__is_exclusive()
85 def _is_owned(self, shared=-1):
86 """Is the current thread somehow owning the lock at this time?
90 < 0: check for any type of ownership (default)
91 0: check for exclusive ownership
92 > 0: check for shared ownership
97 result = self.__is_owned(shared=shared)
104 """Wait on the given condition, and raise an exception if the current lock
105 is declared deleted in the meantime.
108 c: condition to wait on
113 raise errors.LockError('deleted lock')
115 def __exclusive_acquire(self):
116 """Acquire the lock exclusively.
118 This is a private function that presumes you are already holding the
119 internal lock. It's defined separately to avoid code duplication between
120 acquire() and delete()
123 self.__nwait_exc += 1
125 # This is to save ourselves from a nasty race condition that could
126 # theoretically make the sharers starve.
127 if self.__nwait_shr > 0 or self.__nwait_exc > 1:
128 self.__wait(self.__turn_exc)
130 while len(self.__shr) > 0 or self.__exc is not None:
131 self.__wait(self.__turn_exc)
133 self.__exc = threading.currentThread()
135 self.__nwait_exc -= 1
137 assert self.__npass_shr == 0, "SharedLock: internal fairness violation"
139 def acquire(self, blocking=1, shared=0):
140 """Acquire a shared lock.
143 shared: whether to acquire in shared mode. By default an exclusive lock
145 blocking: whether to block while trying to acquire or to operate in
146 try-lock mode. this locking mode is not supported yet.
150 # We don't have non-blocking mode for now
151 raise NotImplementedError
153 self.__lock.acquire()
156 raise errors.LockError('deleted lock')
158 # We cannot acquire the lock if we already have it
159 assert not self.__is_owned(), "double acquire() on a non-recursive lock"
160 assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
163 self.__nwait_shr += 1
166 # If there is an exclusive holder waiting we have to wait. We'll
167 # only do this once, though, when we start waiting for the lock. Then
168 # we'll just wait while there are no exclusive holders.
169 if self.__nwait_exc > 0:
170 # TODO: if !blocking...
172 self.__wait(self.__turn_shr)
174 while self.__exc is not None:
176 # TODO: if !blocking...
177 self.__wait(self.__turn_shr)
179 self.__shr.add(threading.currentThread())
181 # If we were waiting note that we passed
183 self.__npass_shr -= 1
186 self.__nwait_shr -= 1
188 assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
190 # TODO: if !blocking...
191 # (or modify __exclusive_acquire for non-blocking mode)
192 self.__exclusive_acquire()
195 self.__lock.release()
200 """Release a Shared Lock.
202 You must have acquired the lock, either in shared or in exclusive mode,
203 before calling this function.
206 self.__lock.acquire()
208 assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
209 # Autodetect release type
210 if self.__is_exclusive():
213 # An exclusive holder has just had the lock, time to put it in shared
214 # mode if there are shared holders waiting. Otherwise wake up the next
216 if self.__nwait_shr > 0:
217 # Make sure at least the ones which were blocked pass.
218 self.__npass_shr = self.__nwait_shr
219 self.__turn_shr.notifyAll()
220 elif self.__nwait_exc > 0:
221 self.__turn_exc.notify()
223 elif self.__is_sharer():
224 self.__shr.remove(threading.currentThread())
226 # If there are shared holders waiting (and not just scheduled to pass)
227 # there *must* be an exclusive holder waiting as well; otherwise what
228 # were they waiting for?
229 assert (self.__nwait_exc > 0 or self.__npass_shr > 0 or
230 self.__nwait_shr == 0), \
231 "Lock sharers waiting while no exclusive is queueing"
233 # If there are no more shared holders either in or scheduled to pass,
234 # and some exclusive holders are waiting let's wake one up.
235 if (len(self.__shr) == 0 and
236 self.__nwait_exc > 0 and
237 not self.__npass_shr > 0):
238 self.__turn_exc.notify()
241 assert False, "Cannot release non-owned lock"
244 self.__lock.release()
246 def delete(self, blocking=1):
247 """Delete a Shared Lock.
249 This operation will declare the lock for removal. First the lock will be
250 acquired in exclusive mode if you don't already own it, then the lock
251 will be put in a state where any future and pending acquire() fail.
254 blocking: whether to block while trying to acquire or to operate in
255 try-lock mode. this locking mode is not supported yet unless
256 you are already holding exclusively the lock.
259 self.__lock.acquire()
261 assert not self.__is_sharer(), "cannot delete() a lock while sharing it"
264 raise errors.LockError('deleted lock')
266 if not self.__is_exclusive():
268 # We don't have non-blocking mode for now
269 raise NotImplementedError
270 self.__exclusive_acquire()
272 self.__deleted = True
274 # Wake up everybody, they will fail acquiring the lock and
275 # raise an exception instead.
276 self.__turn_exc.notifyAll()
277 self.__turn_shr.notifyAll()
280 self.__lock.release()
284 """Implements a set of locks.
286 This abstraction implements a set of shared locks for the same resource type,
287 distinguished by name. The user can lock a subset of the resources and the
288 LockSet will take care of acquiring the locks always in the same order, thus
291 All the locks needed in the same set must be acquired together, though.
294 def __init__(self, members=None):
295 """Constructs a new LockSet.
298 members: initial members of the set
301 # Used internally to guarantee coherency.
302 self.__lock = SharedLock()
304 # The lockdict indexes the relationship name -> lock
305 # The order-of-locking is implied by the alphabetical order of names
308 if members is not None:
310 self.__lockdict[name] = SharedLock()
312 # The owner dict contains the set of locks each thread owns. For
313 # performance each thread can access its own key without a global lock on
314 # this structure. It is paramount though that *no* other type of access is
315 # done to this structure (eg. no looping over its keys). *_owner helper
316 # function are defined to guarantee access is correct, but in general never
317 # do anything different than __owners[threading.currentThread()], or there
322 """Is the current thread a current level owner?"""
323 return threading.currentThread() in self.__owners
325 def _add_owned(self, name=None):
326 """Note the current thread owns the given lock"""
328 if not self._is_owned():
329 self.__owners[threading.currentThread()] = set()
332 self.__owners[threading.currentThread()].add(name)
334 self.__owners[threading.currentThread()] = set([name])
337 def _del_owned(self, name=None):
338 """Note the current thread owns the given lock"""
341 self.__owners[threading.currentThread()].remove(name)
343 # Only remove the key if we don't hold the set-lock as well
344 if (not self.__lock._is_owned() and
345 not self.__owners[threading.currentThread()]):
346 del self.__owners[threading.currentThread()]
348 def _list_owned(self):
349 """Get the set of resource names owned by the current thread"""
351 return self.__owners[threading.currentThread()].copy()
356 """Return the current set of names.
358 Only call this function while holding __lock and don't iterate on the
359 result after releasing the lock.
362 return self.__lockdict.keys()
365 """Return a copy of the current set of elements.
367 Used only for debugging purposes.
370 self.__lock.acquire(shared=1)
372 result = self.__names()
374 self.__lock.release()
377 def acquire(self, names, blocking=1, shared=0):
378 """Acquire a set of resource locks.
381 names: the names of the locks which shall be acquired.
382 (special lock names, or instance/node names)
383 shared: whether to acquire in shared mode. By default an exclusive lock
385 blocking: whether to block while trying to acquire or to operate in
386 try-lock mode. this locking mode is not supported yet.
389 True: when all the locks are successfully acquired
392 errors.LockError: when any lock we try to acquire has been deleted
393 before we succeed. In this case none of the locks requested will be
398 # We don't have non-blocking mode for now
399 raise NotImplementedError
401 # Check we don't already own locks at this level
402 assert not self._is_owned(), "Cannot acquire locks in the same set twice"
405 # If no names are given acquire the whole set by not letting new names
406 # being added before we release, and getting the current list of names.
407 # Some of them may then be deleted later, but we'll cope with this.
409 # We'd like to acquire this lock in a shared way, as it's nice if
410 # everybody else can use the instances at the same time. If are acquiring
411 # them exclusively though they won't be able to do this anyway, though,
412 # so we'll get the list lock exclusively as well in order to be able to
413 # do add() on the set while owning it.
414 self.__lock.acquire(shared=shared)
416 # note we own the set-lock
418 names = self.__names()
420 # We shouldn't have problems adding the lock to the owners list, but
421 # if we did we'll try to release this lock and re-raise exception.
422 # Of course something is going to be really wrong, after this.
423 self.__lock.release()
427 # Support passing in a single resource to acquire rather than many
428 if isinstance(names, basestring):
434 # First we look the locks up on __lockdict. We have no way of being sure
435 # they will still be there after, but this makes it a lot faster should
436 # just one of them be the already wrong
439 lock = self.__lockdict[lname] # raises KeyError if lock is not there
440 acquire_list.append((lname, lock))
442 if self.__lock._is_owned():
443 # We are acquiring all the set, it doesn't matter if this particular
444 # element is not there anymore.
447 raise errors.LockError('non-existing lock in set (%s)' % lname)
449 # This will hold the locknames we effectively acquired.
451 # Now acquire_list contains a sorted list of resources and locks we want.
452 # In order to get them we loop on this (private) list and acquire() them.
453 # We gave no real guarantee they will still exist till this is done but
454 # .acquire() itself is safe and will alert us if the lock gets deleted.
455 for (lname, lock) in acquire_list:
457 lock.acquire(shared=shared) # raises LockError if the lock is deleted
458 # now the lock cannot be deleted, we have it!
459 self._add_owned(name=lname)
461 except (errors.LockError):
462 if self.__lock._is_owned():
463 # We are acquiring all the set, it doesn't matter if this particular
464 # element is not there anymore.
468 for lname in self._list_owned():
469 self.__lockdict[lname].release()
470 self._del_owned(name=lname)
471 raise errors.LockError('non-existing lock in set (%s)' % name_fail)
473 # We shouldn't have problems adding the lock to the owners list, but
474 # if we did we'll try to release this lock and re-raise exception.
475 # Of course something is going to be really wrong, after this.
481 # If something went wrong and we had the set-lock let's release it...
482 if self.__lock._is_owned():
483 self.__lock.release()
488 def release(self, names=None):
489 """Release a set of resource locks, at the same level.
491 You must have acquired the locks, either in shared or in exclusive mode,
492 before releasing them.
495 names: the names of the locks which shall be released.
496 (defaults to all the locks acquired at that level).
499 assert self._is_owned(), "release() on lock set while not owner"
501 # Support passing in a single resource to release rather than many
502 if isinstance(names, basestring):
506 names = self._list_owned()
509 assert self._list_owned().issuperset(names), (
510 "release() on unheld resources %s" %
511 names.difference(self._list_owned()))
513 # First of all let's release the "all elements" lock, if set.
514 # After this 'add' can work again
515 if self.__lock._is_owned():
516 self.__lock.release()
519 for lockname in names:
520 # If we are sure the lock doesn't leave __lockdict without being
521 # exclusively held we can do this...
522 self.__lockdict[lockname].release()
523 self._del_owned(name=lockname)
525 def add(self, names, acquired=0, shared=0):
526 """Add a new set of elements to the set
529 names: names of the new elements to add
530 acquired: pre-acquire the new resource?
531 shared: is the pre-acquisition shared?
535 assert not self.__lock._is_owned(shared=1), (
536 "Cannot add new elements while sharing the set-lock")
538 # Support passing in a single resource to add rather than many
539 if isinstance(names, basestring):
542 # If we don't already own the set-level lock acquire it in an exclusive way
543 # we'll get it and note we need to release it later.
545 if not self.__lock._is_owned():
547 self.__lock.acquire()
550 invalid_names = set(self.__names()).intersection(names)
552 # This must be an explicit raise, not an assert, because assert is
553 # turned off when using optimization, and this can happen because of
554 # concurrency even if the user doesn't want it.
555 raise errors.LockError("duplicate add() (%s)" % invalid_names)
557 for lockname in names:
561 lock.acquire(shared=shared)
562 # now the lock cannot be deleted, we have it!
564 self._add_owned(name=lockname)
566 # We shouldn't have problems adding the lock to the owners list,
567 # but if we did we'll try to release this lock and re-raise
568 # exception. Of course something is going to be really wrong,
569 # after this. On the other hand the lock hasn't been added to the
570 # __lockdict yet so no other threads should be pending on it. This
571 # release is just a safety measure.
575 self.__lockdict[lockname] = lock
578 # Only release __lock if we were not holding it previously.
580 self.__lock.release()
584 def remove(self, names, blocking=1):
585 """Remove elements from the lock set.
587 You can either not hold anything in the lockset or already hold a superset
588 of the elements you want to delete, exclusively.
591 names: names of the resource to remove.
592 blocking: whether to block while trying to acquire or to operate in
593 try-lock mode. this locking mode is not supported yet unless
594 you are already holding exclusively the locks.
597 A list of lock which we removed. The list is always equal to the names
598 list if we were holding all the locks exclusively.
601 if not blocking and not self._is_owned():
602 # We don't have non-blocking mode for now
603 raise NotImplementedError
605 # Support passing in a single resource to remove rather than many
606 if isinstance(names, basestring):
609 # If we own any subset of this lock it must be a superset of what we want
610 # to delete. The ownership must also be exclusive, but that will be checked
611 # by the lock itself.
612 assert not self._is_owned() or self._list_owned().issuperset(names), (
613 "remove() on acquired lockset while not owning all elements")
618 # Calling delete() acquires the lock exclusively if we don't already own
619 # it, and causes all pending and subsequent lock acquires to fail. It's
620 # fine to call it out of order because delete() also implies release(),
621 # and the assertion above guarantees that if we either already hold
622 # everything we want to delete, or we hold none.
624 self.__lockdict[lname].delete()
625 removed.append(lname)
626 except (KeyError, errors.LockError):
627 # This cannot happen if we were already holding it, verify:
628 assert not self._is_owned(), "remove failed while holding lockset"
630 # If no LockError was raised we are the ones who deleted the lock.
631 # This means we can safely remove it from lockdict, as any further or
632 # pending delete() or acquire() will fail (and nobody can have the lock
633 # since before our call to delete()).
635 # This is done in an else clause because if the exception was thrown
636 # it's the job of the one who actually deleted it.
637 del self.__lockdict[lname]
638 # And let's remove it from our private list if we owned it.
640 self._del_owned(name=lname)
645 # Locking levels, must be acquired in increasing order.
647 # - at level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
648 # acquired before performing any operation, either in shared or in exclusive
649 # mode. acquiring the BGL in exclusive mode is discouraged and should be
651 # - at levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks.
652 # If you need more than one node, or more than one instance, acquire them at
654 # - level LEVEL_CONFIG contains the configuration lock, which you must acquire
655 # before reading or changing the config file.
661 LEVELS = [LEVEL_CLUSTER,
666 # Lock levels which are modifiable
667 LEVELS_MOD = [LEVEL_NODE, LEVEL_INSTANCE]
669 # Constant for the big ganeti lock and config lock
674 class GanetiLockManager:
675 """The Ganeti Locking Library
677 The purpouse of this small library is to manage locking for ganeti clusters
678 in a central place, while at the same time doing dynamic checks against
679 possible deadlocks. It will also make it easier to transition to a different
680 lock type should we migrate away from python threads.
685 def __init__(self, nodes=None, instances=None):
686 """Constructs a new GanetiLockManager object.
688 There should be only a GanetiLockManager object at any time, so this
689 function raises an error if this is not the case.
692 nodes: list of node names
693 instances: list of instance names
696 assert self.__class__._instance is None, "double GanetiLockManager instance"
697 self.__class__._instance = self
699 # The keyring contains all the locks, at their level and in the correct
702 LEVEL_CLUSTER: LockSet([BGL]),
703 LEVEL_NODE: LockSet(nodes),
704 LEVEL_INSTANCE: LockSet(instances),
705 LEVEL_CONFIG: LockSet([CONFIG]),
708 def _names(self, level):
709 """List the lock names at the given level.
710 Used for debugging/testing purposes.
713 level: the level whose list of locks to get
716 assert level in LEVELS, "Invalid locking level %s" % level
717 return self.__keyring[level]._names()
719 def _is_owned(self, level):
720 """Check whether we are owning locks at the given level
723 return self.__keyring[level]._is_owned()
725 def _list_owned(self, level):
726 """Get the set of owned locks at the given level
729 return self.__keyring[level]._list_owned()
731 def _upper_owned(self, level):
732 """Check that we don't own any lock at a level greater than the given one.
735 # This way of checking only works if LEVELS[i] = i, which we check for in
737 return utils.any((self._is_owned(l) for l in LEVELS[level + 1:]))
739 def _BGL_owned(self):
740 """Check if the current thread owns the BGL.
742 Both an exclusive or a shared acquisition work.
745 return BGL in self.__keyring[LEVEL_CLUSTER]._list_owned()
747 def _contains_BGL(self, level, names):
748 """Check if acting on the given level and set of names will change the
749 status of the Big Ganeti Lock.
752 return level == LEVEL_CLUSTER and (names is None or BGL in names)
754 def acquire(self, level, names, blocking=1, shared=0):
755 """Acquire a set of resource locks, at the same level.
758 level: the level at which the locks shall be acquired.
759 It must be a memmber of LEVELS.
760 names: the names of the locks which shall be acquired.
761 (special lock names, or instance/node names)
762 shared: whether to acquire in shared mode. By default an exclusive lock
764 blocking: whether to block while trying to acquire or to operate in
765 try-lock mode. this locking mode is not supported yet.
768 assert level in LEVELS, "Invalid locking level %s" % level
770 # Check that we are either acquiring the Big Ganeti Lock or we already own
771 # it. Some "legacy" opcodes need to be sure they are run non-concurrently
772 # so even if we've migrated we need to at least share the BGL to be
773 # compatible with them. Of course if we own the BGL exclusively there's no
774 # point in acquiring any other lock, unless perhaps we are half way through
775 # the migration of the current opcode.
776 assert (self._contains_BGL(level, names) or self._BGL_owned()), (
777 "You must own the Big Ganeti Lock before acquiring any other")
779 # Check we don't own locks at the same or upper levels.
780 assert not self._upper_owned(level), ("Cannot acquire locks at a level"
781 " while owning some at a greater one")
783 # Acquire the locks in the set.
784 return self.__keyring[level].acquire(names, shared=shared,
787 def release(self, level, names=None):
788 """Release a set of resource locks, at the same level.
790 You must have acquired the locks, either in shared or in exclusive mode,
791 before releasing them.
794 level: the level at which the locks shall be released.
795 It must be a memmber of LEVELS.
796 names: the names of the locks which shall be released.
797 (defaults to all the locks acquired at that level).
800 assert level in LEVELS, "Invalid locking level %s" % level
801 assert (not self._contains_BGL(level, names) or
802 not self._upper_owned(LEVEL_CLUSTER)), (
803 "Cannot release the Big Ganeti Lock while holding something"
806 # Release will complain if we don't own the locks already
807 return self.__keyring[level].release(names)
809 def add(self, level, names, acquired=0, shared=0):
810 """Add locks at the specified level.
813 level: the level at which the locks shall be added.
814 It must be a memmber of LEVELS_MOD.
815 names: names of the locks to acquire
816 acquired: whether to acquire the newly added locks
817 shared: whether the acquisition will be shared
819 assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
820 assert self._BGL_owned(), ("You must own the BGL before performing other"
822 assert not self._upper_owned(level), ("Cannot add locks at a level"
823 " while owning some at a greater one")
824 return self.__keyring[level].add(names, acquired=acquired, shared=shared)
826 def remove(self, level, names, blocking=1):
827 """Remove locks from the specified level.
829 You must either already own the locks you are trying to remove exclusively
830 or not own any lock at an upper level.
833 level: the level at which the locks shall be removed.
834 It must be a memmber of LEVELS_MOD.
835 names: the names of the locks which shall be removed.
836 (special lock names, or instance/node names)
837 blocking: whether to block while trying to operate in try-lock mode.
838 this locking mode is not supported yet.
841 assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
842 assert self._BGL_owned(), ("You must own the BGL before performing other"
844 # Check we either own the level or don't own anything from here up.
845 # LockSet.remove() will check the case in which we don't own all the needed
846 # resources, or we have a shared ownership.
847 assert self._is_owned(level) or not self._upper_owned(level), (
848 "Cannot remove locks at a level while not owning it or"
849 " owning some at a greater one")
850 return self.__keyring[level].remove(names, blocking=blocking)