Statistics
| Branch: | Tag: | Revision:

root / lib / locking.py @ 5b349fd1

History | View | Annotate | Download (40.3 kB)

1 162c1c1f Guido Trotter
#
2 162c1c1f Guido Trotter
#
3 162c1c1f Guido Trotter
4 162c1c1f Guido Trotter
# Copyright (C) 2006, 2007 Google Inc.
5 162c1c1f Guido Trotter
#
6 162c1c1f Guido Trotter
# This program is free software; you can redistribute it and/or modify
7 162c1c1f Guido Trotter
# it under the terms of the GNU General Public License as published by
8 162c1c1f Guido Trotter
# the Free Software Foundation; either version 2 of the License, or
9 162c1c1f Guido Trotter
# (at your option) any later version.
10 162c1c1f Guido Trotter
#
11 162c1c1f Guido Trotter
# This program is distributed in the hope that it will be useful, but
12 162c1c1f Guido Trotter
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 162c1c1f Guido Trotter
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 162c1c1f Guido Trotter
# General Public License for more details.
15 162c1c1f Guido Trotter
#
16 162c1c1f Guido Trotter
# You should have received a copy of the GNU General Public License
17 162c1c1f Guido Trotter
# along with this program; if not, write to the Free Software
18 162c1c1f Guido Trotter
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 162c1c1f Guido Trotter
# 02110-1301, USA.
20 162c1c1f Guido Trotter
21 162c1c1f Guido Trotter
"""Module implementing the Ganeti locking code."""
22 162c1c1f Guido Trotter
23 c70d2d9b Iustin Pop
# pylint: disable-msg=W0212
24 c70d2d9b Iustin Pop
25 c70d2d9b Iustin Pop
# W0212 since e.g. LockSet methods use (a lot) the internals of
26 c70d2d9b Iustin Pop
# SharedLock
27 162c1c1f Guido Trotter
28 d76167a5 Michael Hanselmann
import os
29 d76167a5 Michael Hanselmann
import select
30 162c1c1f Guido Trotter
import threading
31 d76167a5 Michael Hanselmann
import time
32 d76167a5 Michael Hanselmann
import errno
33 84e344d4 Michael Hanselmann
34 a95fd5d7 Guido Trotter
from ganeti import errors
35 7ee7c0c7 Guido Trotter
from ganeti import utils
36 162c1c1f Guido Trotter
37 162c1c1f Guido Trotter
38 42a999d1 Guido Trotter
def ssynchronized(lock, shared=0):
39 42a999d1 Guido Trotter
  """Shared Synchronization decorator.
40 42a999d1 Guido Trotter

41 42a999d1 Guido Trotter
  Calls the function holding the given lock, either in exclusive or shared
42 42a999d1 Guido Trotter
  mode. It requires the passed lock to be a SharedLock (or support its
43 42a999d1 Guido Trotter
  semantics).
44 42a999d1 Guido Trotter

45 42a999d1 Guido Trotter
  """
46 42a999d1 Guido Trotter
  def wrap(fn):
47 42a999d1 Guido Trotter
    def sync_function(*args, **kwargs):
48 42a999d1 Guido Trotter
      lock.acquire(shared=shared)
49 42a999d1 Guido Trotter
      try:
50 42a999d1 Guido Trotter
        return fn(*args, **kwargs)
51 42a999d1 Guido Trotter
      finally:
52 42a999d1 Guido Trotter
        lock.release()
53 42a999d1 Guido Trotter
    return sync_function
54 42a999d1 Guido Trotter
  return wrap
55 42a999d1 Guido Trotter
56 42a999d1 Guido Trotter
57 7e8841bd Michael Hanselmann
class RunningTimeout(object):
58 7e8841bd Michael Hanselmann
  """Class to calculate remaining timeout when doing several operations.
59 7e8841bd Michael Hanselmann

60 7e8841bd Michael Hanselmann
  """
61 7e8841bd Michael Hanselmann
  __slots__ = [
62 7e8841bd Michael Hanselmann
    "_allow_negative",
63 7e8841bd Michael Hanselmann
    "_start_time",
64 7e8841bd Michael Hanselmann
    "_time_fn",
65 7e8841bd Michael Hanselmann
    "_timeout",
66 7e8841bd Michael Hanselmann
    ]
67 7e8841bd Michael Hanselmann
68 7e8841bd Michael Hanselmann
  def __init__(self, timeout, allow_negative, _time_fn=time.time):
69 7e8841bd Michael Hanselmann
    """Initializes this class.
70 7e8841bd Michael Hanselmann

71 7e8841bd Michael Hanselmann
    @type timeout: float
72 7e8841bd Michael Hanselmann
    @param timeout: Timeout duration
73 7e8841bd Michael Hanselmann
    @type allow_negative: bool
74 7e8841bd Michael Hanselmann
    @param allow_negative: Whether to return values below zero
75 7e8841bd Michael Hanselmann
    @param _time_fn: Time function for unittests
76 7e8841bd Michael Hanselmann

77 7e8841bd Michael Hanselmann
    """
78 7e8841bd Michael Hanselmann
    object.__init__(self)
79 7e8841bd Michael Hanselmann
80 7e8841bd Michael Hanselmann
    if timeout is not None and timeout < 0.0:
81 7e8841bd Michael Hanselmann
      raise ValueError("Timeout must not be negative")
82 7e8841bd Michael Hanselmann
83 7e8841bd Michael Hanselmann
    self._timeout = timeout
84 7e8841bd Michael Hanselmann
    self._allow_negative = allow_negative
85 7e8841bd Michael Hanselmann
    self._time_fn = _time_fn
86 7e8841bd Michael Hanselmann
87 7e8841bd Michael Hanselmann
    self._start_time = None
88 7e8841bd Michael Hanselmann
89 7e8841bd Michael Hanselmann
  def Remaining(self):
90 7e8841bd Michael Hanselmann
    """Returns the remaining timeout.
91 7e8841bd Michael Hanselmann

92 7e8841bd Michael Hanselmann
    """
93 7e8841bd Michael Hanselmann
    if self._timeout is None:
94 7e8841bd Michael Hanselmann
      return None
95 7e8841bd Michael Hanselmann
96 7e8841bd Michael Hanselmann
    # Get start time on first calculation
97 7e8841bd Michael Hanselmann
    if self._start_time is None:
98 7e8841bd Michael Hanselmann
      self._start_time = self._time_fn()
99 7e8841bd Michael Hanselmann
100 7e8841bd Michael Hanselmann
    # Calculate remaining time
101 7e8841bd Michael Hanselmann
    remaining_timeout = self._start_time + self._timeout - self._time_fn()
102 7e8841bd Michael Hanselmann
103 7e8841bd Michael Hanselmann
    if not self._allow_negative:
104 7e8841bd Michael Hanselmann
      # Ensure timeout is always >= 0
105 7e8841bd Michael Hanselmann
      return max(0.0, remaining_timeout)
106 7e8841bd Michael Hanselmann
107 7e8841bd Michael Hanselmann
    return remaining_timeout
108 7e8841bd Michael Hanselmann
109 7e8841bd Michael Hanselmann
110 34cb5617 Guido Trotter
class _SingleNotifyPipeConditionWaiter(object):
111 34cb5617 Guido Trotter
  """Helper class for SingleNotifyPipeCondition
112 d76167a5 Michael Hanselmann

113 d76167a5 Michael Hanselmann
  """
114 d76167a5 Michael Hanselmann
  __slots__ = [
115 d76167a5 Michael Hanselmann
    "_fd",
116 d76167a5 Michael Hanselmann
    "_poller",
117 d76167a5 Michael Hanselmann
    ]
118 d76167a5 Michael Hanselmann
119 34cb5617 Guido Trotter
  def __init__(self, poller, fd):
120 34cb5617 Guido Trotter
    """Constructor for _SingleNotifyPipeConditionWaiter
121 d76167a5 Michael Hanselmann

122 d76167a5 Michael Hanselmann
    @type poller: select.poll
123 d76167a5 Michael Hanselmann
    @param poller: Poller object
124 d76167a5 Michael Hanselmann
    @type fd: int
125 d76167a5 Michael Hanselmann
    @param fd: File descriptor to wait for
126 d76167a5 Michael Hanselmann

127 d76167a5 Michael Hanselmann
    """
128 d76167a5 Michael Hanselmann
    object.__init__(self)
129 d76167a5 Michael Hanselmann
    self._poller = poller
130 d76167a5 Michael Hanselmann
    self._fd = fd
131 d76167a5 Michael Hanselmann
132 d76167a5 Michael Hanselmann
  def __call__(self, timeout):
133 d76167a5 Michael Hanselmann
    """Wait for something to happen on the pipe.
134 d76167a5 Michael Hanselmann

135 d76167a5 Michael Hanselmann
    @type timeout: float or None
136 d76167a5 Michael Hanselmann
    @param timeout: Timeout for waiting (can be None)
137 d76167a5 Michael Hanselmann

138 d76167a5 Michael Hanselmann
    """
139 f4e673fb Michael Hanselmann
    running_timeout = RunningTimeout(timeout, True)
140 f4e673fb Michael Hanselmann
141 f4e673fb Michael Hanselmann
    while True:
142 f4e673fb Michael Hanselmann
      remaining_time = running_timeout.Remaining()
143 f4e673fb Michael Hanselmann
144 b44b0141 Michael Hanselmann
      if remaining_time is not None:
145 b44b0141 Michael Hanselmann
        if remaining_time < 0.0:
146 b44b0141 Michael Hanselmann
          break
147 d76167a5 Michael Hanselmann
148 413b7472 Michael Hanselmann
        # Our calculation uses seconds, poll() wants milliseconds
149 b44b0141 Michael Hanselmann
        remaining_time *= 1000
150 d76167a5 Michael Hanselmann
151 d76167a5 Michael Hanselmann
      try:
152 d76167a5 Michael Hanselmann
        result = self._poller.poll(remaining_time)
153 d76167a5 Michael Hanselmann
      except EnvironmentError, err:
154 d76167a5 Michael Hanselmann
        if err.errno != errno.EINTR:
155 d76167a5 Michael Hanselmann
          raise
156 d76167a5 Michael Hanselmann
        result = None
157 d76167a5 Michael Hanselmann
158 d76167a5 Michael Hanselmann
      # Check whether we were notified
159 d76167a5 Michael Hanselmann
      if result and result[0][0] == self._fd:
160 d76167a5 Michael Hanselmann
        break
161 d76167a5 Michael Hanselmann
162 d76167a5 Michael Hanselmann
163 2419060d Guido Trotter
class _BaseCondition(object):
164 2419060d Guido Trotter
  """Base class containing common code for conditions.
165 2419060d Guido Trotter

166 2419060d Guido Trotter
  Some of this code is taken from python's threading module.
167 2419060d Guido Trotter

168 2419060d Guido Trotter
  """
169 2419060d Guido Trotter
  __slots__ = [
170 2419060d Guido Trotter
    "_lock",
171 2419060d Guido Trotter
    "acquire",
172 2419060d Guido Trotter
    "release",
173 2419060d Guido Trotter
    ]
174 2419060d Guido Trotter
175 2419060d Guido Trotter
  def __init__(self, lock):
176 2419060d Guido Trotter
    """Constructor for _BaseCondition.
177 2419060d Guido Trotter

178 69b99987 Michael Hanselmann
    @type lock: threading.Lock
179 2419060d Guido Trotter
    @param lock: condition base lock
180 2419060d Guido Trotter

181 2419060d Guido Trotter
    """
182 2419060d Guido Trotter
    object.__init__(self)
183 2419060d Guido Trotter
184 2419060d Guido Trotter
    # Recursive locks are not supported
185 2419060d Guido Trotter
    assert not hasattr(lock, "_acquire_restore")
