~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lockdir.py

NEWS section template into a separate file

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
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
 
238
240
        # incorrect.  It's possible some other servers or filesystems will
239
241
        # have a similar bug allowing someone to think they got the lock
240
242
        # when it's already held.
 
243
        #
 
244
        # See <https://bugs.edge.launchpad.net/bzr/+bug/498378> for one case.
 
245
        #
 
246
        # Strictly the check is unnecessary and a waste of time for most
 
247
        # people, but probably worth trapping if something is wrong.
241
248
        info = self.peek()
242
249
        self._trace("after locking, info=%r", info)
 
250
        if info is None:
 
251
            raise LockFailed(self, "lock was renamed into place, but "
 
252
                "now is missing!")
243
253
        if info['nonce'] != self.nonce:
244
254
            self._trace("rename succeeded, "
245
255
                "but lock is still held by someone else")
252
262
    def _remove_pending_dir(self, tmpname):
253
263
        """Remove the pending directory
254
264
 
255
 
        This is called if we failed to rename into place, so that the pending 
 
265
        This is called if we failed to rename into place, so that the pending
256
266
        dirs don't clutter up the lockdir.
257
267
        """
258
268
        self._trace("remove %s", tmpname)
291
301
            self._fake_read_lock = False
292
302
            return
293
303
        if not self._lock_held:
294
 
            raise LockNotHeld(self)
 
304
            return lock.cant_unlock_not_held(self)
295
305
        if self._locked_via_token:
296
306
            self._locked_via_token = False
297
307
            self._lock_held = False
298
308
        else:
 
309
            old_nonce = self.nonce
299
310
            # rename before deleting, because we can't atomically remove the
300
311
            # whole tree
301
312
            start_time = time.time()
321
332
                self.transport.delete_tree(tmpname)
322
333
            self._trace("... unlock succeeded after %dms",
323
334
                    (time.time() - start_time) * 1000)
 
335
            result = lock.LockResult(self.transport.abspath(self.path),
 
336
                                     old_nonce)
 
337
            for hook in self.hooks['lock_released']:
 
338
                hook(result)
324
339
 
325
340
    def break_lock(self):
326
341
        """Break a lock not held by this instance of LockDir.
335
350
            lock_info = '\n'.join(self._format_lock_info(holder_info))
336
351
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
337
352
                self.force_break(holder_info)
338
 
        
 
353
 
339
354
    def force_break(self, dead_holder_info):
340
355
        """Release a lock held by another process.
341
356
 
349
364
        LockBreakMismatch is raised.
350
365
 
351
366
        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 
 
367
        It is possible that another process may sneak in and take the
353
368
        lock before the breaking process acquires it.
354
369
        """
355
370
        if not isinstance(dead_holder_info, dict):
364
379
        tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20))
365
380
        self.transport.rename(self._held_dir, tmpname)
366
381
        # check that we actually broke the right lock, not someone else;
367
 
        # there's a small race window between checking it and doing the 
 
382
        # there's a small race window between checking it and doing the
368
383
        # rename.
369
384
        broken_info_path = tmpname + self.__INFO_NAME
370
385
        broken_info = self._read_info_file(broken_info_path)
372
387
            raise LockBreakMismatch(self, broken_info, dead_holder_info)
373
388
        self.transport.delete(broken_info_path)
374
389
        self.transport.rmdir(tmpname)
 
390
        result = lock.LockResult(self.transport.abspath(self.path),
 
391
                                 current_info.get('nonce'))
 
392
        for hook in self.hooks['lock_broken']:
 
393
            hook(result)
375
394
 
376
395
    def _check_not_locked(self):
377
396
        """If the lock is held by this instance, raise an error."""
385
404
        or if the lock has been affected by a bug.
386
405
 
387
406
        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 
 
407
        the lock is thought to be held but has been broken, raises
389
408
        LockBroken.
390
409
        """
391
410
        if not self._lock_held:
397
416
        if info.get('nonce') != self.nonce:
398
417
            # there is a lock, but not ours
399
418
            raise LockBroken(self)
