Statistics
| Branch: | Tag: | Revision:

root / lib / locking.py @ cdb08f44

History | View | Annotate | Download (27.6 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=W0613,W0201
24

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

    
31

    
32
class SharedLock:
33
  """Implements a shared lock.
34

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

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

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

    
51
    # current lock holders
52
    self.__shr = set()
53
    self.__exc = None
54

    
55
    # lock waiters
56
    self.__nwait_exc = 0
57
    self.__nwait_shr = 0
58

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

    
62
  def __is_sharer(self):
63
    """Is the current thread sharing the lock at this time?"""
64
    return threading.currentThread() in self.__shr
65

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

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

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

76
    """
77
    if shared < 0:
78
      return self.__is_sharer() or self.__is_exclusive()
79
    elif shared:
80
      return self.__is_sharer()
81
    else:
82
      return self.__is_exclusive()
83

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

87
    Args:
88
      shared:
89
        < 0: check for any type of ownership (default)
90
        0: check for exclusive ownership
91
        > 0: check for shared ownership
92

93
    """
94
    self.__lock.acquire()
95
    try:
96
      result = self.__is_owned(shared=shared)
97
    finally:
98
      self.__lock.release()
99

    
100
    return result
101

    
102
  def __wait(self, c):
103
    """Wait on the given condition, and raise an exception if the current lock
104
    is declared deleted in the meantime.
105

106
    Args:
107
      c: condition to wait on
108

109
    """
110
    c.wait()
111
    if self.__deleted:
112
      raise errors.LockError('deleted lock')
113

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

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

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

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

    
132
      self.__exc = threading.currentThread()
133
    finally:
134
      self.__nwait_exc -= 1
135

    
136
  def acquire(self, blocking=1, shared=0):
137
    """Acquire a shared lock.
138

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

145
    """
146
    if not blocking:
147
      # We don't have non-blocking mode for now
148
      raise NotImplementedError
149

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

    
155
      # We cannot acquire the lock if we already have it
156
      assert not self.__is_owned(), "double acquire() on a non-recursive lock"
157

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

    
168
          while self.__exc is not None:
169
            # TODO: if !blocking...
170
            self.__wait(self.__turn_shr)
171

    
172
          self.__shr.add(threading.currentThread())
173
        finally:
174
          self.__nwait_shr -= 1
175

    
176
      else:
177
        # TODO: if !blocking...
178
        # (or modify __exclusive_acquire for non-blocking mode)
179
        self.__exclusive_acquire()
180

    
181
    finally:
182
      self.__lock.release()
183

    
184
    return True
185

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

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

192
    """
193
    self.__lock.acquire()
194
    try:
195
      # Autodetect release type
196
      if self.__is_exclusive():
197
        self.__exc = None
198

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

    
207
      elif self.__is_sharer():
208
        self.__shr.remove(threading.currentThread())
209

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

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

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

    
223
    finally:
224
      self.__lock.release()
225

    
226
  def delete(self, blocking=1):
227
    """Delete a Shared Lock.
228

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

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

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

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

    
246
      if not self.__is_exclusive():
247
        if not blocking:
248
          # We don't have non-blocking mode for now
249
          raise NotImplementedError
250
        self.__exclusive_acquire()
251

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

    
259
    finally:
260
      self.__lock.release()
261

    
262

    
263
class LockSet:
264
  """Implements a set of locks.
265

266
  This abstraction implements a set of shared locks for the same resource type,
267
  distinguished by name. The user can lock a subset of the resources and the
268
  LockSet will take care of acquiring the locks always in the same order, thus
269
  preventing deadlock.
270

271
  All the locks needed in the same set must be acquired together, though.
272

273
  """
274
  def __init__(self, members=None):
275
    """Constructs a new LockSet.
276

277
    Args:
278
      members: initial members of the set
279

280
    """
281
    # Used internally to guarantee coherency.
282
    self.__lock = SharedLock()
283

    
284
    # The lockdict indexes the relationship name -> lock
285
    # The order-of-locking is implied by the alphabetical order of names
286
    self.__lockdict = {}
287

    
288
    if members is not None:
289
      for name in members:
290
        self.__lockdict[name] = SharedLock()
291

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

    
301
  def _is_owned(self):
302
    """Is the current thread a current level owner?"""
303
    return threading.currentThread() in self.__owners
304

    
305
  def _add_owned(self, name):
306
    """Note the current thread owns the given lock"""
307
    if self._is_owned():
308
      self.__owners[threading.currentThread()].add(name)
309
    else:
310
       self.__owners[threading.currentThread()] = set([name])
311

    
312
  def _del_owned(self, name):
313
    """Note the current thread owns the given lock"""
314
    self.__owners[threading.currentThread()].remove(name)
315

    
316
    if not self.__owners[threading.currentThread()]:
317
      del self.__owners[threading.currentThread()]
318

    
319
  def _list_owned(self):
320
    """Get the set of resource names owned by the current thread"""
321
    if self._is_owned():
322
      return self.__owners[threading.currentThread()].copy()
323
    else:
324
      return set()
325

    
326
  def __names(self):
327
    """Return the current set of names.
328

329
    Only call this function while holding __lock and don't iterate on the
330
    result after releasing the lock.
331

332
    """
333
    return self.__lockdict.keys()
334

    
335
  def _names(self):
336
    """Return a copy of the current set of elements.
337

338
    Used only for debugging purposes.
339

340
    """
341
    self.__lock.acquire(shared=1)
342
    try:
343
      result = self.__names()
344
    finally:
345
      self.__lock.release()
346
    return set(result)
347

    
348
  def acquire(self, names, blocking=1, shared=0):
349
    """Acquire a set of resource locks.
350

351
    Args:
352
      names: the names of the locks which shall be acquired.
353
             (special lock names, or instance/node names)
354
      shared: whether to acquire in shared mode. By default an exclusive lock
355
              will be acquired.
356
      blocking: whether to block while trying to acquire or to operate in try-lock mode.
357
                this locking mode is not supported yet.
358

359
    Returns:
360
      True: when all the locks are successfully acquired
361

362
    Raises:
363
      errors.LockError: when any lock we try to acquire has been deleted
364
      before we succeed. In this case none of the locks requested will be
365
      acquired.
366

367
    """
368
    if not blocking:
369
      # We don't have non-blocking mode for now
370
      raise NotImplementedError
371

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

    
375
    if names is None:
376
      # If no names are given acquire the whole set by not letting new names
377
      # being added before we release, and getting the current list of names.
378
      # Some of them may then be deleted later, but we'll cope with this.
379
      #
380
      # We'd like to acquire this lock in a shared way, as it's nice if
381
      # everybody else can use the instances at the same time. If are acquiring
382
      # them exclusively though they won't be able to do this anyway, though,
383
      # so we'll get the list lock exclusively as well in order to be able to
384
      # do add() on the set while owning it.
385
      self.__lock.acquire(shared=shared)
386

    
387
    try:
388
      # Support passing in a single resource to acquire rather than many
389
      if isinstance(names, basestring):
390
        names = [names]
391
      else:
392
        if names is None:
393
          names = self.__names()
394
        names.sort()
395

    
396
      acquire_list = []
397
      # First we look the locks up on __lockdict. We have no way of being sure
398
      # they will still be there after, but this makes it a lot faster should
399
      # just one of them be the already wrong
400
      for lname in names:
401
        try:
402
          lock = self.__lockdict[lname] # raises KeyError if the lock is not there
403
          acquire_list.append((lname, lock))
404
        except (KeyError):
405
          if self.__lock._is_owned():
406
            # We are acquiring all the set, it doesn't matter if this particular
407
            # element is not there anymore.
408
            continue
409
          else:
410
            raise errors.LockError('non-existing lock in set (%s)' % lname)
411

    
412
      # This will hold the locknames we effectively acquired.
413
      acquired = set()
414
      # Now acquire_list contains a sorted list of resources and locks we want.
415
      # In order to get them we loop on this (private) list and acquire() them.
416
      # We gave no real guarantee they will still exist till this is done but
417
      # .acquire() itself is safe and will alert us if the lock gets deleted.
418
      for (lname, lock) in acquire_list:
419
        try:
420
          lock.acquire(shared=shared) # raises LockError if the lock is deleted
421
          try:
422
            # now the lock cannot be deleted, we have it!
423
            self._add_owned(lname)
424
            acquired.add(lname)
425
          except:
426
            # We shouldn't have problems adding the lock to the owners list, but
427
            # if we did we'll try to release this lock and re-raise exception.
428
            # Of course something is going to be really wrong, after this.
429
            lock.release()
430
            raise
431

    
432
        except (errors.LockError):
433
          if self.__lock._is_owned():
434
            # We are acquiring all the set, it doesn't matter if this particular
435
            # element is not there anymore.
436
            continue
437
          else:
438
            name_fail = lname
439
            for lname in self._list_owned():
440
              self.__lockdict[lname].release()
441
              self._del_owned(lname)
442
            raise errors.LockError('non-existing lock in set (%s)' % name_fail)
443

    
444
    except:
445
      # If something went wrong and we had the set-lock let's release it...
446
      if self.__lock._is_owned():
447
        self.__lock.release()
448
      raise
449

    
450
    return acquired
451

    
452
  def release(self, names=None):
453
    """Release a set of resource locks, at the same level.
454

455
    You must have acquired the locks, either in shared or in exclusive mode,
456
    before releasing them.
457

458
    Args:
459
      names: the names of the locks which shall be released.
460
             (defaults to all the locks acquired at that level).
461

462
    """
463
    assert self._is_owned(), "release() on lock set while not owner"
464

    
465
    # Support passing in a single resource to release rather than many
466
    if isinstance(names, basestring):
467
      names = [names]
468

    
469
    if names is None:
470
      names = self._list_owned()
471
    else:
472
      names = set(names)
473
      assert self._list_owned().issuperset(names), (
474
               "release() on unheld resources %s" %
475
               names.difference(self._list_owned()))
476

    
477
    # First of all let's release the "all elements" lock, if set.
478
    # After this 'add' can work again
479
    if self.__lock._is_owned():
480
      self.__lock.release()
481

    
482
    for lockname in names:
483
      # If we are sure the lock doesn't leave __lockdict without being
484
      # exclusively held we can do this...
485
      self.__lockdict[lockname].release()
486
      self._del_owned(lockname)
487

    
488
  def add(self, names, acquired=0, shared=0):
489
    """Add a new set of elements to the set
490

491
    Args:
492
      names: names of the new elements to add
493
      acquired: pre-acquire the new resource?
494
      shared: is the pre-acquisition shared?
495

496
    """
497

    
498
    assert not self.__lock._is_owned(shared=1), (
499
           "Cannot add new elements while sharing the set-lock")
500

    
501
    # Support passing in a single resource to add rather than many
502
    if isinstance(names, basestring):
503
      names = [names]
504

    
505
    # If we don't already own the set-level lock acquire it in an exclusive way
506
    # we'll get it and note we need to release it later.
507
    release_lock = False
508
    if not self.__lock._is_owned():
509
      release_lock = True
510
      self.__lock.acquire()
511

    
512
    try:
513
      invalid_names = set(self.__names()).intersection(names)
514
      if invalid_names:
515
        # This must be an explicit raise, not an assert, because assert is
516
        # turned off when using optimization, and this can happen because of
517
        # concurrency even if the user doesn't want it.
518
        raise errors.LockError("duplicate add() (%s)" % invalid_names)
519

    
520
      for lockname in names:
521
        lock = SharedLock()
522

    
523
        if acquired:
524
          lock.acquire(shared=shared)
525
          # now the lock cannot be deleted, we have it!
526
          try:
527
            self._add_owned(lockname)
528
          except:
529
            # We shouldn't have problems adding the lock to the owners list,
530
            # but if we did we'll try to release this lock and re-raise
531
            # exception.  Of course something is going to be really wrong,
532
            # after this.  On the other hand the lock hasn't been added to the
533
            # __lockdict yet so no other threads should be pending on it. This
534
            # release is just a safety measure.
535
            lock.release()
536
            raise
537

    
538
        self.__lockdict[lockname] = lock
539

    
540
    finally:
541
      # Only release __lock if we were not holding it previously.
542
      if release_lock:
543
        self.__lock.release()
544

    
545
    return True
546

    
547
  def remove(self, names, blocking=1):
548
    """Remove elements from the lock set.
549

550
    You can either not hold anything in the lockset or already hold a superset
551
    of the elements you want to delete, exclusively.
552

553
    Args:
554
      names: names of the resource to remove.
555
      blocking: whether to block while trying to acquire or to operate in
556
                try-lock mode.  this locking mode is not supported yet unless
557
                you are already holding exclusively the locks.
558

559
    Returns:
560
      A list of lock which we removed. The list is always equal to the names
561
      list if we were holding all the locks exclusively.
562

563
    """
564
    if not blocking and not self._is_owned():
565
      # We don't have non-blocking mode for now
566
      raise NotImplementedError
567

    
568
    # Support passing in a single resource to remove rather than many
569
    if isinstance(names, basestring):
570
      names = [names]
571

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

    
578
    removed = []
579

    
580
    for lname in names:
581
      # Calling delete() acquires the lock exclusively if we don't already own
582
      # it, and causes all pending and subsequent lock acquires to fail. It's
583
      # fine to call it out of order because delete() also implies release(),
584
      # and the assertion above guarantees that if we either already hold
585
      # everything we want to delete, or we hold none.
586
      try:
587
        self.__lockdict[lname].delete()
588
        removed.append(lname)
589
      except (KeyError, errors.LockError):
590
        # This cannot happen if we were already holding it, verify:
591
        assert not self._is_owned(), "remove failed while holding lockset"
592
      else:
593
        # If no LockError was raised we are the ones who deleted the lock.
594
        # This means we can safely remove it from lockdict, as any further or
595
        # pending delete() or acquire() will fail (and nobody can have the lock
596
        # since before our call to delete()).
597
        #
598
        # This is done in an else clause because if the exception was thrown
599
        # it's the job of the one who actually deleted it.
600
        del self.__lockdict[lname]
601
        # And let's remove it from our private list if we owned it.
602
        if self._is_owned():
603
          self._del_owned(lname)
604

    
605
    return removed
606

    
607

    
608
# Locking levels, must be acquired in increasing order.
609
# Current rules are:
610
#   - at level LEVEL_CLUSTER resides the Big Ganeti Lock (BGL) which must be
611
#   acquired before performing any operation, either in shared or in exclusive
612
#   mode. acquiring the BGL in exclusive mode is discouraged and should be
613
#   avoided.
614
#   - at levels LEVEL_NODE and LEVEL_INSTANCE reside node and instance locks.
615
#   If you need more than one node, or more than one instance, acquire them at
616
#   the same time.
617
#  - level LEVEL_CONFIG contains the configuration lock, which you must acquire
618
#  before reading or changing the config file.
619
LEVEL_CLUSTER = 0
620
LEVEL_NODE = 1
621
LEVEL_INSTANCE = 2
622
LEVEL_CONFIG = 3
623

    
624
LEVELS = [LEVEL_CLUSTER,
625
          LEVEL_NODE,
626
          LEVEL_INSTANCE,
627
          LEVEL_CONFIG]
628

    
629
# Lock levels which are modifiable
630
LEVELS_MOD = [LEVEL_NODE, LEVEL_INSTANCE]
631

    
632
# Constant for the big ganeti lock and config lock
633
BGL = 'BGL'
634
CONFIG = 'config'
635

    
636

    
637
class GanetiLockManager:
638
  """The Ganeti Locking Library
639

640
  The purpouse of this small library is to manage locking for ganeti clusters
641
  in a central place, while at the same time doing dynamic checks against
642
  possible deadlocks. It will also make it easier to transition to a different
643
  lock type should we migrate away from python threads.
644

645
  """
646
  _instance = None
647

    
648
  def __init__(self, nodes=None, instances=None):
649
    """Constructs a new GanetiLockManager object.
650

651
    There should be only a
652
    GanetiLockManager object at any time, so this function raises an error if this
653
    is not the case.
654

655
    Args:
656
      nodes: list of node names
657
      instances: list of instance names
658

659
    """
660
    assert self.__class__._instance is None, "double GanetiLockManager instance"
661
    self.__class__._instance = self
662

    
663
    # The keyring contains all the locks, at their level and in the correct
664
    # locking order.
665
    self.__keyring = {
666
      LEVEL_CLUSTER: LockSet([BGL]),
667
      LEVEL_NODE: LockSet(nodes),
668
      LEVEL_INSTANCE: LockSet(instances),
669
      LEVEL_CONFIG: LockSet([CONFIG]),
670
    }
671

    
672
  def _names(self, level):
673
    """List the lock names at the given level.
674
    Used for debugging/testing purposes.
675

676
    Args:
677
      level: the level whose list of locks to get
678

679
    """
680
    assert level in LEVELS, "Invalid locking level %s" % level
681
    return self.__keyring[level]._names()
682

    
683
  def _is_owned(self, level):
684
    """Check whether we are owning locks at the given level
685

686
    """
687
    return self.__keyring[level]._is_owned()
688

    
689
  def _list_owned(self, level):
690
    """Get the set of owned locks at the given level
691

692
    """
693
    return self.__keyring[level]._list_owned()
694

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

698
    """
699
    # This way of checking only works if LEVELS[i] = i, which we check for in
700
    # the test cases.
701
    return utils.any((self._is_owned(l) for l in LEVELS[level + 1:]))
702

    
703
  def _BGL_owned(self):
704
    """Check if the current thread owns the BGL.
705

706
    Both an exclusive or a shared acquisition work.
707

708
    """
709
    return BGL in self.__keyring[LEVEL_CLUSTER]._list_owned()
710

    
711
  def _contains_BGL(self, level, names):
712
    """Check if acting on the given level and set of names will change the
713
    status of the Big Ganeti Lock.
714

715
    """
716
    return level == LEVEL_CLUSTER and (names is None or BGL in names)
717

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

721
    Args:
722
      level: the level at which the locks shall be acquired.
723
             It must be a memmber of LEVELS.
724
      names: the names of the locks which shall be acquired.
725
             (special lock names, or instance/node names)
726
      shared: whether to acquire in shared mode. By default an exclusive lock
727
              will be acquired.
728
      blocking: whether to block while trying to acquire or to operate in try-lock mode.
729
                this locking mode is not supported yet.
730

731
    """
732
    assert level in LEVELS, "Invalid locking level %s" % level
733

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

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

    
747
    # Acquire the locks in the set.
748
    return self.__keyring[level].acquire(names, shared=shared,
749
                                         blocking=blocking)
750

    
751
  def release(self, level, names=None):
752
    """Release a set of resource locks, at the same level.
753

754
    You must have acquired the locks, either in shared or in exclusive mode,
755
    before releasing them.
756

757
    Args:
758
      level: the level at which the locks shall be released.
759
             It must be a memmber of LEVELS.
760
      names: the names of the locks which shall be released.
761
             (defaults to all the locks acquired at that level).
762

763
    """
764
    assert level in LEVELS, "Invalid locking level %s" % level
765
    assert (not self._contains_BGL(level, names) or
766
            not self._upper_owned(LEVEL_CLUSTER)), (
767
            "Cannot release the Big Ganeti Lock while holding something"
768
            " at upper levels")
769

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

    
773
  def add(self, level, names, acquired=0, shared=0):
774
    """Add locks at the specified level.
775

776
    Args:
777
      level: the level at which the locks shall be added.
778
             It must be a memmber of LEVELS_MOD.
779
      names: names of the locks to acquire
780
      acquired: whether to acquire the newly added locks
781
      shared: whether the acquisition will be shared
782
    """
783
    assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
784
    assert self._BGL_owned(), ("You must own the BGL before performing other"
785
           " operations")
786
    assert not self._upper_owned(level), ("Cannot add locks at a level"
787
           " while owning some at a greater one")
788
    return self.__keyring[level].add(names, acquired=acquired, shared=shared)
789

    
790
  def remove(self, level, names, blocking=1):
791
    """Remove locks from the specified level.
792

793
    You must either already own the locks you are trying to remove exclusively
794
    or not own any lock at an upper level.
795

796
    Args:
797
      level: the level at which the locks shall be removed.
798
             It must be a memmber of LEVELS_MOD.
799
      names: the names of the locks which shall be removed.
800
             (special lock names, or instance/node names)
801
      blocking: whether to block while trying to operate in try-lock mode.
802
                this locking mode is not supported yet.
803

804
    """
805
    assert level in LEVELS_MOD, "Invalid or immutable level %s" % level
806
    assert self._BGL_owned(), ("You must own the BGL before performing other"
807
           " operations")
808
    # Check we either own the level or don't own anything from here up.
809
    # LockSet.remove() will check the case in which we don't own all the needed
810
    # resources, or we have a shared ownership.
811
    assert self._is_owned(level) or not self._upper_owned(level), (
812
           "Cannot remove locks at a level while not owning it or"
813
           " owning some at a greater one")
814
    return self.__keyring[level].remove(names, blocking=blocking)