186 2419060d Guido Trotter
    assert not hasattr(lock, "_release_save")
187 2419060d Guido Trotter
188 2419060d Guido Trotter
    self._lock = lock
189 2419060d Guido Trotter
190 2419060d Guido Trotter
    # Export the lock's acquire() and release() methods
191 2419060d Guido Trotter
    self.acquire = lock.acquire
192 2419060d Guido Trotter
    self.release = lock.release
193 2419060d Guido Trotter
194 2419060d Guido Trotter
  def _is_owned(self):
195 2419060d Guido Trotter
    """Check whether lock is owned by current thread.
196 2419060d Guido Trotter

197 2419060d Guido Trotter
    """
198 2419060d Guido Trotter
    if self._lock.acquire(0):
199 2419060d Guido Trotter
      self._lock.release()
200 2419060d Guido Trotter
      return False
201 2419060d Guido Trotter
202 2419060d Guido Trotter
    return True
203 2419060d Guido Trotter
204 2419060d Guido Trotter
  def _check_owned(self):
205 2419060d Guido Trotter
    """Raise an exception if the current thread doesn't own the lock.
206 2419060d Guido Trotter

207 2419060d Guido Trotter
    """
208 2419060d Guido Trotter
    if not self._is_owned():
209 2419060d Guido Trotter
      raise RuntimeError("cannot work with un-aquired lock")
210 2419060d Guido Trotter
211 2419060d Guido Trotter
212 34cb5617 Guido Trotter
class SingleNotifyPipeCondition(_BaseCondition):
213 34cb5617 Guido Trotter
  """Condition which can only be notified once.
214 d76167a5 Michael Hanselmann

215 34cb5617 Guido Trotter
  This condition class uses pipes and poll, internally, to be able to wait for
216 34cb5617 Guido Trotter
  notification with a timeout, without resorting to polling. It is almost
217 34cb5617 Guido Trotter
  compatible with Python's threading.Condition, with the following differences:
218 34cb5617 Guido Trotter
    - notifyAll can only be called once, and no wait can happen after that
219 34cb5617 Guido Trotter
    - notify is not supported, only notifyAll
220 d76167a5 Michael Hanselmann

221 d76167a5 Michael Hanselmann
  """
222 34cb5617 Guido Trotter
223 154b9580 Balazs Lecz
  __slots__ = [
224 d76167a5 Michael Hanselmann
    "_poller",
225 d76167a5 Michael Hanselmann
    "_read_fd",
226 d76167a5 Michael Hanselmann
    "_write_fd",
227 d76167a5 Michael Hanselmann
    "_nwaiters",
228 34cb5617 Guido Trotter
    "_notified",
229 d76167a5 Michael Hanselmann
    ]
230 d76167a5 Michael Hanselmann
231 34cb5617 Guido Trotter
  _waiter_class = _SingleNotifyPipeConditionWaiter
232 d76167a5 Michael Hanselmann
233 34cb5617 Guido Trotter
  def __init__(self, lock):
234 34cb5617 Guido Trotter
    """Constructor for SingleNotifyPipeCondition
235 d76167a5 Michael Hanselmann

236 d76167a5 Michael Hanselmann
    """
237 34cb5617 Guido Trotter
    _BaseCondition.__init__(self, lock)
238 d76167a5 Michael Hanselmann
    self._nwaiters = 0
239 34cb5617 Guido Trotter
    self._notified = False
240 34cb5617 Guido Trotter
    self._read_fd = None
241 34cb5617 Guido Trotter
    self._write_fd = None
242 34cb5617 Guido Trotter
    self._poller = None
243 d76167a5 Michael Hanselmann
244 34cb5617 Guido Trotter
  def _check_unnotified(self):
245 69b99987 Michael Hanselmann
    """Throws an exception if already notified.
246 69b99987 Michael Hanselmann

247 69b99987 Michael Hanselmann
    """
248 34cb5617 Guido Trotter
    if self._notified:
249 34cb5617 Guido Trotter
      raise RuntimeError("cannot use already notified condition")
250 d76167a5 Michael Hanselmann
251 34cb5617 Guido Trotter
  def _Cleanup(self):
252 34cb5617 Guido Trotter
    """Cleanup open file descriptors, if any.
253 d76167a5 Michael Hanselmann

254 d76167a5 Michael Hanselmann
    """
255 34cb5617 Guido Trotter
    if self._read_fd is not None:
256 34cb5617 Guido Trotter
      os.close(self._read_fd)
257 34cb5617 Guido Trotter
      self._read_fd = None
258 d76167a5 Michael Hanselmann
259 34cb5617 Guido Trotter
    if self._write_fd is not None:
260 34cb5617 Guido Trotter
      os.close(self._write_fd)
261 34cb5617 Guido Trotter
      self._write_fd = None
262 34cb5617 Guido Trotter
    self._poller = None
263 d76167a5 Michael Hanselmann
264 34cb5617 Guido Trotter
  def wait(self, timeout=None):
265 34cb5617 Guido Trotter
    """Wait for a notification.
266 d76167a5 Michael Hanselmann

267 34cb5617 Guido Trotter
    @type timeout: float or None
268 34cb5617 Guido Trotter
    @param timeout: Waiting timeout (can be None)
269 d76167a5 Michael Hanselmann

270 d76167a5 Michael Hanselmann
    """
271 34cb5617 Guido Trotter
    self._check_owned()
272 34cb5617 Guido Trotter
    self._check_unnotified()
273 d76167a5 Michael Hanselmann
274 34cb5617 Guido Trotter
    self._nwaiters += 1
275 34cb5617 Guido Trotter
    try:
276 34cb5617 Guido Trotter
      if self._poller is None:
277 34cb5617 Guido Trotter
        (self._read_fd, self._write_fd) = os.pipe()
278 34cb5617 Guido Trotter
        self._poller = select.poll()
279 34cb5617 Guido Trotter
        self._poller.register(self._read_fd, select.POLLHUP)
280 d76167a5 Michael Hanselmann
281 34cb5617 Guido Trotter
      wait_fn = self._waiter_class(self._poller, self._read_fd)
282 34cb5617 Guido Trotter
      self.release()
283 34cb5617 Guido Trotter
      try:
284 34cb5617 Guido Trotter
        # Wait for notification
285 34cb5617 Guido Trotter
        wait_fn(timeout)
286 34cb5617 Guido Trotter
      finally:
287 34cb5617 Guido Trotter
        # Re-acquire lock
288 34cb5617 Guido Trotter
        self.acquire()
289 34cb5617 Guido Trotter
    finally:
290 34cb5617 Guido Trotter
      self._nwaiters -= 1
291 34cb5617 Guido Trotter
      if self._nwaiters == 0:
292 34cb5617 Guido Trotter
        self._Cleanup()
293 d76167a5 Michael Hanselmann
294 7260cfbe Iustin Pop
  def notifyAll(self): # pylint: disable-msg=C0103
295 d76167a5 Michael Hanselmann
    """Close the writing side of the pipe to notify all waiters.
296 d76167a5 Michael Hanselmann

297 d76167a5 Michael Hanselmann
    """
298 34cb5617 Guido Trotter
    self._check_owned()
299 34cb5617 Guido Trotter
    self._check_unnotified()
300 34cb5617 Guido Trotter
    self._notified = True
301 d76167a5 Michael Hanselmann
    if self._write_fd is not None:
302 d76167a5 Michael Hanselmann
      os.close(self._write_fd)
303 d76167a5 Michael Hanselmann
      self._write_fd = None
304 d76167a5 Michael Hanselmann
305 d76167a5 Michael Hanselmann
306 34cb5617 Guido Trotter
class PipeCondition(_BaseCondition):
307 48dabc6a Michael Hanselmann
  """Group-only non-polling condition with counters.
308 48dabc6a Michael Hanselmann

309 48dabc6a Michael Hanselmann
  This condition class uses pipes and poll, internally, to be able to wait for
310 48dabc6a Michael Hanselmann
  notification with a timeout, without resorting to polling. It is almost
311 48dabc6a Michael Hanselmann
  compatible with Python's threading.Condition, but only supports notifyAll and
312 48dabc6a Michael Hanselmann
  non-recursive locks. As an additional features it's able to report whether
313 48dabc6a Michael Hanselmann
  there are any waiting threads.
314 48dabc6a Michael Hanselmann

315 48dabc6a Michael Hanselmann
  """
316 154b9580 Balazs Lecz
  __slots__ = [
317 48dabc6a Michael Hanselmann
    "_nwaiters",
318 34cb5617 Guido Trotter
    "_single_condition",
319 48dabc6a Michael Hanselmann
    ]
320 48dabc6a Michael Hanselmann
321 34cb5617 Guido Trotter
  _single_condition_class = SingleNotifyPipeCondition
322 48dabc6a Michael Hanselmann
323 48dabc6a Michael Hanselmann
  def __init__(self, lock):
324 48dabc6a Michael Hanselmann
    """Initializes this class.
325 48dabc6a Michael Hanselmann

326 48dabc6a Michael Hanselmann
    """
327 2419060d Guido Trotter
    _BaseCondition.__init__(self, lock)
328 48dabc6a Michael Hanselmann
    self._nwaiters = 0
329 34cb5617 Guido Trotter
    self._single_condition = self._single_condition_class(self._lock)
330 48dabc6a Michael Hanselmann
331 48dabc6a Michael Hanselmann
  def wait(self, timeout=None):
332 48dabc6a Michael Hanselmann
    """Wait for a notification.
333 48dabc6a Michael Hanselmann

334 48dabc6a Michael Hanselmann
    @type timeout: float or None
335 48dabc6a Michael Hanselmann
    @param timeout: Waiting timeout (can be None)
336 48dabc6a Michael Hanselmann

337 48dabc6a Michael Hanselmann
    """
338 48dabc6a Michael Hanselmann
    self._check_owned()
339 48dabc6a Michael Hanselmann
340 48dabc6a Michael Hanselmann
    # Keep local reference to the pipe. It could be replaced by another thread
341 48dabc6a Michael Hanselmann
    # notifying while we're waiting.
342 34cb5617 Guido Trotter
    my_condition = self._single_condition
343 48dabc6a Michael Hanselmann
344 48dabc6a Michael Hanselmann
    assert self._nwaiters >= 0
345 48dabc6a Michael Hanselmann
    self._nwaiters += 1
346 48dabc6a Michael Hanselmann
    try:
347 34cb5617 Guido Trotter
      my_condition.wait(timeout)
348 48dabc6a Michael Hanselmann
    finally:
349 48dabc6a Michael Hanselmann
      assert self._nwaiters > 0
350 48dabc6a Michael Hanselmann
      self._nwaiters -= 1
351 48dabc6a Michael Hanselmann
352 7260cfbe Iustin Pop
  def notifyAll(self): # pylint: disable-msg=C0103
353 48dabc6a Michael Hanselmann
    """Notify all currently waiting threads.
354 48dabc6a Michael Hanselmann

355 48dabc6a Michael Hanselmann
    """
356 48dabc6a Michael Hanselmann
    self._check_owned()
357 34cb5617 Guido Trotter
    self._single_condition.notifyAll()
358 34cb5617 Guido Trotter
    self._single_condition = self._single_condition_class(self._lock)
359 48dabc6a Michael Hanselmann
360 48dabc6a Michael Hanselmann
  def has_waiting(self):
361 48dabc6a Michael Hanselmann
    """Returns whether there are active waiters.
362 48dabc6a Michael Hanselmann

363 48dabc6a Michael Hanselmann
    """
364 48dabc6a Michael Hanselmann
    self._check_owned()
365 48dabc6a Michael Hanselmann
366 48dabc6a Michael Hanselmann
    return bool(self._nwaiters)