400
 
        
 
419
 
401
420
    def _read_info_file(self, path):
402
421
        """Read one given info file.
403
422
 
407
426
 
408
427
    def peek(self):
409
428
        """Check if the lock is held by anyone.
410
 
        
 
429
 
411
430
        If it is held, this returns the lock info structure as a rio Stanza,
412
431
        which contains some information about the current lock holder.
413
432
        Otherwise returns None.
422
441
    def _prepare_info(self):
423
442
        """Write information about a pending lock to a temporary file.
424
443
        """
425
 
        import socket
426
444
        # XXX: is creating this here inefficient?
427
445
        config = bzrlib.config.GlobalConfig()
428
446
        try:
429
447
            user = config.user_email()
430
448
        except errors.NoEmailInUsername:
431
449
            user = config.username()
432
 
        s = Stanza(hostname=socket.gethostname(),
 
450
        s = rio.Stanza(hostname=get_host_name(),
433
451
                   pid=str(os.getpid()),
434
452
                   start_time=str(int(time.time())),
435
453
                   nonce=self.nonce,
438
456
        return s.to_string()
439
457
 
440
458
    def _parse_info(self, info_file):
441
 
        return read_stanza(info_file.readlines()).as_dict()
 
459
        return rio.read_stanza(info_file.readlines()).as_dict()
442
460
 
443
461
    def attempt_lock(self):
444
462
        """Take the lock; fail if it's already held.
445
 
        
 
463
 
446
464
        If you wish to block until the lock can be obtained, call wait_lock()
447
465
        instead.
448
466
 
451
469
        """
452
470
        if self._fake_read_lock:
453
471
            raise LockContention(self)
454
 
        return self._attempt_lock()
 
472
        result = self._attempt_lock()
 
473
        hook_result = lock.LockResult(self.transport.abspath(self.path),
 
474
                self.nonce)
 
475
        for hook in self.hooks['lock_acquired']:
 
476
            hook(hook_result)
 
477
        return result
455
478
 
456
479
    def wait_lock(self, timeout=None, poll=None, max_attempts=None):
457
480
        """Wait a certain period for a lock.
464
487
 
465
488
        :param timeout: Approximate maximum amount of time to wait for the
466
489
        lock, in seconds.
467
 
         
 
490
 
468
491
        :param poll: Delay in seconds between retrying the lock.
469
492
 
470
493
        :param max_attempts: Maximum number of times to try to lock.
530
553
            else:
531
554
                self._trace("timeout after waiting %ss", timeout)
532
555
                raise LockContention(self)
533
 
    
 
556
 
534
557
    def leave_in_place(self):
535
558
        self._locked_via_token = True
536
559
 
539
562
 
540
563
    def lock_write(self, token=None):
541
564
        """Wait for and acquire the lock.
542
 
        
 
565
 
543
566
        :param token: if this is already locked, then lock_write will fail
544
567
            unless the token matches the existing lock.
545
568
        :returns: a token if this instance supports tokens, otherwise None.
551
574
        A token should be passed in if you know that you have locked the object
552
575
        some other way, and need to synchronise this object's state with that
553
576
        fact.
554
 
         
 
577
 
555
578
        XXX: docstring duplicated from LockableFiles.lock_write.
556
579
        """
557
580
        if token is not None:
566
589
    def lock_read(self):
567
590
        """Compatibility-mode shared lock.
568
591
 
569
 
        LockDir doesn't support shared read-only locks, so this 
 
592
        LockDir doesn't support shared read-only locks, so this
570
593
        just pretends that the lock is taken but really does nothing.
571
594
        """
572
 
        # At the moment Branches are commonly locked for read, but 
 
595
        # At the moment Branches are commonly locked for read, but
573
596
        # we can't rely on that remotely.  Once this is cleaned up,
574
 
        # reenable this warning to prevent it coming back in 
 
597
        # reenable this warning to prevent it coming back in
575
598
        # -- mbp 20060303
576
599
        ## warn("LockDir.lock_read falls back to write lock")
577
600
        if self._lock_held or self._fake_read_lock: