Statistics
| Branch: | Tag: | Revision:

root / lib / locking.py @ c70d2d9b

History | View | Annotate | Download (29.8 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 Google Inc.
5
#
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.
10
#
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.
15
#
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
19
# 02110-1301, USA.
20

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

    
23
# pylint: disable-msg=W0212
24

    
25
# W0212 since e.g. LockSet methods use (a lot) the internals of
26
# SharedLock
27

    
28
import threading
29
# Wouldn't it be better to define LockingError in the locking module?
30
# Well, for now that's how the rest of the code does it...
31
from ganeti import errors
32
from ganeti import utils
33

    
34

    
35
def ssynchronized(lock, shared=0):
36
  """Shared Synchronization decorator.
37

38
  Calls the function holding the given lock, either in exclusive or shared
39
  mode. It requires the passed lock to be a SharedLock (or support its
40
  semantics).
41

42
  """
43
  def wrap(fn):
44
    def sync_function(*args, **kwargs):
45
      lock.acquire(shared=shared)
46
      try:
47
        return fn(*args, **kwargs)
48
      finally:
49
        lock.release()
50
    return sync_function
51
  return wrap
52

    
53

    
54
class SharedLock:
55
  """Implements a shared lock.
56

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

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

65
  """
66
  def __init__(self):
67
    """Construct a new SharedLock"""
68
    # we have two conditions, c_shr and c_exc, sharing the same lock.
69
    self.__lock = threading.Lock()
70
    self.__turn_shr = threading.Condition(self.__lock)
71
    self.__turn_exc = threading.Condition(self.__lock)
72

    
73
    # current lock holders
74
    self.__shr = set()
75
    self.__exc = None
76

    
77
    # lock waiters
78
    self.__nwait_exc = 0
79
    self.__nwait_shr = 0
80
    self.__npass_shr = 0
81

    
82
    # is this lock in the deleted state?
83
    self.__deleted = False
84

    
85
  def __is_sharer(self):
86
    """Is the current thread sharing the lock at this time?"""
87
    return threading.currentThread() in self.__shr
88

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

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

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

99
    """
100
    if shared < 0:
101
      return self.__is_sharer() or self.__is_exclusive()
102
    elif shared:
103
      return self.__is_sharer()
104
    else:
105
      return self.__is_exclusive()
106

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

110
    @param shared:
111
        - < 0: check for any type of ownership (default)
112
        - 0: check for exclusive ownership
113
        - > 0: check for shared ownership
114

115
    """
116
    self.__lock.acquire()
117
    try:
118
      result = self.__is_owned(shared=shared)
119
    finally:
120
      self.__lock.release()
121

    
122
    return result
123

    
124
  def __wait(self, c):
125
    """Wait on the given condition, and raise an exception if the current lock
126
    is declared deleted in the meantime.
127

128
    @param c: the condition to wait on
129

130
    """
131
    c.wait()
132
    if self.__deleted:
133
      raise errors.LockError('deleted lock')
134

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

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

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

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

    
153
      self.__exc = threading.currentThread()
154
    finally:
155
      self.__nwait_exc -= 1
156

    
157
    assert self.__npass_shr == 0, "SharedLock: internal fairness violation"
158

    
159
  def acquire(self, blocking=1, shared=0):
160
    """Acquire a shared lock.
161

162
    @param shared: whether to acquire in shared mode; by default an
163
        exclusive lock will be acquired
164
    @param blocking: whether to block while trying to acquire or to
165
        operate in try-lock mode (this locking mode is not supported yet)
166

167
    """
168
    if not blocking:
169
      # We don't have non-blocking mode for now
170
      raise NotImplementedError
171

    
172
    self.__lock.acquire()
173
    try:
174
      if self.__deleted:
175
        raise errors.LockError('deleted lock')
176

    
177
      # We cannot acquire the lock if we already have it
178
      assert not self.__is_owned(), "double acquire() on a non-recursive lock"
179
      assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
180

    
181
      if shared:
182
        self.__nwait_shr += 1
183
        try:
184
          wait = False
185
          # If there is an exclusive holder waiting we have to wait.
186
          # We'll only do this once, though, when we start waiting for
187
          # the lock. Then we'll just wait while there are no
188
          # exclusive holders.
189
          if self.__nwait_exc > 0:
190
            # TODO: if !blocking...
191
            wait = True
192
            self.__wait(self.__turn_shr)
193

    
194
          while self.__exc is not None:
195
            wait = True
196
            # TODO: if !blocking...
197
            self.__wait(self.__turn_shr)
198

    
199
          self.__shr.add(threading.currentThread())
200

    
201
          # If we were waiting note that we passed
202
          if wait:
203
            self.__npass_shr -= 1
204

    
205
        finally:
206
          self.__nwait_shr -= 1
207

    
208
        assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
209
      else:
210
        # TODO: if !blocking...
211
        # (or modify __exclusive_acquire for non-blocking mode)
212
        self.__exclusive_acquire()
213

    
214
    finally:
215
      self.__lock.release()
216

    
217
    return True
218

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

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

225
    """
226
    self.__lock.acquire()
227
    try:
228
      assert self.__npass_shr >= 0, "Internal fairness condition weirdness"
229
      # Autodetect release type
230
      if self.__is_exclusive():
231
        self.__exc = None
232

    
233
        # An exclusive holder has just had the lock, time to put it in shared
234
        # mode if there are shared holders waiting. Otherwise wake up the next
235
        # exclusive holder.
236
        if self.__nwait_shr > 0:
237
          # Make sure at least the ones which were blocked pass.
238
          self.__npass_shr = self.__nwait_shr
239
          self.__turn_shr.notifyAll()
240
        elif self.__nwait_exc > 0:
241
          self.__turn_exc.notify()
242

    
243
      elif self.__is_sharer():
244
        self.__shr.remove(threading.currentThread())
245

    
246
        # If there are shared holders waiting (and not just scheduled to pass)
247
        # there *must* be an exclusive holder waiting as well; otherwise what
248
        # were they waiting for?
249
        assert (self.__nwait_exc > 0 or
250
                self.__npass_shr == self.__nwait_shr), \
251
                "Lock sharers waiting while no exclusive is queueing"
252

    
253
        # If there are no more shared holders either in or scheduled to pass,
254
        # and some exclusive holders are waiting let's wake one up.
255
        if (len(self.__shr) == 0 and
256
            self.__nwait_exc > 0 and
257
            not self.__npass_shr > 0):
258
          self.__turn_exc.notify()
259

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

    
263
    finally:
264
      self.__lock.release()
265

    
266
  def delete(self, blocking=1):
267
    """Delete a Shared Lock.
268

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

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

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

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

    
285
      if not self.__is_exclusive():
286
        if not blocking:
287
          # We don't have non-blocking mode for now
288
          raise NotImplementedError
289
        self.__exclusive_acquire()
290

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

    
298
    finally:
299
      self.__lock.release()
300

    
301

    
302
# Whenever we want to acquire a full LockSet we pass None as the value
303
# to acquire.  Hide this behind this nicely named constant.
304
ALL_SET = None
305

    
306

    
307
class LockSet:
308
  """Implements a set of locks.
309

310
  This abstraction implements a set of shared locks for the same resource type,
311
  distinguished by name. The user can lock a subset of the resources and the
312
  LockSet will take care of acquiring the locks always in the same order, thus
313
  preventing deadlock.
314

315
  All the locks needed in the same set must be acquired together, though.
316

317
  """
318
  def __init__(self, members=None):
319
    """Constructs a new LockSet.
320

321
    @param members: initial members of the set
322

323
    """
324
    # Used internally to guarantee coherency.
325
    self.__lock = SharedLock()
326

    
327
    # The lockdict indexes the relationship name -> lock
328
    # The order-of-locking is implied by the alphabetical order of names
329
    self.__lockdict = {}
330

    
331
    if members is not None:
332
      for name in members:
333
        self.__lockdict[name] = SharedLock()
334

    
335
    # The owner dict contains the set of locks each thread owns. For
336
    # performance each thread can access its own key without a global lock on
337
    # this structure. It is paramount though that *no* other type of access is
338
    # done to this structure (eg. no looping over its keys). *_owner helper
339
    # function are defined to guarantee access is correct, but in general never
340
    # do anything different than __owners[threading.currentThread()], or there
341
    # will be trouble.
342
    self.__owners = {}
343

    
344
  def _is_owned(self):
345
    """Is the current thread a current level owner?"""
346
    return threading.currentThread() in self.__owners
347

    
348
  def _add_owned(self, name=None):
349
    """Note the current thread owns the given lock"""
350
    if name is None:
351
      if not self._is_owned():
352
        self.__owners[threading.currentThread()] = set()
353
    else:
354
      if self._is_owned():
355
        self.__owners[threading.currentThread()].add(name)
356
      else:
357
        self.__owners[threading.currentThread()] = set([name])
358

    
359

    
360
  def _del_owned(self, name=None):
361
    """Note the current thread owns the given lock"""
362

    
363
    if name is not None:
364
      self.__owners[threading.currentThread()].remove(name)
365

    
366
    # Only remove the key if we don't hold the set-lock as well
367
    if (not self.__lock._is_owned() and
368
        not self.__owners[threading.currentThread()]):
369
      del self.__owners[threading.currentThread()]
370

    
371
  def _list_owned(self):
372
    """Get the set of resource names owned by the current thread"""
373
    if self._is_owned():
374
      return self.__owners[threading.currentThread()].copy()
375
    else:
376
      return set()
377

    
378
  def __names(self):
379
    """Return the current set of names.
380

381
    Only call this function while holding __lock and don't iterate on the
382
    result after releasing the lock.
383

384
    """
385
    return self.__lockdict.keys()
386

    
387
  def _names(self):
388
    """Return a copy of the current set of elements.
389

390
    Used only for debugging purposes.
391

392
    """
393
    # If we don't already own the set-level lock acquired
394
    # we'll get it and note we need to release it later.
395
    release_lock = False
396
    if not self.__lock._is_owned():
397
      release_lock = True
398
      self.__lock.acquire(shared=1)
399
    try:
400
      result = self.__names()
401
    finally:
402
      if release_lock:
403
        self.__lock.release()
404
    return set(result)
405

    
406
  def acquire(self, names, blocking=1, shared=0):
407
    """Acquire a set of resource locks.
408

409
    @param names: the names of the locks which shall be acquired
410
        (special lock names, or instance/node names)
411
    @param shared: whether to acquire in shared mode; by default an
412
        exclusive lock will be acquired
413
    @param blocking: whether to block while trying to acquire or to
414
        operate in try-lock mode (this locking mode is not supported yet)
415

416
    @return: True when all the locks are successfully acquired
417

418
    @raise errors.LockError: when any lock we try to acquire has
419
        been deleted before we succeed. In this case none of the
420
        locks requested will be acquired.
421

422
    """
423
    if not blocking:
424
      # We don't have non-blocking mode for now
425
      raise NotImplementedError
426

    
427
    # Check we don't already own locks at this level
428
    assert not self._is_owned(), "Cannot acquire locks in the same set twice"
429

    
430
    if names is None:
431
      # If no names are given acquire the whole set by not letting new names
432
      # being added before we release, and getting the current list of names.
433
      # Some of them may then be deleted later, but we'll cope with this.
434
      #
435
      # We'd like to acquire this lock in a shared way, as it's nice if
436
      # everybody else can use the instances at the same time. If are acquiring
437
      # them exclusively though they won't be able to do this anyway, though,
438
      # so we'll get the list lock exclusively as well in order to be able to
439
      # do add() on the set while owning it.
440
      self.__lock.acquire(shared=shared)
441
      try:
442
        # note we own the set-lock
443
        self._add_owned()
444
        names = self.__names()
445
      except:
446
        # We shouldn't have problems adding the lock to the owners list, but
447
        # if we did we'll try to release this lock and re-raise exception.
448
        # Of course something is going to be really wrong, after this.
449
        self.__lock.release()
450
        raise
451

    
452
    try:
453
      # Support passing in a single resource to acquire rather than many
454
      if isinstance(names, basestring):
455
        names = [names]
456
      else:
457
        names = sorted(names)
458

    
459
      acquire_list = []
460
      # First we look the locks up on __lockdict. We have no way of being sure
461
      # they will still be there after, but this makes it a lot faster should
462
      # just one of them be the already wrong
463
      for lname in utils.UniqueSequence(names):
464
        try:
465
          lock = self.__lockdict[lname] # raises KeyError if lock is not there
466
          acquire_list.append((lname, lock))
467
        except (KeyError):
468
          if self.__lock._is_owned():
469
            # We are acquiring all the set, it doesn't matter if this
470
            # particular element is not there anymore.
471
            continue
472
          else:
473
            raise errors.LockError('non-existing lock in set (%s)' % lname)
474

    
475
      # This will hold the locknames we effectively acquired.
476
      acquired = set()
477
      # Now acquire_list contains a sorted list of resources and locks we want.
478
      # In order to get them we loop on this (private) list and acquire() them.
479
      # We gave no real guarantee they will still exist till this is done but
480
      # .acquire() itself is safe and will alert us if the lock gets deleted.
481
      for (lname, lock) in acquire_list:
482
        try:
483
          lock.acquire(shared=shared) # raises LockError if the lock is deleted
484
          # now the lock cannot be deleted, we have it!
485
          self._add_owned(name=lname)
486
          acquired.add(lname)
487
        except (errors.LockError):
488
          if self.__lock._is_owned():
489
            # We are acquiring all the set, it doesn't matter if this
490
            # particular element is not there anymore.
491
            continue
492
          else:
493
            name_fail = lname
494
            for lname in self._list_owned():
495
              self.__lockdict[lname].release()
496
              self._del_owned(name=lname)
497
            raise errors.LockError('non-existing lock in set (%s)' % name_fail)
498
        except:
499
          # We shouldn't have problems adding the lock to the owners list, but
500
          # if we did we'll try to release this lock and re-raise exception.
501
          # Of course something is going to be really wrong, after this.
502
          if lock._is_owned():
503
            lock.release()
504
          raise
505

    
506
    except:
507
      # If something went wrong and we had the set-lock let's release it...
508
      if self.__lock._is_owned():
509
        self.__lock.release()
510
      raise
511

    
512
    return acquired
513

    
514
  def release(self, names=None):
515
    """Release a set of resource locks, at the same level.
516

517
    You must have acquired the locks, either in shared or in exclusive mode,
518
    before releasing them.
519

520
    @param names: the names of the locks which shall be released
521
        (defaults to all the locks acquired at that level).
522

523
    """
524
    assert self._is_owned(), "release() on lock set while not owner"
525

    
526
    # Support passing in a single resource to release rather than many
527
    if isinstance(names, basestring):
528
      names = [names]
529

    
530
    if names is None:
531
      names = self._list_owned()
532
    else:
533
      names = set(names)
534
      assert self._list_owned().issuperset(names), (
535
               "release() on unheld resources %s" %
536
               names.difference(self._list_owned()))
537

    
538
    # First of all let's release the "all elements" lock, if set.
539
    # After this 'add' can work again
540
    if self.__lock._is_owned():
541
      self.__lock.release()
542
      self._del_owned()
543

    
544
    for lockname in names:
545
      # If we are sure the lock doesn't leave __lockdict without being
546
      # exclusively held we can do this...
547
      self.__lockdict[lockname].release()
548
      self._del_owned(name=lockname)
549

    
550
  def add(self, names, acquired=0, shared=0):
551
    """Add a new set of elements to the set
552

553
    @param names: names of the new elements to add
554
    @param acquired: pre-acquire the new resource?
555
    @param shared: is the pre-acquisition shared?
556

557
    """
558
    # Check we don't already own locks at this level
559
    assert not self._is_owned() or self.__lock._is_owned(shared=0), \
560
      "Cannot add locks if the set is only partially owned, or shared"
561

    
562
    # Support passing in a single resource to add rather than many
563
    if isinstance(names, basestring):
564
      names = [names]
565

    
566
    # If we don't already own the set-level lock acquired in an exclusive way
567
    # we'll get it and note we need to release it later.
568
    release_lock = False
569
    if not self.__lock._is_owned():
570
      release_lock = True
571
      self.__lock.acquire()
572

    
573
    try:
574
      invalid_names = set(self.__names()).intersection(names)
575
      if invalid_names:
576
        # This must be an explicit raise, not an assert, because assert is
577
        # turned off when using optimization, and this can happen because of
578
        # concurrency even if the user doesn't want it.
579
        raise errors.LockError("duplicate add() (%s)" % invalid_names)
580

    
581
      for lockname in names:
582
        lock = SharedLock()
583

    
584
        if acquired:
585
          lock.acquire(shared=shared)
586
          # now the lock cannot be deleted, we have it!
587
          try:
588
            self._add_owned(name=lockname)
589
          except:
590
            # We shouldn't have problems adding the lock to the owners list,
591
            # but if we did we'll try to release this lock and re-raise
592
            # exception.  Of course something is going to be really wrong,
593
            # after this.  On the other hand the lock hasn't been added to the
594
            # __lockdict yet so no other threads should be pending on it. This
595
            # release is just a safety measure.
596
            lock.release()
597
            raise
598

    
599
        self.__lockdict[lockname] = lock
600

    
601
    finally:
602
      # Only release __lock if we were not holding it previously.
603
      if release_lock:
604
        self.__lock.release()
605

    
606
    return True
607

    
608
  def remove(self, names, blocking=1):
609
    """Remove elements from the lock set.
610

611
    You can either not hold anything in the lockset or already hold a superset
612
    of the elements you want to delete, exclusively.
613

614
    @param names: names of the resource to remove.
615
    @param blocking: whether to block while trying to acquire or to
616
        operate in try-lock mode (this locking mode is not supported
617
        yet unless you are already holding exclusively the locks)
618

619
    @return:: a list of locks which we removed; the list is always
620
        equal to the names list if we were holding all the locks
621
        exclusively
622

623
    """
624
    if not blocking and not self._is_owned():
625
      # We don't have non-blocking mode for now
626
      raise NotImplementedError
627

    
628
    # Support passing in a single resource to remove rather than many
629
    if isinstance(names, basestring):
630
      names = [names]
631

    
632
    # If we own any subset of this lock it must be a superset of what we want
633
    # to delete. The ownership must also be exclusive, but that will be checked
634
    # by the lock itself.
635
    assert not self._is_owned() or self._list_owned().issuperset(names), (
636
      "remove() on acquired lockset while not owning all elements")
637

    
638
    removed = []
639

    
640
    for lname in names:
641
      # Calling delete() acquires the lock exclusively if we don't already own
642
      # it, and causes all pending and subsequent lock acquires to fail. It's
643
      # fine to call it out of order because delete() also implies release(),
644
      # and the assertion above guarantees that if we either already hold
645
      # everything we want to delete, or we hold none.
646
      try:
647
        self.__lockdict[lname].delete()
648
        removed.append(lname)
649
      except (KeyError, errors.LockError):
650
        # This cannot happen if we were already holding it, verify:
651
        assert not self._is_owned(), "remove failed while holding lockset"
652
      else:
653
        # If no LockError was raised we are the ones who deleted the lock.
654
        # This means we can safely remove it from lockdict, as any further or
655
        # pending delete() or acquire() will fail (and nobody can have the lock
656
        # since before our call to delete()).
657
        #
658
        # This is done in an else clause because if the exception was thrown
659
        # it's the job of the one who actually deleted it.
660
        del self.__lockdict[lname]
661
        # And let's remove it from our private list if we owned it.
662
        if self._is_owned():
663
          self._del_owned(name=lname)
664

    
665
    return removed
666

    
667

    
668
# Locking levels, must be acquired in increasing order.
669
# Current rules are:
670
#   - at level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
671
#   acquired before performing any operation, either in shared or in exclusive
672
#   mode. acquiring the BGL in exclusive mode is discouraged and should be
673
#   avoided.
674
#   - at levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks.
675
#   If you need more than one node, or more than one instance, acquire them at
676
#   the same time.
677
LEVEL_CLUSTER = 0
678
LEVEL_INSTANCE = 1
679
LEVEL_NODE = 2
680

    
681
LEVELS = [LEVEL_CLUSTER,
682
          LEVEL_INSTANCE,
683
          LEVEL_NODE]
684

    
685
# Lock levels which are modifiable
686
LEVELS_MOD = [LEVEL_NODE, LEVEL_INSTANCE]
687

    
688
# Constant for the big ganeti lock
689
BGL = 'BGL'
690

    
691

    
692
class GanetiLockManager:
693
  """The Ganeti Locking Library
694

695
  The purpose of this small library is to manage locking for ganeti clusters
696
  in a central place, while at the same time doing dynamic checks against
697
  possible deadlocks. It will also make it easier to transition to a different
698
  lock type should we migrate away from python threads.
699

700
  """
701
  _instance = None
702

    
703
  def __init__(self, nodes=None, instances=None):
704
    """Constructs a new GanetiLockManager object.
705

706
    There should be only a GanetiLockManager object at any time, so this
707
    function raises an error if this is not the case.
708

709
    @param nodes: list of node names
710
    @param instances: list of instance names
711

712
    """
713
    assert self.__class__._instance is None, \
714
           "double GanetiLockManager instance"
715

    
716
    self.__class__._instance = self
717

    
718
    # The keyring contains all the locks, at their level and in the correct
719
    # locking order.
720
    self.__keyring = {
721
      LEVEL_CLUSTER: LockSet([BGL]),
722
      LEVEL_NODE: LockSet(nodes),
723
      LEVEL_INSTANCE: LockSet(instances),
724
    }
725

    
726
  def _names(self, level):
727
    """List the lock names at the given level.
728

729
    This can be used for debugging/testing purposes.
730

731
    @param level: the level whose list of locks to get
732

733
    """
734
    assert level in LEVELS, "Invalid locking level %s" % level
735
    return self.__keyring[level]._names()
736

    
737
  def _is_owned(self, level):
738
    """Check whether we are owning locks at the given level
739

740
    """
741
    return self.__keyring[level]._is_owned()
742

    
743
  is_owned = _is_owned
744

    
745
  def _list_owned(self, level):
746
    """Get the set of owned locks at the given level
747

748
    """
749
    return self.__keyring[level]._list_owned()
750

    
751
  def _upper_owned(self, level):
752
    """Check that we don't own any lock at a level greater than the given one.
753

754
    """
755
    # This way of checking only works if LEVELS[i] = i, which we check for in
756
    # the test cases.
757
    return utils.any((self._is_owned(l) for l in LEVELS[level + 1:]))
758

    
759
  def _BGL_owned(self): # pylint: disable-msg=C0103
760
    """Check if the current thread owns the BGL.
761

762
    Both an exclusive or a shared acquisition work.
763

764
    """
765
    return BGL in self.__keyring[LEVEL_CLUSTER]._list_owned()
766

    
767
  @staticmethod
768
  def _contains_BGL(level, names): # pylint: disable-msg=C0103
769
    """Check if the level contains the BGL.
770

771
    Check if acting on the given level and set of names will change
772
    the status of the Big Ganeti Lock.
773

774
    """
775
    return level == LEVEL_CLUSTER and (names is None or BGL in names)
776

    
777
  def acquire(self, level, names, blocking=1, shared=0):
778
    """Acquire a set of resource locks, at the same level.
779

780
    @param level: the level at which the locks shall be acquired;
781
        it must be a member of LEVELS.
782
    @param names: the names of the locks which shall be acquired
783
        (special lock names, or instance/node names)
784
    @param shared: whether to acquire in shared mode; by default
785
        an exclusive lock will be acquired
786
    @param blocking: whether to block while trying to acquire or to
787
        operate in try-lock mode (this locking mode is not supported yet)
788

789
    """
790
    assert level in LEVELS, "Invalid locking level %s" % level
791

    
792
    # Check that we are either acquiring the Big Ganeti Lock or we already own
793
    # it. Some "legacy" opcodes need to be sure they are run non-concurrently
794
    # so even if we've migrated we need to at least share the BGL to be
795
    # compatible with them. Of course if we own the BGL exclusively there's no
796
    # point in acquiring any other lock, unless perhaps we are half way through
797
    # the migration of the current opcode.
798
    assert (self._contains_BGL(level, names) or self._BGL_owned()), (
799
            "You must own the Big Ganeti Lock before acquiring any other")
800

    
801
    # Check we don't own locks at the same or upper levels.
802
    assert not self._upper_owned(level), ("Cannot acquire locks at a level"
803
           " while owning some at a greater one")
804

    
805
    # Acquire the locks in the set.
806
    return self.__keyring[level].acquire(names, shared=shared,
807
                                         blocking=blocking)
808

    
809
  def release(self, level, names=None):
810
    """Release a set of resource locks, at the same level.
811

812
    You must have acquired the locks, either in shared or in exclusive
813
    mode, before releasing them.
814

815
    @param level: the level at which the locks shall be released;
816
        it must be a member of LEVELS
817
    @param names: the names of the locks which shall be released
818
        (defaults to all the locks acquired at that level)
819

820
    """
821
    assert level in LEVELS, "Invalid locking level %s" % level
822
    assert (not self._contains_BGL(level, names) or
823
            not self._upper_owned(LEVEL_CLUSTER)), (
824
            "Cannot release the Big Ganeti Lock while holding something"
825
            " at upper levels")
826

    
827
    # Release will complain if we don't own the locks already
828
    return self.__keyring[level].release(names)
829

    
830
  def add(self, level, names, acquired=0, shared=0):
831
    """Add locks at the specified level.
832

833
    @param level: the level at which the locks shall be added;
834
        it must be a member of LEVELS_MOD.
835
    @param names: names of the locks to acquire
836
    @param acquired: whether to acquire the newly added locks
837
    @param shared: whether the acquisition will be shared
838

839
    """
840
    assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
841
    assert self._BGL_owned(), ("You must own the BGL before performing other"
842
           " operations")
843
    assert not self._upper_owned(level), ("Cannot add locks at a level"
844
           " while owning some at a greater one")
845
    return self.__keyring[level].add(names, acquired=acquired, shared=shared)
846

    
847
  def remove(self, level, names, blocking=1):
848
    """Remove locks from the specified level.
849

850
    You must either already own the locks you are trying to remove
851
    exclusively or not own any lock at an upper level.
852

853
    @param level: the level at which the locks shall be removed;
854
        it must be a member of LEVELS_MOD
855
    @param names: the names of the locks which shall be removed
856
        (special lock names, or instance/node names)
857
    @param blocking: whether to block while trying to operate in
858
        try-lock mode (this locking mode is not supported yet)
859

860
    """
861
    assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
862
    assert self._BGL_owned(), ("You must own the BGL before performing other"
863
           " operations")
864
    # Check we either own the level or don't own anything from here
865
    # up. LockSet.remove() will check the case in which we don't own
866
    # all the needed resources, or we have a shared ownership.
867
    assert self._is_owned(level) or not self._upper_owned(level), (
868
           "Cannot remove locks at a level while not owning it or"
869
           " owning some at a greater one")
870
    return self.__keyring[level].remove(names, blocking=blocking)