367 48dabc6a Michael Hanselmann
368 48dabc6a Michael Hanselmann
369 84e344d4 Michael Hanselmann
class _CountingCondition(object):
370 84e344d4 Michael Hanselmann
  """Wrapper for Python's built-in threading.Condition class.
371 84e344d4 Michael Hanselmann

372 84e344d4 Michael Hanselmann
  This wrapper keeps a count of active waiters. We can't access the internal
373 84e344d4 Michael Hanselmann
  "__waiters" attribute of threading.Condition because it's not thread-safe.
374 84e344d4 Michael Hanselmann

375 84e344d4 Michael Hanselmann
  """
376 84e344d4 Michael Hanselmann
  __slots__ = [
377 84e344d4 Michael Hanselmann
    "_cond",
378 84e344d4 Michael Hanselmann
    "_nwaiters",
379 84e344d4 Michael Hanselmann
    ]
380 84e344d4 Michael Hanselmann
381 84e344d4 Michael Hanselmann
  def __init__(self, lock):
382 84e344d4 Michael Hanselmann
    """Initializes this class.
383 84e344d4 Michael Hanselmann

384 84e344d4 Michael Hanselmann
    """
385 84e344d4 Michael Hanselmann
    object.__init__(self)
386 84e344d4 Michael Hanselmann
    self._cond = threading.Condition(lock=lock)
387 84e344d4 Michael Hanselmann
    self._nwaiters = 0
388 84e344d4 Michael Hanselmann
389 7260cfbe Iustin Pop
  def notifyAll(self): # pylint: disable-msg=C0103
390 84e344d4 Michael Hanselmann
    """Notifies the condition.
391 84e344d4 Michael Hanselmann

392 84e344d4 Michael Hanselmann
    """
393 84e344d4 Michael Hanselmann
    return self._cond.notifyAll()
394 84e344d4 Michael Hanselmann
395 84e344d4 Michael Hanselmann
  def wait(self, timeout=None):
396 84e344d4 Michael Hanselmann
    """Waits for the condition to be notified.
397 84e344d4 Michael Hanselmann

398 84e344d4 Michael Hanselmann
    @type timeout: float or None
399 34cb5617 Guido Trotter
    @param timeout: Waiting timeout (can be None)
400 84e344d4 Michael Hanselmann

401 84e344d4 Michael Hanselmann
    """
402 84e344d4 Michael Hanselmann
    assert self._nwaiters >= 0
403 84e344d4 Michael Hanselmann
404 84e344d4 Michael Hanselmann
    self._nwaiters += 1
405 84e344d4 Michael Hanselmann
    try:
406 84e344d4 Michael Hanselmann
      return self._cond.wait(timeout=timeout)
407 84e344d4 Michael Hanselmann
    finally:
408 84e344d4 Michael Hanselmann
      self._nwaiters -= 1
409 84e344d4 Michael Hanselmann
410 84e344d4 Michael Hanselmann
  def has_waiting(self):
411 84e344d4 Michael Hanselmann
    """Returns whether there are active waiters.
412 84e344d4 Michael Hanselmann

413 84e344d4 Michael Hanselmann
    """
414 84e344d4 Michael Hanselmann
    return bool(self._nwaiters)
415 84e344d4 Michael Hanselmann
416 84e344d4 Michael Hanselmann
417 84e344d4 Michael Hanselmann
class SharedLock(object):
418 162c1c1f Guido Trotter
  """Implements a shared lock.
419 162c1c1f Guido Trotter

420 162c1c1f Guido Trotter
  Multiple threads can acquire the lock in a shared way, calling
421 162c1c1f Guido Trotter
  acquire_shared().  In order to acquire the lock in an exclusive way threads
422 162c1c1f Guido Trotter
  can call acquire_exclusive().
423 162c1c1f Guido Trotter

424 162c1c1f Guido Trotter
  The lock prevents starvation but does not guarantee that threads will acquire
425 162c1c1f Guido Trotter
  the shared lock in the order they queued for it, just that they will
426 162c1c1f Guido Trotter
  eventually do so.
427 162c1c1f Guido Trotter

428 162c1c1f Guido Trotter
  """
429 84e344d4 Michael Hanselmann
  __slots__ = [
430 84e344d4 Michael Hanselmann
    "__active_shr_c",
431 84e344d4 Michael Hanselmann
    "__inactive_shr_c",
432 84e344d4 Michael Hanselmann
    "__deleted",
433 84e344d4 Michael Hanselmann
    "__exc",
434 84e344d4 Michael Hanselmann
    "__lock",
435 84e344d4 Michael Hanselmann
    "__pending",
436 84e344d4 Michael Hanselmann
    "__shr",
437 84e344d4 Michael Hanselmann
    ]
438 84e344d4 Michael Hanselmann
439 34cb5617 Guido Trotter
  __condition_class = PipeCondition
440 84e344d4 Michael Hanselmann
441 162c1c1f Guido Trotter
  def __init__(self):
442 84e344d4 Michael Hanselmann
    """Construct a new SharedLock.
443 84e344d4 Michael Hanselmann

444 84e344d4 Michael Hanselmann
    """
445 84e344d4 Michael Hanselmann
    object.__init__(self)
446 84e344d4 Michael Hanselmann
447 84e344d4 Michael Hanselmann
    # Internal lock
448 162c1c1f Guido Trotter
    self.__lock = threading.Lock()
449 162c1c1f Guido Trotter
450 84e344d4 Michael Hanselmann
    # Queue containing waiting acquires
451 84e344d4 Michael Hanselmann
    self.__pending = []
452 84e344d4 Michael Hanselmann
453 84e344d4 Michael Hanselmann
    # Active and inactive conditions for shared locks
454 84e344d4 Michael Hanselmann
    self.__active_shr_c = self.__condition_class(self.__lock)
455 84e344d4 Michael Hanselmann
    self.__inactive_shr_c = self.__condition_class(self.__lock)
456 84e344d4 Michael Hanselmann
457 84e344d4 Michael Hanselmann
    # Current lock holders
458 162c1c1f Guido Trotter
    self.__shr = set()
459 162c1c1f Guido Trotter
    self.__exc = None
460 162c1c1f Guido Trotter
461 a95fd5d7 Guido Trotter
    # is this lock in the deleted state?
462 a95fd5d7 Guido Trotter
    self.__deleted = False
463 a95fd5d7 Guido Trotter
464 84e344d4 Michael Hanselmann
  def __check_deleted(self):
465 84e344d4 Michael Hanselmann
    """Raises an exception if the lock has been deleted.
466 84e344d4 Michael Hanselmann

467 84e344d4 Michael Hanselmann
    """
468 84e344d4 Michael Hanselmann
    if self.__deleted:
469 84e344d4 Michael Hanselmann
      raise errors.LockError("Deleted lock")
470 84e344d4 Michael Hanselmann
471 162c1c1f Guido Trotter
  def __is_sharer(self):
472 84e344d4 Michael Hanselmann
    """Is the current thread sharing the lock at this time?
473 84e344d4 Michael Hanselmann

474 84e344d4 Michael Hanselmann
    """
475 162c1c1f Guido Trotter
    return threading.currentThread() in self.__shr
476 162c1c1f Guido Trotter
477 162c1c1f Guido Trotter
  def __is_exclusive(self):
478 84e344d4 Michael Hanselmann
    """Is the current thread holding the lock exclusively at this time?
479 84e344d4 Michael Hanselmann

480 84e344d4 Michael Hanselmann
    """
481 162c1c1f Guido Trotter
    return threading.currentThread() == self.__exc
482 162c1c1f Guido Trotter
483 162c1c1f Guido Trotter
  def __is_owned(self, shared=-1):
484 162c1c1f Guido Trotter
    """Is the current thread somehow owning the lock at this time?
485 162c1c1f Guido Trotter

486 162c1c1f Guido Trotter
    This is a private version of the function, which presumes you're holding
487 162c1c1f Guido Trotter
    the internal lock.
488 162c1c1f Guido Trotter

489 162c1c1f Guido Trotter
    """
490 162c1c1f Guido Trotter
    if shared < 0:
491 162c1c1f Guido Trotter
      return self.__is_sharer() or self.__is_exclusive()
492 162c1c1f Guido Trotter
    elif shared:
493 162c1c1f Guido Trotter
      return self.__is_sharer()
494 162c1c1f Guido Trotter
    else:
495 162c1c1f Guido Trotter
      return self.__is_exclusive()
496 162c1c1f Guido Trotter
497 162c1c1f Guido Trotter
  def _is_owned(self, shared=-1):
498 162c1c1f Guido Trotter
    """Is the current thread somehow owning the lock at this time?
499 162c1c1f Guido Trotter

500 c41eea6e Iustin Pop
    @param shared:
501 c41eea6e Iustin Pop
        - < 0: check for any type of ownership (default)
502 c41eea6e Iustin Pop
        - 0: check for exclusive ownership
503 c41eea6e Iustin Pop
        - > 0: check for shared ownership
504 162c1c1f Guido Trotter

505 162c1c1f Guido Trotter
    """
506 162c1c1f Guido Trotter
    self.__lock.acquire()
507 162c1c1f Guido Trotter
    try:
508 84e344d4 Michael Hanselmann
      return self.__is_owned(shared=shared)
509 162c1c1f Guido Trotter
    finally:
510 162c1c1f Guido Trotter
      self.__lock.release()
511 162c1c1f Guido Trotter
512 84e344d4 Michael Hanselmann
  def _count_pending(self):
513 84e344d4 Michael Hanselmann
    """Returns the number of pending acquires.
514 a95fd5d7 Guido Trotter

515 84e344d4 Michael Hanselmann
    @rtype: int
516 a95fd5d7 Guido Trotter

517 a95fd5d7 Guido Trotter
    """
518 84e344d4 Michael Hanselmann
    self.__lock.acquire()
519 84e344d4 Michael Hanselmann
    try:
520 84e344d4 Michael Hanselmann
      return len(self.__pending)
521 84e344d4 Michael Hanselmann
    finally:
522 84e344d4 Michael Hanselmann
      self.__lock.release()
523 a95fd5d7 Guido Trotter
524 84e344d4 Michael Hanselmann
  def __do_acquire(self, shared):
525 84e344d4 Michael Hanselmann
    """Actually acquire the lock.
526 84e344d4 Michael Hanselmann

527 84e344d4 Michael Hanselmann
    """
528 84e344d4 Michael Hanselmann
    if shared:
529 84e344d4 Michael Hanselmann
      self.__shr.add(threading.currentThread())
530 84e344d4 Michael Hanselmann
    else:
531 84e344d4 Michael Hanselmann
      self.__exc = threading.currentThread()
532 a95fd5d7 Guido Trotter
533 84e344d4 Michael Hanselmann
  def __can_acquire(self, shared):
534 84e344d4 Michael Hanselmann
    """Determine whether lock can be acquired.
535 a95fd5d7 Guido Trotter

536 a95fd5d7 Guido Trotter
    """
537 84e344d4 Michael Hanselmann
    if shared:
538 84e344d4 Michael Hanselmann
      return self.__exc is None
539 84e344d4 Michael Hanselmann
    else:
540 84e344d4 Michael Hanselmann
      return len(self.__shr) == 0 and self.__exc is None
541 a95fd5d7 Guido Trotter
542 84e344d4 Michael Hanselmann
  def __is_on_top(self, cond):
543 84e344d4 Michael Hanselmann
    """Checks whether the passed condition is on top of the queue.
544 a95fd5d7 Guido Trotter

545 84e344d4 Michael Hanselmann
    The caller must make sure the queue isn't empty.
546 a95fd5d7 Guido Trotter

547 84e344d4 Michael Hanselmann
    """
548 84e344d4 Michael Hanselmann
    return self.__pending[0] == cond
