~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lockdir.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-27 02:27:19 UTC
  • mfrom: (4634.3.19 gc-batching)
  • Revision ID: pqm@pqm.ubuntu.com-20090827022719-bl2yoqhpj3fcfczu
(andrew) Fix #402657: 2a fetch over dumb transport reads one group at
        a time.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""On-disk mutex protecting a resource
18
18
 
21
21
internal locks (such as flock etc) because they can be seen across all
22
22
transports, including http.
23
23
 
24
 
Objects can be read if there is only physical read access; therefore 
 
24
Objects can be read if there is only physical read access; therefore
25
25
readers can never be required to create a lock, though they will
26
26
check whether a writer is using the lock.  Writers can't detect
27
27
whether anyone else is reading from the resource as they write.
56
56
 
57
57
The desired characteristics are:
58
58
 
59
 
* Locks are not reentrant.  (That is, a client that tries to take a 
 
59
* Locks are not reentrant.  (That is, a client that tries to take a
60
60
  lock it already holds may deadlock or fail.)
61
61
* Stale locks can be guessed at by a heuristic
62
62
* Lost locks can be broken by any client
78
78
and deadlocks will likely occur if the locks are aliased.
79
79
 
80
80
In the future we may add a "freshen" method which can be called
81
 
by a lock holder to check that their lock has not been broken, and to 
 
81
by a lock holder to check that their lock has not been broken, and to
82
82
update the timestamp within it.
83
83
 
84
84
Example usage:
105
105
 
106
106
import os
107
107
import time
108
 
from cStringIO import StringIO
109
108
 
110
109
from bzrlib import (
111
110
    debug,
112
111
    errors,
 
112
    lock,
113
113
    )
114
114
import bzrlib.config
115
115
from bzrlib.errors import (
124
124
        PathError,
125
125
        ResourceBusy,
126
126
        TransportError,
127
 
        UnlockableTransport,
128
127
        )
129
128
from bzrlib.trace import mutter, note
130
 
from bzrlib.transport import Transport
131
 
from bzrlib.osutils import rand_chars, format_delta, get_host_name
132
 
from bzrlib.rio import read_stanza, Stanza
 
129
from bzrlib.osutils import format_delta, rand_chars, get_host_name
133
130
import bzrlib.ui
134
131
 
 
132
from bzrlib.lazy_import import lazy_import
 
133
lazy_import(globals(), """
 
134
from bzrlib import rio
 
135
""")
135
136
 
136
137
# XXX: At the moment there is no consideration of thread safety on LockDir
137
138
# objects.  This should perhaps be updated - e.g. if two threads try to take a
152
153
_DEFAULT_POLL_SECONDS = 1.0
153
154
 
154
155
 
155
 
class LockDir(object):
156
 
    """Write-lock guarding access to data."""
 
156
class LockDir(lock.Lock):
 
157
    """Write-lock guarding access to data.
 
158
    """
157
159
 
158
160
    __INFO_NAME = '/info'
159
161
 
164
166
 
165
167
        :param transport: Transport which will contain the lock
166
168
 
167
 
        :param path: Path to the lock within the base directory of the 
 
169
        :param path: Path to the lock within the base directory of the
168
170
            transport.
169
171
        """
170
172
        self.transport = transport
189
191
    def create(self, mode=None):
190
192
        """Create the on-disk lock.
191
193
 
192
 
        This is typically only called when the object/directory containing the 
 
194
        This is typically only called when the object/directory containing the
193
195
        directory is first created.  The lock is not held when it's created.
194
196
        """
195
197
        self._trace("create lock directory")
201
203
 
202
204
    def _attempt_lock(self):
203
205
        """Make the pending directory and attempt to rename into place.
204
 
        
 
206
 
205
207
        If the rename succeeds, we read back the info file to check that we
206
208
        really got the lock.
207
209
 
252
254
    def _remove_pending_dir(self, tmpname):
253
255
        """Remove the pending directory
254
256
 
255
 
        This is called if we failed to rename into place, so that the pending 
 
257
        This is called if we failed to rename into place, so that the pending
256
258
        dirs don't clutter up the lockdir.
257
259
        """
258
260
        self._trace("remove %s", tmpname)
291
293
            self._fake_read_lock = False
292
294
            return
293
295
        if not self._lock_held:
294
 
            raise LockNotHeld(self)
 
296
            return lock.cant_unlock_not_held(self)
295
297
        if self._locked_via_token:
296
298
            self._locked_via_token = False
297
299
            self._lock_held = False
298
300
        else:
 
301
            old_nonce = self.nonce
299
302
            # rename before deleting, because we can't atomically remove the
300
303
            # whole tree
301
304
            start_time = time.time()
321
324
                self.transport.delete_tree(tmpname)
322
325
            self._trace("... unlock succeeded after %dms",
323
326
                    (time.time() - start_time) * 1000)
 
327
            result = lock.LockResult(self.transport.abspath(self.path),
 
328
                                     old_nonce)
 
329
            for hook in self.hooks['lock_released']:
 
330
                hook(result)
324
331
 
325
332
    def break_lock(self):
326
333
        """Break a lock not held by this instance of LockDir.
335
342
            lock_info = '\n'.join(self._format_lock_info(holder_info))
336
343
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
337
344
                self.force_break(holder_info)
338
 
        
 
345
 
339
346
    def force_break(self, dead_holder_info):
340
347
        """Release a lock held by another process.
341
348
 
349
356
        LockBreakMismatch is raised.
350
357
 
351
358
        After the lock is broken it will not be held by any process.
352
 
        It is possible that another process may sneak in and take the 
 
359
        It is possible that another process may sneak in and take the
353
360
        lock before the breaking process acquires it.
354
361
        """
355
362
        if not isinstance(dead_holder_info, dict):
364
371
        tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20))
365
372
        self.transport.rename(self._held_dir, tmpname)
366
373
        # check that we actually broke the right lock, not someone else;
367
 
        # there's a small race window between checking it and doing the 
 
374
        # there's a small race window between checking it and doing the
368
375
        # rename.
369
376
        broken_info_path = tmpname + self.__INFO_NAME
370
377
        broken_info = self._read_info_file(broken_info_path)
372
379
            raise LockBreakMismatch(self, broken_info, dead_holder_info)
373
380
        self.transport.delete(broken_info_path)
374
381
        self.transport.rmdir(tmpname)
 
382
        result = lock.LockResult(self.transport.abspath(self.path),
 
383
                                 current_info.get('nonce'))
 
384
        for hook in self.hooks['lock_broken']:
 
385
            hook(result)
375
386
 
376
387
    def _check_not_locked(self):
377
388
        """If the lock is held by this instance, raise an error."""
385
396
        or if the lock has been affected by a bug.
386
397
 
387
398
        If the lock is not thought to be held, raises LockNotHeld.  If
388
 
        the lock is thought to be held but has been broken, raises 
 
399
        the lock is thought to be held but has been broken, raises
389
400
        LockBroken.
390
401
        """
391
402
        if not self._lock_held:
397
408
        if info.get('nonce') != self.nonce:
398
409
            # there is a lock, but not ours
399
410
            raise LockBroken(self)
400
 
        
 
411
 
401
412
    def _read_info_file(self, path):
402
413
        """Read one given info file.
403
414
 
407
418
 
408
419
    def peek(self):
409
420
        """Check if the lock is held by anyone.
410
 
        
 
421
 
411
422
        If it is held, this returns the lock info structure as a rio Stanza,
412
423
        which contains some information about the current lock holder.
413
424
        Otherwise returns None.
428
439
            user = config.user_email()
429
440
        except errors.NoEmailInUsername:
430
441
            user = config.username()
431
 
        s = Stanza(hostname=get_host_name(),
 
442
        s = rio.Stanza(hostname=get_host_name(),
432
443
                   pid=str(os.getpid()),
433
444
                   start_time=str(int(time.time())),
434
445
                   nonce=self.nonce,
437
448
        return s.to_string()
438
449
 
439
450
    def _parse_info(self, info_file):
440
 
        return read_stanza(info_file.readlines()).as_dict()
 
451
        return rio.read_stanza(info_file.readlines()).as_dict()
441
452
 
442
453
    def attempt_lock(self):
443
454
        """Take the lock; fail if it's already held.
444
 
        
 
455
 
445
456
        If you wish to block until the lock can be obtained, call wait_lock()
446
457
        instead.
447
458
 
450
461
        """
451
462
        if self._fake_read_lock:
452
463
            raise LockContention(self)
453
 
        return self._attempt_lock()
 
464
        result = self._attempt_lock()
 
465
        hook_result = lock.LockResult(self.transport.abspath(self.path),
 
466
                self.nonce)
 
467
        for hook in self.hooks['lock_acquired']:
 
468
            hook(hook_result)
 
469
        return result
454
470
 
455
471
    def wait_lock(self, timeout=None, poll=None, max_attempts=None):
456
472
        """Wait a certain period for a lock.
463
479
 
464
480
        :param timeout: Approximate maximum amount of time to wait for the
465
481
        lock, in seconds.
466
 
         
 
482
 
467
483
        :param poll: Delay in seconds between retrying the lock.
468
484
 
469
485
        :param max_attempts: Maximum number of times to try to lock.
529
545
            else:
530
546
                self._trace("timeout after waiting %ss", timeout)
531
547
                raise LockContention(self)
532
 
    
 
548
 
533
549
    def leave_in_place(self):
534
550
        self._locked_via_token = True
535
551
 
538
554
 
539
555
    def lock_write(self, token=None):
540
556
        """Wait for and acquire the lock.
541
 
        
 
557
 
542
558
        :param token: if this is already locked, then lock_write will fail
543
559
            unless the token matches the existing lock.
544
560
        :returns: a token if this instance supports tokens, otherwise None.
550
566
        A token should be passed in if you know that you have locked the object
551
567
        some other way, and need to synchronise this object's state with that
552
568
        fact.
553
 
         
 
569
 
554
570
        XXX: docstring duplicated from LockableFiles.lock_write.
555
571
        """
556
572
        if token is not None:
565
581
    def lock_read(self):
566
582
        """Compatibility-mode shared lock.
567
583
 
568
 
        LockDir doesn't support shared read-only locks, so this 
 
584
        LockDir doesn't support shared read-only locks, so this
569
585
        just pretends that the lock is taken but really does nothing.
570
586
        """
571
 
        # At the moment Branches are commonly locked for read, but 
 
587
        # At the moment Branches are commonly locked for read, but
572
588
        # we can't rely on that remotely.  Once this is cleaned up,
573
 
        # reenable this warning to prevent it coming back in 
 
589
        # reenable this warning to prevent it coming back in
574
590
        # -- mbp 20060303
575
591
        ## warn("LockDir.lock_read falls back to write lock")
576
592
        if self._lock_held or self._fake_read_lock: