locking.py 7.74 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#
#

# Copyright (C) 2006, 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.

"""Module implementing the Ganeti locking code."""

# pylint: disable-msg=W0613,W0201

import threading
26
27
28
# Wouldn't it be better to define LockingError in the locking module?
# Well, for now that's how the rest of the code does it...
from ganeti import errors
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43


class SharedLock:
  """Implements a shared lock.

  Multiple threads can acquire the lock in a shared way, calling
  acquire_shared().  In order to acquire the lock in an exclusive way threads
  can call acquire_exclusive().

  The lock prevents starvation but does not guarantee that threads will acquire
  the shared lock in the order they queued for it, just that they will
  eventually do so.

  """
  def __init__(self):
44
    """Construct a new SharedLock"""
45
46
47
48
49
50
51
52
53
54
55
56
57
    # we have two conditions, c_shr and c_exc, sharing the same lock.
    self.__lock = threading.Lock()
    self.__turn_shr = threading.Condition(self.__lock)
    self.__turn_exc = threading.Condition(self.__lock)

    # current lock holders
    self.__shr = set()
    self.__exc = None

    # lock waiters
    self.__nwait_exc = 0
    self.__nwait_shr = 0

58
59
60
    # is this lock in the deleted state?
    self.__deleted = False

61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
  def __is_sharer(self):
    """Is the current thread sharing the lock at this time?"""
    return threading.currentThread() in self.__shr

  def __is_exclusive(self):
    """Is the current thread holding the lock exclusively at this time?"""
    return threading.currentThread() == self.__exc

  def __is_owned(self, shared=-1):
    """Is the current thread somehow owning the lock at this time?

    This is a private version of the function, which presumes you're holding
    the internal lock.

    """
    if shared < 0:
      return self.__is_sharer() or self.__is_exclusive()
    elif shared:
      return self.__is_sharer()
    else:
      return self.__is_exclusive()

  def _is_owned(self, shared=-1):
    """Is the current thread somehow owning the lock at this time?

    Args:
      shared:
        < 0: check for any type of ownership (default)
        0: check for exclusive ownership
        > 0: check for shared ownership

    """
    self.__lock.acquire()
    try:
      result = self.__is_owned(shared)
    finally:
      self.__lock.release()

    return result

101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
  def __wait(self,c):
    """Wait on the given condition, and raise an exception if the current lock
    is declared deleted in the meantime.

    Args:
      c: condition to wait on

    """
    c.wait()
    if self.__deleted:
      raise errors.LockError('deleted lock')

  def __exclusive_acquire(self):
    """Acquire the lock exclusively.

    This is a private function that presumes you are already holding the
    internal lock. It's defined separately to avoid code duplication between
    acquire() and delete()

    """
    self.__nwait_exc += 1
    try:
      # This is to save ourselves from a nasty race condition that could
      # theoretically make the sharers starve.
      if self.__nwait_shr > 0 or self.__nwait_exc > 1:
        self.__wait(self.__turn_exc)

      while len(self.__shr) > 0 or self.__exc is not None:
        self.__wait(self.__turn_exc)

      self.__exc = threading.currentThread()
    finally:
      self.__nwait_exc -= 1


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
  def acquire(self, blocking=1, shared=0):
    """Acquire a shared lock.

    Args:
      shared: whether to acquire in shared mode. By default an exclusive lock
              will be acquired.
      blocking: whether to block while trying to acquire or to operate in try-lock mode.
                this locking mode is not supported yet.

    """
    if not blocking:
      # We don't have non-blocking mode for now
      raise NotImplementedError

    self.__lock.acquire()
    try:
152
153
154
      if self.__deleted:
        raise errors.LockError('deleted lock')

155
156
157
158
159
160
161
162
163
164
165
      # We cannot acquire the lock if we already have it
      assert not self.__is_owned(), "double acquire() on a non-recursive lock"

      if shared:
        self.__nwait_shr += 1
        try:
          # If there is an exclusive holder waiting we have to wait.  We'll
          # only do this once, though, when we start waiting for the lock. Then
          # we'll just wait while there are no exclusive holders.
          if self.__nwait_exc > 0:
            # TODO: if !blocking...
166
            self.__wait(self.__turn_shr)
167
168
169

          while self.__exc is not None:
            # TODO: if !blocking...
170
            self.__wait(self.__turn_shr)
171
172
173
174
175
176

          self.__shr.add(threading.currentThread())
        finally:
          self.__nwait_shr -= 1

      else:
177
178
179
        # TODO: if !blocking...
        # (or modify __exclusive_acquire for non-blocking mode)
        self.__exclusive_acquire()
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225

    finally:
      self.__lock.release()

    return True

  def release(self):
    """Release a Shared Lock.

    You must have acquired the lock, either in shared or in exclusive mode,
    before calling this function.

    """
    self.__lock.acquire()
    try:
      # Autodetect release type
      if self.__is_exclusive():
        self.__exc = None

        # An exclusive holder has just had the lock, time to put it in shared
        # mode if there are shared holders waiting. Otherwise wake up the next
        # exclusive holder.
        if self.__nwait_shr > 0:
          self.__turn_shr.notifyAll()
        elif self.__nwait_exc > 0:
         self.__turn_exc.notify()

      elif self.__is_sharer():
        self.__shr.remove(threading.currentThread())

        # If there are shared holders waiting there *must* be an exclusive holder
        # waiting as well; otherwise what were they waiting for?
        assert (self.__nwait_shr == 0 or self.__nwait_exc > 0,
                "Lock sharers waiting while no exclusive is queueing")

        # If there are no more shared holders and some exclusive holders are
        # waiting let's wake one up.
        if len(self.__shr) == 0 and self.__nwait_exc > 0:
          self.__turn_exc.notify()

      else:
        assert False, "Cannot release non-owned lock"

    finally:
      self.__lock.release()

226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
  def delete(self, blocking=1):
    """Delete a Shared Lock.

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

    Args:
      blocking: whether to block while trying to acquire or to operate in
                try-lock mode.  this locking mode is not supported yet unless
                you are already holding exclusively the lock.

    """
    self.__lock.acquire()
    try:
      assert not self.__is_sharer(), "cannot delete() a lock while sharing it"

      if self.__deleted:
        raise errors.LockError('deleted lock')

      if not self.__is_exclusive():
        if not blocking:
          # We don't have non-blocking mode for now
          raise NotImplementedError
        self.__exclusive_acquire()

      self.__deleted = True
      self.__exc = None
      # Wake up everybody, they will fail acquiring the lock and
      # raise an exception instead.
      self.__turn_exc.notifyAll()
      self.__turn_shr.notifyAll()

    finally:
      self.__lock.release()