549 4d686df8 Guido Trotter
550 a66bd91b Michael Hanselmann
  def __acquire_unlocked(self, shared, timeout):
551 84e344d4 Michael Hanselmann
    """Acquire a shared lock.
552 9216a9f7 Michael Hanselmann

553 84e344d4 Michael Hanselmann
    @param shared: whether to acquire in shared mode; by default an
554 84e344d4 Michael Hanselmann
        exclusive lock will be acquired
555 84e344d4 Michael Hanselmann
    @param timeout: maximum waiting time before giving up
556 9216a9f7 Michael Hanselmann

557 9216a9f7 Michael Hanselmann
    """
558 84e344d4 Michael Hanselmann
    self.__check_deleted()
559 9216a9f7 Michael Hanselmann
560 84e344d4 Michael Hanselmann
    # We cannot acquire the lock if we already have it
561 84e344d4 Michael Hanselmann
    assert not self.__is_owned(), "double acquire() on a non-recursive lock"
562 84e344d4 Michael Hanselmann
563 84e344d4 Michael Hanselmann
    # Check whether someone else holds the lock or there are pending acquires.
564 84e344d4 Michael Hanselmann
    if not self.__pending and self.__can_acquire(shared):
565 84e344d4 Michael Hanselmann
      # Apparently not, can acquire lock directly.
566 84e344d4 Michael Hanselmann
      self.__do_acquire(shared)
567 84e344d4 Michael Hanselmann
      return True
568 9216a9f7 Michael Hanselmann
569 84e344d4 Michael Hanselmann
    if shared:
570 84e344d4 Michael Hanselmann
      wait_condition = self.__active_shr_c
571 9216a9f7 Michael Hanselmann
572 84e344d4 Michael Hanselmann
      # Check if we're not yet in the queue
573 84e344d4 Michael Hanselmann
      if wait_condition not in self.__pending:
574 84e344d4 Michael Hanselmann
        self.__pending.append(wait_condition)
575 84e344d4 Michael Hanselmann
    else:
576 84e344d4 Michael Hanselmann
      wait_condition = self.__condition_class(self.__lock)
577 84e344d4 Michael Hanselmann
      # Always add to queue
578 84e344d4 Michael Hanselmann
      self.__pending.append(wait_condition)
579 84e344d4 Michael Hanselmann
580 84e344d4 Michael Hanselmann
    try:
581 84e344d4 Michael Hanselmann
      # Wait until we become the topmost acquire in the queue or the timeout
582 84e344d4 Michael Hanselmann
      # expires.
583 84e344d4 Michael Hanselmann
      while not (self.__is_on_top(wait_condition) and
584 84e344d4 Michael Hanselmann
                 self.__can_acquire(shared)):
585 84e344d4 Michael Hanselmann
        # Wait for notification
586 84e344d4 Michael Hanselmann
        wait_condition.wait(timeout)
587 84e344d4 Michael Hanselmann
        self.__check_deleted()
588 84e344d4 Michael Hanselmann
589 84e344d4 Michael Hanselmann
        # A lot of code assumes blocking acquires always succeed. Loop
590 84e344d4 Michael Hanselmann
        # internally for that case.
591 84e344d4 Michael Hanselmann
        if timeout is not None:
592 84e344d4 Michael Hanselmann
          break
593 84e344d4 Michael Hanselmann
594 84e344d4 Michael Hanselmann
      if self.__is_on_top(wait_condition) and self.__can_acquire(shared):
595 84e344d4 Michael Hanselmann
        self.__do_acquire(shared)
596 84e344d4 Michael Hanselmann
        return True
597 9216a9f7 Michael Hanselmann
    finally:
598 84e344d4 Michael Hanselmann
      # Remove condition from queue if there are no more waiters
599 84e344d4 Michael Hanselmann
      if not wait_condition.has_waiting() and not self.__deleted:
600 84e344d4 Michael Hanselmann
        self.__pending.remove(wait_condition)
601 9216a9f7 Michael Hanselmann
602 84e344d4 Michael Hanselmann
    return False
603 9216a9f7 Michael Hanselmann
604 008b92fa Michael Hanselmann
  def acquire(self, shared=0, timeout=None, test_notify=None):
605 162c1c1f Guido Trotter
    """Acquire a shared lock.
606 162c1c1f Guido Trotter

607 ec44d893 Guido Trotter
    @type shared: integer (0/1) used as a boolean
608 c41eea6e Iustin Pop
    @param shared: whether to acquire in shared mode; by default an
609 c41eea6e Iustin Pop
        exclusive lock will be acquired
610 84e344d4 Michael Hanselmann
    @type timeout: float
611 84e344d4 Michael Hanselmann
    @param timeout: maximum waiting time before giving up
612 008b92fa Michael Hanselmann
    @type test_notify: callable or None
613 008b92fa Michael Hanselmann
    @param test_notify: Special callback function for unittesting
614 162c1c1f Guido Trotter

615 162c1c1f Guido Trotter
    """
616 162c1c1f Guido Trotter
    self.__lock.acquire()
617 162c1c1f Guido Trotter
    try:
618 008b92fa Michael Hanselmann
      # We already got the lock, notify now
619 008b92fa Michael Hanselmann
      if __debug__ and callable(test_notify):
620 008b92fa Michael Hanselmann
        test_notify()
621 008b92fa Michael Hanselmann
622 84e344d4 Michael Hanselmann
      return self.__acquire_unlocked(shared, timeout)
623 162c1c1f Guido Trotter
    finally:
624 162c1c1f Guido Trotter
      self.__lock.release()
625 162c1c1f Guido Trotter
626 162c1c1f Guido Trotter
  def release(self):
627 162c1c1f Guido Trotter
    """Release a Shared Lock.
628 162c1c1f Guido Trotter

629 162c1c1f Guido Trotter
    You must have acquired the lock, either in shared or in exclusive mode,
630 162c1c1f Guido Trotter
    before calling this function.
631 162c1c1f Guido Trotter

632 162c1c1f Guido Trotter
    """
633 162c1c1f Guido Trotter
    self.__lock.acquire()
634 162c1c1f Guido Trotter
    try:
635 84e344d4 Michael Hanselmann
      assert self.__is_exclusive() or self.__is_sharer(), \
636 84e344d4 Michael Hanselmann
        "Cannot release non-owned lock"
637 84e344d4 Michael Hanselmann
638 162c1c1f Guido Trotter
      # Autodetect release type
639 162c1c1f Guido Trotter
      if self.__is_exclusive():
640 162c1c1f Guido Trotter
        self.__exc = None
641 84e344d4 Michael Hanselmann
      else:
642 162c1c1f Guido Trotter
        self.__shr.remove(threading.currentThread())
643 162c1c1f Guido Trotter
644 84e344d4 Michael Hanselmann
      # Notify topmost condition in queue
645 84e344d4 Michael Hanselmann
      if self.__pending:
646 84e344d4 Michael Hanselmann
        first_condition = self.__pending[0]
647 84e344d4 Michael Hanselmann
        first_condition.notifyAll()
648 4d686df8 Guido Trotter
649 84e344d4 Michael Hanselmann
        if first_condition == self.__active_shr_c:
650 84e344d4 Michael Hanselmann
          self.__active_shr_c = self.__inactive_shr_c
651 84e344d4 Michael Hanselmann
          self.__inactive_shr_c = first_condition
652 162c1c1f Guido Trotter
653 162c1c1f Guido Trotter
    finally:
654 162c1c1f Guido Trotter
      self.__lock.release()
655 162c1c1f Guido Trotter
656 84e344d4 Michael Hanselmann
  def delete(self, timeout=None):
657 a95fd5d7 Guido Trotter
    """Delete a Shared Lock.
658 a95fd5d7 Guido Trotter

659 a95fd5d7 Guido Trotter
    This operation will declare the lock for removal. First the lock will be
660 a95fd5d7 Guido Trotter
    acquired in exclusive mode if you don't already own it, then the lock
661 a95fd5d7 Guido Trotter
    will be put in a state where any future and pending acquire() fail.
662 a95fd5d7 Guido Trotter

663 84e344d4 Michael Hanselmann
    @type timeout: float
664 84e344d4 Michael Hanselmann
    @param timeout: maximum waiting time before giving up
665 a95fd5d7 Guido Trotter

666 a95fd5d7 Guido Trotter
    """
667 a95fd5d7 Guido Trotter
    self.__lock.acquire()
668 a95fd5d7 Guido Trotter
    try:
669 84e344d4 Michael Hanselmann
      assert not self.__is_sharer(), "Cannot delete() a lock while sharing it"
670 84e344d4 Michael Hanselmann
671 84e344d4 Michael Hanselmann
      self.__check_deleted()
672 a95fd5d7 Guido Trotter
673 84e344d4 Michael Hanselmann
      # The caller is allowed to hold the lock exclusively already.
674 84e344d4 Michael Hanselmann
      acquired = self.__is_exclusive()
675 a95fd5d7 Guido Trotter
676 84e344d4 Michael Hanselmann
      if not acquired:
677 a66bd91b Michael Hanselmann
        acquired = self.__acquire_unlocked(0, timeout)
678 a66bd91b Michael Hanselmann
679 a66bd91b Michael Hanselmann
        assert self.__is_exclusive() and not self.__is_sharer(), \
680 a66bd91b Michael Hanselmann
          "Lock wasn't acquired in exclusive mode"
681 84e344d4 Michael Hanselmann
682 84e344d4 Michael Hanselmann
      if acquired:
683 84e344d4 Michael Hanselmann
        self.__deleted = True
684 84e344d4 Michael Hanselmann
        self.__exc = None
685 a95fd5d7 Guido Trotter
686 84e344d4 Michael Hanselmann
        # Notify all acquires. They'll throw an error.
687 84e344d4 Michael Hanselmann
        while self.__pending:
688 84e344d4 Michael Hanselmann
          self.__pending.pop().notifyAll()
689 a95fd5d7 Guido Trotter
690 84e344d4 Michael Hanselmann
      return acquired
691 a95fd5d7 Guido Trotter
    finally:
692 a95fd5d7 Guido Trotter
      self.__lock.release()
693 a95fd5d7 Guido Trotter
694 aaae9bc0 Guido Trotter
695 f12eadb3 Iustin Pop
# Whenever we want to acquire a full LockSet we pass None as the value
696 5bbd3f7f Michael Hanselmann
# to acquire.  Hide this behind this nicely named constant.
697 e310b019 Guido Trotter
ALL_SET = None
698 e310b019 Guido Trotter
699 e310b019 Guido Trotter
700 5aab242c Michael Hanselmann
class _AcquireTimeout(Exception):
701 5aab242c Michael Hanselmann
  """Internal exception to abort an acquire on a timeout.
702 5aab242c Michael Hanselmann

703 5aab242c Michael Hanselmann
  """
704 5aab242c Michael Hanselmann
705 5aab242c Michael Hanselmann
706 aaae9bc0 Guido Trotter
class LockSet:
707 aaae9bc0 Guido Trotter
  """Implements a set of locks.
708 aaae9bc0 Guido Trotter

709 aaae9bc0 Guido Trotter
  This abstraction implements a set of shared locks for the same resource type,
710 aaae9bc0 Guido Trotter
  distinguished by name. The user can lock a subset of the resources and the
711 aaae9bc0 Guido Trotter
  LockSet will take care of acquiring the locks always in the same order, thus
712 aaae9bc0 Guido Trotter
  preventing deadlock.
713 aaae9bc0 Guido Trotter

714 aaae9bc0 Guido Trotter
  All the locks needed in the same set must be acquired together, though.
715 aaae9bc0 Guido Trotter

716 aaae9bc0 Guido Trotter
  """
717 aaae9bc0 Guido Trotter
  def __init__(self, members=None):
718 aaae9bc0 Guido Trotter
    """Constructs a new LockSet.
719 aaae9bc0 Guido Trotter

720 ec44d893 Guido Trotter
    @type members: list of strings
721 c41eea6e Iustin Pop
    @param members: initial members of the set
722 aaae9bc0 Guido Trotter

723 aaae9bc0 Guido Trotter
    """
724 aaae9bc0 Guido Trotter
    # Used internally to guarantee coherency.
725 aaae9bc0 Guido Trotter
    self.__lock = SharedLock()
726 aaae9bc0 Guido Trotter
727 aaae9bc0 Guido Trotter
    # The lockdict indexes the relationship name -> lock
728 aaae9bc0 Guido Trotter
    # The order-of-locking is implied by the alphabetical order of names
729 aaae9bc0 Guido Trotter
    self.__lockdict = {}
730 aaae9bc0 Guido Trotter
731 aaae9bc0 Guido Trotter
    if members is not None:
732 aaae9bc0 Guido Trotter
      for name in members:
733 aaae9bc0 Guido Trotter
        self.__lockdict[name] = SharedLock()
734 aaae9bc0 Guido Trotter
735 aaae9bc0 Guido Trotter
    # The owner dict contains the set of locks each thread owns. For
736 aaae9bc0 Guido Trotter
    # performance each thread can access its own key without a global lock on
737 aaae9bc0 Guido Trotter
    # this structure. It is paramount though that *no* other type of access is
738 aaae9bc0 Guido Trotter
    # done to this structure (eg. no looping over its keys). *_owner helper
739 aaae9bc0 Guido Trotter
    # function are defined to guarantee access is correct, but in general never
740 aaae9bc0 Guido Trotter
    # do anything different than __owners[threading.currentThread()], or there
741 aaae9bc0 Guido Trotter
    # will be trouble.
742 aaae9bc0 Guido Trotter
    self.__owners = {}
743 aaae9bc0 Guido Trotter
744 aaae9bc0 Guido Trotter
  def _is_owned(self):
745 aaae9bc0 Guido Trotter
    """Is the current thread a current level owner?"""
746 aaae9bc0 Guido Trotter
    return threading.currentThread() in self.__owners
747 aaae9bc0 Guido Trotter
748 b2dabfd6 Guido Trotter
  def _add_owned(self, name=None):
749 aaae9bc0 Guido Trotter
    """Note the current thread owns the given lock"""
750 b2dabfd6 Guido Trotter
    if name is None:
751 b2dabfd6 Guido Trotter
      if not self._is_owned():
752 b2dabfd6 Guido Trotter
        self.__owners[threading.currentThread()] = set()
753 aaae9bc0 Guido Trotter
    else:
754 b2dabfd6 Guido Trotter
      if self._is_owned():
755 b2dabfd6 Guido Trotter
        self.__owners[threading.currentThread()].add(name)
756 b2dabfd6 Guido Trotter
      else:
757 b2dabfd6 Guido Trotter
        self.__owners[threading.currentThread()] = set([name])
758 b2dabfd6 Guido Trotter
759 b2dabfd6 Guido Trotter
  def _del_owned(self, name=None):
760 aaae9bc0 Guido Trotter
    """Note the current thread owns the given lock"""
761 aaae9bc0 Guido Trotter
762 e4335b5b Michael Hanselmann
    assert not (name is None and self.__lock._is_owned()), \
763 e4335b5b Michael Hanselmann
           "Cannot hold internal lock when deleting owner status"
764 e4335b5b Michael Hanselmann
765 b2dabfd6 Guido Trotter
    if name is not None:
766 b2dabfd6 Guido Trotter
      self.__owners[threading.currentThread()].remove(name)
767 b2dabfd6 Guido Trotter
768 b2dabfd6 Guido Trotter
    # Only remove the key if we don't hold the set-lock as well
769 b2dabfd6 Guido Trotter
    if (not self.__lock._is_owned() and
770 b2dabfd6 Guido Trotter
        not self.__owners[threading.currentThread()]):
771 aaae9bc0 Guido Trotter
      del self.__owners[threading.currentThread()]
772 aaae9bc0 Guido Trotter
773 aaae9bc0 Guido Trotter
  def _list_owned(self):
774 aaae9bc0 Guido Trotter
    """Get the set of resource names owned by the current thread"""
775 aaae9bc0 Guido Trotter
    if self._is_owned():
776 aaae9bc0 Guido Trotter
      return self.__owners[threading.currentThread()].copy()
777 aaae9bc0 Guido Trotter
    else:
778 aaae9bc0 Guido Trotter
      return set()
779 aaae9bc0 Guido Trotter
780 5aab242c Michael Hanselmann
  def _release_and_delete_owned(self):
781 5aab242c Michael Hanselmann
    """Release and delete all resources owned by the current thread"""
782 5aab242c Michael Hanselmann
    for lname in self._list_owned():
783 56452af7 Michael Hanselmann
      lock = self.__lockdict[lname]
784 56452af7 Michael Hanselmann
      if lock._is_owned():
785 56452af7 Michael Hanselmann
        lock.release()
786 5aab242c Michael Hanselmann
      self._del_owned(name=lname)
787 5aab242c Michael Hanselmann
788 aaae9bc0 Guido Trotter
  def __names(self):
789 aaae9bc0 Guido Trotter
    """Return the current set of names.
790 aaae9bc0 Guido Trotter

791 aaae9bc0 Guido Trotter
    Only call this function while holding __lock and don't iterate on the
792 aaae9bc0 Guido Trotter
    result after releasing the lock.
793 aaae9bc0 Guido Trotter

794 aaae9bc0 Guido Trotter
    """
795 0cf257c5 Guido Trotter
    return self.__lockdict.keys()
796 aaae9bc0 Guido Trotter
797 aaae9bc0 Guido Trotter
  def _names(self):
798 aaae9bc0 Guido Trotter
    """Return a copy of the current set of elements.
799 aaae9bc0 Guido Trotter

800 aaae9bc0 Guido Trotter
    Used only for debugging purposes.
801 cdb08f44 Michael Hanselmann

802 aaae9bc0 Guido Trotter
    """
803 d4803c24 Guido Trotter
    # If we don't already own the set-level lock acquired
804 d4803c24 Guido Trotter
    # we'll get it and note we need to release it later.
805 d4803c24 Guido Trotter
    release_lock = False
806 d4803c24 Guido Trotter
    if not self.__lock._is_owned():
807 d4803c24 Guido Trotter
      release_lock = True
808 d4803c24 Guido Trotter
      self.__lock.acquire(shared=1)
809 aaae9bc0 Guido Trotter
    try:
810 aaae9bc0 Guido Trotter
      result = self.__names()
811 aaae9bc0 Guido Trotter
    finally:
812 d4803c24 Guido Trotter
      if release_lock:
813 d4803c24 Guido Trotter
        self.__lock.release()
814 0cf257c5 Guido Trotter
    return set(result)
815 aaae9bc0 Guido Trotter
816 5aab242c Michael Hanselmann
  def acquire(self, names, timeout=None, shared=0, test_notify=None):
817 aaae9bc0 Guido Trotter
    """Acquire a set of resource locks.
818 aaae9bc0 Guido Trotter

819 ec44d893 Guido Trotter
    @type names: list of strings (or string)
820 c41eea6e Iustin Pop
    @param names: the names of the locks which shall be acquired
821 c41eea6e Iustin Pop
        (special lock names, or instance/node names)
822 ec44d893 Guido Trotter
    @type shared: integer (0/1) used as a boolean
823 c41eea6e Iustin Pop
    @param shared: whether to acquire in shared mode; by default an
824 c41eea6e Iustin Pop
        exclusive lock will be acquired
825 5aab242c Michael Hanselmann
    @type timeout: float or None
826 5e0a6daf Michael Hanselmann
    @param timeout: Maximum time to acquire all locks
827 5aab242c Michael Hanselmann
    @type test_notify: callable or None
828 5aab242c Michael Hanselmann
    @param test_notify: Special callback function for unittesting
829 aaae9bc0 Guido Trotter

830 5aab242c Michael Hanselmann
    @return: Set of all locks successfully acquired or None in case of timeout
831 aaae9bc0 Guido Trotter

832 c41eea6e Iustin Pop
    @raise errors.LockError: when any lock we try to acquire has
833 c41eea6e Iustin Pop
        been deleted before we succeed. In this case none of the
834 c41eea6e Iustin Pop
        locks requested will be acquired.
835 aaae9bc0 Guido Trotter

836 aaae9bc0 Guido Trotter
    """
837 5aab242c Michael Hanselmann
    assert timeout is None or timeout >= 0.0
838 aaae9bc0 Guido Trotter
839 aaae9bc0 Guido Trotter
    # Check we don't already own locks at this level
840 aaae9bc0 Guido Trotter
    assert not self._is_owned(), "Cannot acquire locks in the same set twice"
841 aaae9bc0 Guido Trotter
842 5aab242c Michael Hanselmann
    # We need to keep track of how long we spent waiting for a lock. The
843 5aab242c Michael Hanselmann
    # timeout passed to this function is over all lock acquires.
844 7e8841bd Michael Hanselmann
    running_timeout = RunningTimeout(timeout, False)
845 5aab242c Michael Hanselmann
846 806e20fd Guido Trotter
    try:
847 76e2f08a Michael Hanselmann
      if names is not None:
848 5aab242c Michael Hanselmann
        # Support passing in a single resource to acquire rather than many
849 5aab242c Michael Hanselmann
        if isinstance(names, basestring):
850 5aab242c Michael Hanselmann
          names = [names]
851 5aab242c Michael Hanselmann
852 76e2f08a Michael Hanselmann
        return self.__acquire_inner(names, False, shared,
853 7e8841bd Michael Hanselmann
                                    running_timeout.Remaining, test_notify)
854 76e2f08a Michael Hanselmann
855 76e2f08a Michael Hanselmann
      else:
856 76e2f08a Michael Hanselmann
        # If no names are given acquire the whole set by not letting new names
857 76e2f08a Michael Hanselmann
        # being added before we release, and getting the current list of names.
858 76e2f08a Michael Hanselmann
        # Some of them may then be deleted later, but we'll cope with this.
859 76e2f08a Michael Hanselmann
        #
860 76e2f08a Michael Hanselmann
        # We'd like to acquire this lock in a shared way, as it's nice if
861 76e2f08a Michael Hanselmann
        # everybody else can use the instances at the same time. If are
862 76e2f08a Michael Hanselmann
        # acquiring them exclusively though they won't be able to do this
863 76e2f08a Michael Hanselmann
        # anyway, though, so we'll get the list lock exclusively as well in
864 76e2f08a Michael Hanselmann
        # order to be able to do add() on the set while owning it.
865 76e2f08a Michael Hanselmann
        if not self.__lock.acquire(shared=shared,
866 7e8841bd Michael Hanselmann
                                   timeout=running_timeout.Remaining()):
867 76e2f08a Michael Hanselmann
          raise _AcquireTimeout()
868 76e2f08a Michael Hanselmann
        try:
869 76e2f08a Michael Hanselmann
          # note we own the set-lock
870 76e2f08a Michael Hanselmann
          self._add_owned()
871 76e2f08a Michael Hanselmann
872 76e2f08a Michael Hanselmann
          return self.__acquire_inner(self.__names(), True, shared,
873 7e8841bd Michael Hanselmann
                                      running_timeout.Remaining, test_notify)
874 76e2f08a Michael Hanselmann
        except:
875 76e2f08a Michael Hanselmann
          # We shouldn't have problems adding the lock to the owners list, but
876 76e2f08a Michael Hanselmann
          # if we did we'll try to release this lock and re-raise exception.
877 76e2f08a Michael Hanselmann
          # Of course something is going to be really wrong, after this.
878 5aab242c Michael Hanselmann
          self.__lock.release()
879 76e2f08a Michael Hanselmann
          self._del_owned()
880 76e2f08a Michael Hanselmann
          raise
881 5aab242c Michael Hanselmann
882 5aab242c Michael Hanselmann
    except _AcquireTimeout:
883 5aab242c Michael Hanselmann
      return None
884 aaae9bc0 Guido Trotter
885 76e2f08a Michael Hanselmann
  def __acquire_inner(self, names, want_all, shared, timeout_fn, test_notify):
886 7e8841bd Michael Hanselmann
    """Inner logic for acquiring a number of locks.
887 7e8841bd Michael Hanselmann

888 7e8841bd Michael Hanselmann
    @param names: Names of the locks to be acquired
889 7e8841bd Michael Hanselmann
    @param want_all: Whether all locks in the set should be acquired
890 7e8841bd Michael Hanselmann
    @param shared: Whether to acquire in shared mode
891 7e8841bd Michael Hanselmann
    @param timeout_fn: Function returning remaining timeout
892 7e8841bd Michael Hanselmann
    @param test_notify: Special callback function for unittesting
893 76e2f08a Michael Hanselmann

894 76e2f08a Michael Hanselmann
    """
895 76e2f08a Michael Hanselmann
    acquire_list = []
896 76e2f08a Michael Hanselmann
897 76e2f08a Michael Hanselmann
    # First we look the locks up on __lockdict. We have no way of being sure
898 76e2f08a Michael Hanselmann
    # they will still be there after, but this makes it a lot faster should
899 71e1863e Michael Hanselmann
    # just one of them be the already wrong. Using a sorted sequence to prevent
900 71e1863e Michael Hanselmann
    # deadlocks.
901 71e1863e Michael Hanselmann
    for lname in sorted(utils.UniqueSequence(names)):
902 76e2f08a Michael Hanselmann
      try:
903 76e2f08a Michael Hanselmann
        lock = self.__lockdict[lname] # raises KeyError if lock is not there
904 76e2f08a Michael Hanselmann
      except KeyError:
905 76e2f08a Michael Hanselmann
        if want_all:
906 76e2f08a Michael Hanselmann
          # We are acquiring all the set, it doesn't matter if this particular
907 76e2f08a Michael Hanselmann
          # element is not there anymore.
908 76e2f08a Michael Hanselmann
          continue
909 76e2f08a Michael Hanselmann
910 76e2f08a Michael Hanselmann
        raise errors.LockError("Non-existing lock in set (%s)" % lname)
911 76e2f08a Michael Hanselmann
912 9b154270 Michael Hanselmann
      acquire_list.append((lname, lock))
913 9b154270 Michael Hanselmann
914 76e2f08a Michael Hanselmann
    # This will hold the locknames we effectively acquired.
915 76e2f08a Michael Hanselmann
    acquired = set()
916 76e2f08a Michael Hanselmann
917 76e2f08a Michael Hanselmann
    try:
918 76e2f08a Michael Hanselmann
      # Now acquire_list contains a sorted list of resources and locks we
919 76e2f08a Michael Hanselmann
      # want.  In order to get them we loop on this (private) list and
920 76e2f08a Michael Hanselmann
      # acquire() them.  We gave no real guarantee they will still exist till
921 76e2f08a Michael Hanselmann
      # this is done but .acquire() itself is safe and will alert us if the
922 76e2f08a Michael Hanselmann
      # lock gets deleted.
923 76e2f08a Michael Hanselmann
      for (lname, lock) in acquire_list:
924 76e2f08a Michael Hanselmann
        if __debug__ and callable(test_notify):
925 76e2f08a Michael Hanselmann
          test_notify_fn = lambda: test_notify(lname)
926 76e2f08a Michael Hanselmann
        else:
927 76e2f08a Michael Hanselmann
          test_notify_fn = None
928 76e2f08a Michael Hanselmann
929 76e2f08a Michael Hanselmann
        timeout = timeout_fn()
930 76e2f08a Michael Hanselmann
931 76e2f08a Michael Hanselmann
        try:
932 76e2f08a Michael Hanselmann
          # raises LockError if the lock was deleted
933 76e2f08a Michael Hanselmann
          acq_success = lock.acquire(shared=shared, timeout=timeout,
934 76e2f08a Michael Hanselmann
                                     test_notify=test_notify_fn)
935 76e2f08a Michael Hanselmann
        except errors.LockError:
936 76e2f08a Michael Hanselmann
          if want_all:
937 76e2f08a Michael Hanselmann
            # We are acquiring all the set, it doesn't matter if this
938 76e2f08a Michael Hanselmann
            # particular element is not there anymore.
939 76e2f08a Michael Hanselmann
            continue
940 76e2f08a Michael Hanselmann
941 76e2f08a Michael Hanselmann
          raise errors.LockError("Non-existing lock in set (%s)" % lname)
942 76e2f08a Michael Hanselmann
943 76e2f08a Michael Hanselmann
        if not acq_success:
944 76e2f08a Michael Hanselmann
          # Couldn't get lock or timeout occurred
945 76e2f08a Michael Hanselmann
          if timeout is None:
946 76e2f08a Michael Hanselmann
            # This shouldn't happen as SharedLock.acquire(timeout=None) is
947 76e2f08a Michael Hanselmann
            # blocking.
948 76e2f08a Michael Hanselmann
            raise errors.LockError("Failed to get lock %s" % lname)
949 76e2f08a Michael Hanselmann
950 76e2f08a Michael Hanselmann
          raise _AcquireTimeout()
951 76e2f08a Michael Hanselmann
952 76e2f08a Michael Hanselmann
        try:
953 76e2f08a Michael Hanselmann
          # now the lock cannot be deleted, we have it!
954 76e2f08a Michael Hanselmann
          self._add_owned(name=lname)
955 76e2f08a Michael Hanselmann
          acquired.add(lname)
956 76e2f08a Michael Hanselmann
957 76e2f08a Michael Hanselmann
        except:
958 76e2f08a Michael Hanselmann
          # We shouldn't have problems adding the lock to the owners list, but
959 76e2f08a Michael Hanselmann
          # if we did we'll try to release this lock and re-raise exception.
960 76e2f08a Michael Hanselmann
          # Of course something is going to be really wrong after this.
961 76e2f08a Michael Hanselmann
          if lock._is_owned():
962 76e2f08a Michael Hanselmann
            lock.release()
963 76e2f08a Michael Hanselmann
          raise
964 76e2f08a Michael Hanselmann
965 76e2f08a Michael Hanselmann
    except:
966 76e2f08a Michael Hanselmann
      # Release all owned locks
967 76e2f08a Michael Hanselmann
      self._release_and_delete_owned()
968 76e2f08a Michael Hanselmann
      raise
969 76e2f08a Michael Hanselmann
970 0cc00929 Guido Trotter
    return acquired
971 aaae9bc0 Guido Trotter
972 aaae9bc0 Guido Trotter
  def release(self, names=None):
973 aaae9bc0 Guido Trotter
    """Release a set of resource locks, at the same level.
974 aaae9bc0 Guido Trotter

975 aaae9bc0 Guido Trotter
    You must have acquired the locks, either in shared or in exclusive mode,
976 aaae9bc0 Guido Trotter
    before releasing them.
977 aaae9bc0 Guido Trotter

978 ec44d893 Guido Trotter
    @type names: list of strings, or None
979 c41eea6e Iustin Pop
    @param names: the names of the locks which shall be released
980 c41eea6e Iustin Pop
        (defaults to all the locks acquired at that level).
981 aaae9bc0 Guido Trotter

982 aaae9bc0 Guido Trotter
    """
983 aaae9bc0 Guido Trotter
    assert self._is_owned(), "release() on lock set while not owner"
984 aaae9bc0 Guido Trotter
985 aaae9bc0 Guido Trotter
    # Support passing in a single resource to release rather than many
986 aaae9bc0 Guido Trotter
    if isinstance(names, basestring):
987 aaae9bc0 Guido Trotter
      names = [names]
988 aaae9bc0 Guido Trotter
989 aaae9bc0 Guido Trotter
    if names is None:
990 aaae9bc0 Guido Trotter
      names = self._list_owned()
991 aaae9bc0 Guido Trotter
    else:
992 aaae9bc0 Guido Trotter
      names = set(names)
993 aaae9bc0 Guido Trotter
      assert self._list_owned().issuperset(names), (
994 aaae9bc0 Guido Trotter
               "release() on unheld resources %s" %
995 aaae9bc0 Guido Trotter
               names.difference(self._list_owned()))
996 aaae9bc0 Guido Trotter
997 3b7ed473 Guido Trotter
    # First of all let's release the "all elements" lock, if set.
998 3b7ed473 Guido Trotter
    # After this 'add' can work again
999 3b7ed473 Guido Trotter
    if self.__lock._is_owned():
1000 3b7ed473 Guido Trotter
      self.__lock.release()
1001 b2dabfd6 Guido Trotter
      self._del_owned()
1002 3b7ed473 Guido Trotter
1003 aaae9bc0 Guido Trotter
    for lockname in names:
1004 aaae9bc0 Guido Trotter
      # If we are sure the lock doesn't leave __lockdict without being
1005 aaae9bc0 Guido Trotter
      # exclusively held we can do this...
1006 aaae9bc0 Guido Trotter
      self.__lockdict[lockname].release()
1007 b2dabfd6 Guido Trotter
      self._del_owned(name=lockname)
1008 aaae9bc0 Guido Trotter
1009 aaae9bc0 Guido Trotter
  def add(self, names, acquired=0, shared=0):
1010 aaae9bc0 Guido Trotter
    """Add a new set of elements to the set
1011 aaae9bc0 Guido Trotter

1012 ec44d893 Guido Trotter
    @type names: list of strings
1013 c41eea6e Iustin Pop
    @param names: names of the new elements to add
1014 ec44d893 Guido Trotter
    @type acquired: integer (0/1) used as a boolean
1015 c41eea6e Iustin Pop
    @param acquired: pre-acquire the new resource?
1016 ec44d893 Guido Trotter
    @type shared: integer (0/1) used as a boolean
1017 c41eea6e Iustin Pop
    @param shared: is the pre-acquisition shared?
1018 aaae9bc0 Guido Trotter

1019 aaae9bc0 Guido Trotter
    """
1020 d2aff862 Guido Trotter
    # Check we don't already own locks at this level
1021 d2aff862 Guido Trotter
    assert not self._is_owned() or self.__lock._is_owned(shared=0), \
1022 d2aff862 Guido Trotter
      "Cannot add locks if the set is only partially owned, or shared"
1023 3b7ed473 Guido Trotter
1024 aaae9bc0 Guido Trotter
    # Support passing in a single resource to add rather than many
1025 aaae9bc0 Guido Trotter
    if isinstance(names, basestring):
1026 aaae9bc0 Guido Trotter
      names = [names]
1027 aaae9bc0 Guido Trotter
1028 ab62526c Guido Trotter
    # If we don't already own the set-level lock acquired in an exclusive way
1029 3b7ed473 Guido Trotter
    # we'll get it and note we need to release it later.
1030 3b7ed473 Guido Trotter
    release_lock = False
1031 3b7ed473 Guido Trotter
    if not self.__lock._is_owned():
1032 3b7ed473 Guido Trotter
      release_lock = True
1033 3b7ed473 Guido Trotter
      self.__lock.acquire()
1034 3b7ed473 Guido Trotter
1035 aaae9bc0 Guido Trotter
    try:
1036 0cf257c5 Guido Trotter
      invalid_names = set(self.__names()).intersection(names)
1037 aaae9bc0 Guido Trotter
      if invalid_names:
1038 aaae9bc0 Guido Trotter
        # This must be an explicit raise, not an assert, because assert is
1039 aaae9bc0 Guido Trotter
        # turned off when using optimization, and this can happen because of
1040 aaae9bc0 Guido Trotter
        # concurrency even if the user doesn't want it.
1041 aaae9bc0 Guido Trotter
        raise errors.LockError("duplicate add() (%s)" % invalid_names)
1042 aaae9bc0 Guido Trotter
1043 aaae9bc0 Guido Trotter
      for lockname in names:
1044 aaae9bc0 Guido Trotter
        lock = SharedLock()
1045 aaae9bc0 Guido Trotter
1046 aaae9bc0 Guido Trotter
        if acquired:
1047 aaae9bc0 Guido Trotter
          lock.acquire(shared=shared)
1048 aaae9bc0 Guido Trotter
          # now the lock cannot be deleted, we have it!
1049 aaae9bc0 Guido Trotter
          try:
1050 b2dabfd6 Guido Trotter
            self._add_owned(name=lockname)
1051 aaae9bc0 Guido Trotter
          except:
1052 aaae9bc0 Guido Trotter
            # We shouldn't have problems adding the lock to the owners list,
1053 aaae9bc0 Guido Trotter
            # but if we did we'll try to release this lock and re-raise
1054 aaae9bc0 Guido Trotter
            # exception.  Of course something is going to be really wrong,
1055 aaae9bc0 Guido Trotter
            # after this.  On the other hand the lock hasn't been added to the
1056 aaae9bc0 Guido Trotter
            # __lockdict yet so no other threads should be pending on it. This
1057 aaae9bc0 Guido Trotter
            # release is just a safety measure.
1058 aaae9bc0 Guido Trotter
            lock.release()
1059 aaae9bc0 Guido Trotter
            raise
1060 aaae9bc0 Guido Trotter
1061 aaae9bc0 Guido Trotter
        self.__lockdict[lockname] = lock
1062 aaae9bc0 Guido Trotter
1063 aaae9bc0 Guido Trotter
    finally:
1064 3b7ed473 Guido Trotter
      # Only release __lock if we were not holding it previously.
1065 3b7ed473 Guido Trotter
      if release_lock:
1066 3b7ed473 Guido Trotter
        self.__lock.release()
1067 aaae9bc0 Guido Trotter
1068 aaae9bc0 Guido Trotter
    return True
1069 aaae9bc0 Guido Trotter
1070 5e0a6daf Michael Hanselmann
  def remove(self, names):
1071 aaae9bc0 Guido Trotter
    """Remove elements from the lock set.
1072 aaae9bc0 Guido Trotter

1073 aaae9bc0 Guido Trotter
    You can either not hold anything in the lockset or already hold a superset
1074 aaae9bc0 Guido Trotter
    of the elements you want to delete, exclusively.
1075 aaae9bc0 Guido Trotter

1076 ec44d893 Guido Trotter
    @type names: list of strings
1077 c41eea6e Iustin Pop
    @param names: names of the resource to remove.
1078 aaae9bc0 Guido Trotter

1079 5aab242c Michael Hanselmann
    @return: a list of locks which we removed; the list is always
1080 c41eea6e Iustin Pop
        equal to the names list if we were holding all the locks
1081 c41eea6e Iustin Pop
        exclusively
1082 aaae9bc0 Guido Trotter

1083 aaae9bc0 Guido Trotter
    """
1084 aaae9bc0 Guido Trotter
    # Support passing in a single resource to remove rather than many
1085 aaae9bc0 Guido Trotter
    if isinstance(names, basestring):
1086 aaae9bc0 Guido Trotter
      names = [names]
1087 aaae9bc0 Guido Trotter
1088 aaae9bc0 Guido Trotter
    # If we own any subset of this lock it must be a superset of what we want
1089 aaae9bc0 Guido Trotter
    # to delete. The ownership must also be exclusive, but that will be checked
1090 aaae9bc0 Guido Trotter
    # by the lock itself.
1091 aaae9bc0 Guido Trotter
    assert not self._is_owned() or self._list_owned().issuperset(names), (
1092 aaae9bc0 Guido Trotter
      "remove() on acquired lockset while not owning all elements")
1093 aaae9bc0 Guido Trotter
1094 3f404fc5 Guido Trotter
    removed = []
1095 aaae9bc0 Guido Trotter
1096 aaae9bc0 Guido Trotter
    for lname in names:
1097 aaae9bc0 Guido Trotter
      # Calling delete() acquires the lock exclusively if we don't already own
1098 aaae9bc0 Guido Trotter
      # it, and causes all pending and subsequent lock acquires to fail. It's
1099 aaae9bc0 Guido Trotter
      # fine to call it out of order because delete() also implies release(),
1100 aaae9bc0 Guido Trotter
      # and the assertion above guarantees that if we either already hold
1101 aaae9bc0 Guido Trotter
      # everything we want to delete, or we hold none.
1102 aaae9bc0 Guido Trotter
      try:
1103 aaae9bc0 Guido Trotter
        self.__lockdict[lname].delete()
1104 3f404fc5 Guido Trotter
        removed.append(lname)
1105 aaae9bc0 Guido Trotter
      except (KeyError, errors.LockError):
1106 aaae9bc0 Guido Trotter
        # This cannot happen if we were already holding it, verify:
1107 aaae9bc0 Guido Trotter
        assert not self._is_owned(), "remove failed while holding lockset"
1108 aaae9bc0 Guido Trotter
      else:
1109 aaae9bc0 Guido Trotter
        # If no LockError was raised we are the ones who deleted the lock.
1110 aaae9bc0 Guido Trotter
        # This means we can safely remove it from lockdict, as any further or
1111 aaae9bc0 Guido Trotter
        # pending delete() or acquire() will fail (and nobody can have the lock
1112 aaae9bc0 Guido Trotter
        # since before our call to delete()).
1113 aaae9bc0 Guido Trotter
        #
1114 aaae9bc0 Guido Trotter
        # This is done in an else clause because if the exception was thrown
1115 aaae9bc0 Guido Trotter
        # it's the job of the one who actually deleted it.
1116 aaae9bc0 Guido Trotter
        del self.__lockdict[lname]
1117 aaae9bc0 Guido Trotter
        # And let's remove it from our private list if we owned it.
1118 aaae9bc0 Guido Trotter
        if self._is_owned():
1119 b2dabfd6 Guido Trotter
          self._del_owned(name=lname)
1120 aaae9bc0 Guido Trotter
1121 3f404fc5 Guido Trotter
    return removed
1122 aaae9bc0 Guido Trotter
1123 7ee7c0c7 Guido Trotter
1124 7ee7c0c7 Guido Trotter
# Locking levels, must be acquired in increasing order.
1125 7ee7c0c7 Guido Trotter
# Current rules are:
1126 7ee7c0c7 Guido Trotter
#   - at level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
1127 7ee7c0c7 Guido Trotter
#   acquired before performing any operation, either in shared or in exclusive
1128 7ee7c0c7 Guido Trotter
#   mode. acquiring the BGL in exclusive mode is discouraged and should be
1129 7ee7c0c7 Guido Trotter
#   avoided.
1130 7ee7c0c7 Guido Trotter
#   - at levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks.
1131 7ee7c0c7 Guido Trotter
#   If you need more than one node, or more than one instance, acquire them at
1132 7ee7c0c7 Guido Trotter
#   the same time.
1133 7ee7c0c7 Guido Trotter
LEVEL_CLUSTER = 0
1134 04e1bfaf Guido Trotter
LEVEL_INSTANCE = 1
1135 04e1bfaf Guido Trotter
LEVEL_NODE = 2
1136 7ee7c0c7 Guido Trotter
1137 7ee7c0c7 Guido Trotter
LEVELS = [LEVEL_CLUSTER,
1138 04e1bfaf Guido Trotter
          LEVEL_INSTANCE,
1139 04e1bfaf Guido Trotter
          LEVEL_NODE]
1140 7ee7c0c7 Guido Trotter
1141 7ee7c0c7 Guido Trotter
# Lock levels which are modifiable
1142 7ee7c0c7 Guido Trotter
LEVELS_MOD = [LEVEL_NODE, LEVEL_INSTANCE]
1143 7ee7c0c7 Guido Trotter
1144 ea205dbc Michael Hanselmann
LEVEL_NAMES = {
1145 ea205dbc Michael Hanselmann
  LEVEL_CLUSTER: "cluster",
1146 ea205dbc Michael Hanselmann
  LEVEL_INSTANCE: "instance",
1147 ea205dbc Michael Hanselmann
  LEVEL_NODE: "node",
1148 ea205dbc Michael Hanselmann
  }
1149 ea205dbc Michael Hanselmann
1150 08a6c581 Guido Trotter
# Constant for the big ganeti lock
1151 7ee7c0c7 Guido Trotter
BGL = 'BGL'
1152 7ee7c0c7 Guido Trotter
1153 7ee7c0c7 Guido Trotter
1154 7ee7c0c7 Guido Trotter
class GanetiLockManager:
1155 7ee7c0c7 Guido Trotter
  """The Ganeti Locking Library
1156 7ee7c0c7 Guido Trotter

1157 5bbd3f7f Michael Hanselmann
  The purpose of this small library is to manage locking for ganeti clusters
1158 7ee7c0c7 Guido Trotter
  in a central place, while at the same time doing dynamic checks against
1159 7ee7c0c7 Guido Trotter
  possible deadlocks. It will also make it easier to transition to a different
1160 7ee7c0c7 Guido Trotter
  lock type should we migrate away from python threads.
1161 7ee7c0c7 Guido Trotter

1162 7ee7c0c7 Guido Trotter
  """
1163 7ee7c0c7 Guido Trotter
  _instance = None
1164 7ee7c0c7 Guido Trotter
1165 7ee7c0c7 Guido Trotter
  def __init__(self, nodes=None, instances=None):
1166 7ee7c0c7 Guido Trotter
    """Constructs a new GanetiLockManager object.
1167 7ee7c0c7 Guido Trotter

1168 4e07ec8c Guido Trotter
    There should be only a GanetiLockManager object at any time, so this
1169 4e07ec8c Guido Trotter
    function raises an error if this is not the case.
1170 7ee7c0c7 Guido Trotter

1171 c41eea6e Iustin Pop
    @param nodes: list of node names
1172 c41eea6e Iustin Pop
    @param instances: list of instance names
1173 7ee7c0c7 Guido Trotter

1174 7ee7c0c7 Guido Trotter
    """
1175 c41eea6e Iustin Pop
    assert self.__class__._instance is None, \
1176 c41eea6e Iustin Pop
           "double GanetiLockManager instance"
1177 c41eea6e Iustin Pop
1178 7ee7c0c7 Guido Trotter
    self.__class__._instance = self
1179 7ee7c0c7 Guido Trotter
1180 7ee7c0c7 Guido Trotter
    # The keyring contains all the locks, at their level and in the correct
1181 7ee7c0c7 Guido Trotter
    # locking order.
1182 7ee7c0c7 Guido Trotter
    self.__keyring = {
1183 7ee7c0c7 Guido Trotter
      LEVEL_CLUSTER: LockSet([BGL]),
1184 7ee7c0c7 Guido Trotter
      LEVEL_NODE: LockSet(nodes),
1185 7ee7c0c7 Guido Trotter
      LEVEL_INSTANCE: LockSet(instances),
1186 7ee7c0c7 Guido Trotter
    }
1187 7ee7c0c7 Guido Trotter
1188 7ee7c0c7 Guido Trotter
  def _names(self, level):
1189 7ee7c0c7 Guido Trotter
    """List the lock names at the given level.
1190 7ee7c0c7 Guido Trotter

1191 c41eea6e Iustin Pop
    This can be used for debugging/testing purposes.
1192 c41eea6e Iustin Pop

1193 c41eea6e Iustin Pop
    @param level: the level whose list of locks to get
1194 7ee7c0c7 Guido Trotter

1195 7ee7c0c7 Guido Trotter
    """
1196 7ee7c0c7 Guido Trotter
    assert level in LEVELS, "Invalid locking level %s" % level
1197 7ee7c0c7 Guido Trotter
    return self.__keyring[level]._names()
1198 7ee7c0c7 Guido Trotter
1199 7ee7c0c7 Guido Trotter
  def _is_owned(self, level):
1200 7ee7c0c7 Guido Trotter
    """Check whether we are owning locks at the given level
1201 7ee7c0c7 Guido Trotter

1202 7ee7c0c7 Guido Trotter
    """
1203 7ee7c0c7 Guido Trotter
    return self.__keyring[level]._is_owned()
1204 7ee7c0c7 Guido Trotter
1205 d4f4b3e7 Guido Trotter
  is_owned = _is_owned
1206 d4f4b3e7 Guido Trotter
1207 7ee7c0c7 Guido Trotter
  def _list_owned(self, level):
1208 7ee7c0c7 Guido Trotter
    """Get the set of owned locks at the given level
1209 7ee7c0c7 Guido Trotter

1210 7ee7c0c7 Guido Trotter
    """
1211 7ee7c0c7 Guido Trotter
    return self.__keyring[level]._list_owned()
1212 7ee7c0c7 Guido Trotter
1213 7ee7c0c7 Guido Trotter
  def _upper_owned(self, level):
1214 7ee7c0c7 Guido Trotter
    """Check that we don't own any lock at a level greater than the given one.
1215 7ee7c0c7 Guido Trotter

1216 7ee7c0c7 Guido Trotter
    """
1217 7ee7c0c7 Guido Trotter
    # This way of checking only works if LEVELS[i] = i, which we check for in
1218 7ee7c0c7 Guido Trotter
    # the test cases.
1219 7ee7c0c7 Guido Trotter
    return utils.any((self._is_owned(l) for l in LEVELS[level + 1:]))
1220 7ee7c0c7 Guido Trotter
1221 fe267188 Iustin Pop
  def _BGL_owned(self): # pylint: disable-msg=C0103
1222 7ee7c0c7 Guido Trotter
    """Check if the current thread owns the BGL.
1223 7ee7c0c7 Guido Trotter

1224 7ee7c0c7 Guido Trotter
    Both an exclusive or a shared acquisition work.
1225 7ee7c0c7 Guido Trotter

1226 7ee7c0c7 Guido Trotter
    """
1227 7ee7c0c7 Guido Trotter
    return BGL in self.__keyring[LEVEL_CLUSTER]._list_owned()
1228 7ee7c0c7 Guido Trotter
1229 c70d2d9b Iustin Pop
  @staticmethod
1230 c70d2d9b Iustin Pop
  def _contains_BGL(level, names): # pylint: disable-msg=C0103
1231 c41eea6e Iustin Pop
    """Check if the level contains the BGL.
1232 c41eea6e Iustin Pop

1233 c41eea6e Iustin Pop
    Check if acting on the given level and set of names will change
1234 c41eea6e Iustin Pop
    the status of the Big Ganeti Lock.
1235 7ee7c0c7 Guido Trotter

1236 7ee7c0c7 Guido Trotter
    """
1237 7ee7c0c7 Guido Trotter
    return level == LEVEL_CLUSTER and (names is None or BGL in names)
1238 7ee7c0c7 Guido Trotter
1239 5e0a6daf Michael Hanselmann
  def acquire(self, level, names, timeout=None, shared=0):
1240 7ee7c0c7 Guido Trotter
    """Acquire a set of resource locks, at the same level.
1241 7ee7c0c7 Guido Trotter

1242 ec44d893 Guido Trotter
    @type level: member of locking.LEVELS
1243 ec44d893 Guido Trotter
    @param level: the level at which the locks shall be acquired
1244 ec44d893 Guido Trotter
    @type names: list of strings (or string)
1245 c41eea6e Iustin Pop
    @param names: the names of the locks which shall be acquired
1246 c41eea6e Iustin Pop
        (special lock names, or instance/node names)
1247 ec44d893 Guido Trotter
    @type shared: integer (0/1) used as a boolean
1248 c41eea6e Iustin Pop
    @param shared: whether to acquire in shared mode; by default
1249 c41eea6e Iustin Pop
        an exclusive lock will be acquired
1250 5e0a6daf Michael Hanselmann
    @type timeout: float
1251 5e0a6daf Michael Hanselmann
    @param timeout: Maximum time to acquire all locks
1252 7ee7c0c7 Guido Trotter

1253 7ee7c0c7 Guido Trotter
    """
1254 7ee7c0c7 Guido Trotter
    assert level in LEVELS, "Invalid locking level %s" % level
1255 7ee7c0c7 Guido Trotter
1256 7ee7c0c7 Guido Trotter
    # Check that we are either acquiring the Big Ganeti Lock or we already own
1257 7ee7c0c7 Guido Trotter
    # it. Some "legacy" opcodes need to be sure they are run non-concurrently
1258 7ee7c0c7 Guido Trotter
    # so even if we've migrated we need to at least share the BGL to be
1259 7ee7c0c7 Guido Trotter
    # compatible with them. Of course if we own the BGL exclusively there's no
1260 7ee7c0c7 Guido Trotter
    # point in acquiring any other lock, unless perhaps we are half way through
1261 7ee7c0c7 Guido Trotter
    # the migration of the current opcode.
1262 7ee7c0c7 Guido Trotter
    assert (self._contains_BGL(level, names) or self._BGL_owned()), (
1263 7ee7c0c7 Guido Trotter
            "You must own the Big Ganeti Lock before acquiring any other")
1264 7ee7c0c7 Guido Trotter
1265 7ee7c0c7 Guido Trotter
    # Check we don't own locks at the same or upper levels.
1266 21a6c826 Guido Trotter
    assert not self._upper_owned(level), ("Cannot acquire locks at a level"
1267 7ee7c0c7 Guido Trotter
           " while owning some at a greater one")
1268 7ee7c0c7 Guido Trotter
1269 7ee7c0c7 Guido Trotter
    # Acquire the locks in the set.
1270 5e0a6daf Michael Hanselmann
    return self.__keyring[level].acquire(names, shared=shared, timeout=timeout)
1271 7ee7c0c7 Guido Trotter
1272 7ee7c0c7 Guido Trotter
  def release(self, level, names=None):
1273 7ee7c0c7 Guido Trotter
    """Release a set of resource locks, at the same level.
1274 7ee7c0c7 Guido Trotter

1275 c41eea6e Iustin Pop
    You must have acquired the locks, either in shared or in exclusive
1276 c41eea6e Iustin Pop
    mode, before releasing them.
1277 7ee7c0c7 Guido Trotter

1278 ec44d893 Guido Trotter
    @type level: member of locking.LEVELS
1279 ec44d893 Guido Trotter
    @param level: the level at which the locks shall be released
1280 ec44d893 Guido Trotter
    @type names: list of strings, or None
1281 c41eea6e Iustin Pop
    @param names: the names of the locks which shall be released
1282 c41eea6e Iustin Pop
        (defaults to all the locks acquired at that level)
1283 7ee7c0c7 Guido Trotter

1284 7ee7c0c7 Guido Trotter
    """
1285 7ee7c0c7 Guido Trotter
    assert level in LEVELS, "Invalid locking level %s" % level
1286 7ee7c0c7 Guido Trotter
    assert (not self._contains_BGL(level, names) or
1287 7ee7c0c7 Guido Trotter
            not self._upper_owned(LEVEL_CLUSTER)), (
1288 7ee7c0c7 Guido Trotter
            "Cannot release the Big Ganeti Lock while holding something"
1289 e4335b5b Michael Hanselmann
            " at upper levels (%r)" %
1290 1f864b60 Iustin Pop
            (utils.CommaJoin(["%s=%r" % (LEVEL_NAMES[i], self._list_owned(i))
1291 1f864b60 Iustin Pop
                              for i in self.__keyring.keys()]), ))
1292 7ee7c0c7 Guido Trotter
1293 7ee7c0c7 Guido Trotter
    # Release will complain if we don't own the locks already
1294 7ee7c0c7 Guido Trotter
    return self.__keyring[level].release(names)
1295 7ee7c0c7 Guido Trotter
1296 7ee7c0c7 Guido Trotter
  def add(self, level, names, acquired=0, shared=0):
1297 7ee7c0c7 Guido Trotter
    """Add locks at the specified level.
1298 7ee7c0c7 Guido Trotter

1299 ec44d893 Guido Trotter
    @type level: member of locking.LEVELS_MOD
1300 ec44d893 Guido Trotter
    @param level: the level at which the locks shall be added
1301 ec44d893 Guido Trotter
    @type names: list of strings
1302 c41eea6e Iustin Pop
    @param names: names of the locks to acquire
1303 ec44d893 Guido Trotter
    @type acquired: integer (0/1) used as a boolean
1304 c41eea6e Iustin Pop
    @param acquired: whether to acquire the newly added locks
1305 ec44d893 Guido Trotter
    @type shared: integer (0/1) used as a boolean
1306 c41eea6e Iustin Pop
    @param shared: whether the acquisition will be shared
1307 c41eea6e Iustin Pop

1308 7ee7c0c7 Guido Trotter
    """
1309 7ee7c0c7 Guido Trotter
    assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
1310 7ee7c0c7 Guido Trotter
    assert self._BGL_owned(), ("You must own the BGL before performing other"
1311 7ee7c0c7 Guido Trotter
           " operations")
1312 7ee7c0c7 Guido Trotter
    assert not self._upper_owned(level), ("Cannot add locks at a level"
1313 7ee7c0c7 Guido Trotter
           " while owning some at a greater one")
1314 7ee7c0c7 Guido Trotter
    return self.__keyring[level].add(names, acquired=acquired, shared=shared)
1315 7ee7c0c7 Guido Trotter
1316 5e0a6daf Michael Hanselmann
  def remove(self, level, names):
1317 7ee7c0c7 Guido Trotter
    """Remove locks from the specified level.
1318 7ee7c0c7 Guido Trotter

1319 c41eea6e Iustin Pop
    You must either already own the locks you are trying to remove
1320 c41eea6e Iustin Pop
    exclusively or not own any lock at an upper level.
1321 7ee7c0c7 Guido Trotter

1322 ec44d893 Guido Trotter
    @type level: member of locking.LEVELS_MOD
1323 ec44d893 Guido Trotter
    @param level: the level at which the locks shall be removed
1324 ec44d893 Guido Trotter
    @type names: list of strings
1325 c41eea6e Iustin Pop
    @param names: the names of the locks which shall be removed
1326 c41eea6e Iustin Pop
        (special lock names, or instance/node names)
1327 7ee7c0c7 Guido Trotter

1328 7ee7c0c7 Guido Trotter
    """
1329 7ee7c0c7 Guido Trotter
    assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
1330 7ee7c0c7 Guido Trotter
    assert self._BGL_owned(), ("You must own the BGL before performing other"
1331 7ee7c0c7 Guido Trotter
           " operations")
1332 f12eadb3 Iustin Pop
    # Check we either own the level or don't own anything from here
1333 f12eadb3 Iustin Pop
    # up. LockSet.remove() will check the case in which we don't own
1334 f12eadb3 Iustin Pop
    # all the needed resources, or we have a shared ownership.
1335 7ee7c0c7 Guido Trotter
    assert self._is_owned(level) or not self._upper_owned(level), (
1336 7ee7c0c7 Guido Trotter
           "Cannot remove locks at a level while not owning it or"
1337 7ee7c0c7 Guido Trotter
           " owning some at a greater one")
1338 5e0a6daf Michael Hanselmann
    return self.__keyring[level].remove(names)