/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/lockdir.py

  • Committer: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2006-2010 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
    osutils,
113
114
    )
114
115
import bzrlib.config
 
116
from bzrlib.decorators import only_raises
115
117
from bzrlib.errors import (
116
118
        DirectoryNotEmpty,
117
119
        FileExists,
124
126
        PathError,
125
127
        ResourceBusy,
126
128
        TransportError,
127
 
        UnlockableTransport,
128
129
        )
129
130
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
 
131
from bzrlib.osutils import format_delta, rand_chars, get_host_name
133
132
import bzrlib.ui
134
133
 
 
134
from bzrlib.lazy_import import lazy_import
 
135
lazy_import(globals(), """
 
136
from bzrlib import rio
 
137
""")
135
138
 
136
139
# XXX: At the moment there is no consideration of thread safety on LockDir
137
140
# objects.  This should perhaps be updated - e.g. if two threads try to take a
152
155
_DEFAULT_POLL_SECONDS = 1.0
153
156
 
154
157
 
155
 
class LockDir(object):
156
 
    """Write-lock guarding access to data."""
 
158
class LockDir(lock.Lock):
 
159
    """Write-lock guarding access to data.
 
160
    """
157
161
 
158
162
    __INFO_NAME = '/info'
159
163
 
164
168
 
165
169
        :param transport: Transport which will contain the lock
166
170
 
167
 
        :param path: Path to the lock within the base directory of the 
 
171
        :param path: Path to the lock within the base directory of the
168
172
            transport.
169
173
        """
170
 
        assert isinstance(transport, Transport), \
171
 
            ("not a transport: %r" % transport)
172
174
        self.transport = transport
173
175
        self.path = path
174
176
        self._lock_held = False
191
193
    def create(self, mode=None):
192
194
        """Create the on-disk lock.
193
195
 
194
 
        This is typically only called when the object/directory containing the 
 
196
        This is typically only called when the object/directory containing the
195
197
        directory is first created.  The lock is not held when it's created.
196
198
        """
197
199
        self._trace("create lock directory")
203
205
 
204
206
    def _attempt_lock(self):
205
207
        """Make the pending directory and attempt to rename into place.
206
 
        
 
208
 
207
209
        If the rename succeeds, we read back the info file to check that we
208
210
        really got the lock.
209
211
 
240
242
        # incorrect.  It's possible some other servers or filesystems will
241
243
        # have a similar bug allowing someone to think they got the lock
242
244
        # when it's already held.
 
245
        #
 
246
        # See <https://bugs.edge.launchpad.net/bzr/+bug/498378> for one case.
 
247
        #
 
248
        # Strictly the check is unnecessary and a waste of time for most
 
249
        # people, but probably worth trapping if something is wrong.
243
250
        info = self.peek()
244
251
        self._trace("after locking, info=%r", info)
245
 
        if info['nonce'] != self.nonce:
 
252
        if info is None:
 
253
            raise LockFailed(self, "lock was renamed into place, but "
 
254
                "now is missing!")
 
255
        if info.get('nonce') != self.nonce:
246
256
            self._trace("rename succeeded, "
247
257
                "but lock is still held by someone else")
248
258
            raise LockContention(self)
254
264
    def _remove_pending_dir(self, tmpname):
255
265
        """Remove the pending directory
256
266
 
257
 
        This is called if we failed to rename into place, so that the pending 
 
267
        This is called if we failed to rename into place, so that the pending
258
268
        dirs don't clutter up the lockdir.
259
269
        """
260
270
        self._trace("remove %s", tmpname)
286
296
                                            info_bytes)
287
297
        return tmpname
288
298
 
 
299
    @only_raises(LockNotHeld, LockBroken)
289
300
    def unlock(self):
290
301
        """Release a held lock
291
302
        """
293
304
            self._fake_read_lock = False
294
305
            return
295
306
        if not self._lock_held:
296
 
            raise LockNotHeld(self)
 
307
            return lock.cant_unlock_not_held(self)
297
308
        if self._locked_via_token:
298
309
            self._locked_via_token = False
299
310
            self._lock_held = False
300
311
        else:
 
312
            old_nonce = self.nonce
301
313
            # rename before deleting, because we can't atomically remove the
302
314
            # whole tree
303
315
            start_time = time.time()
323
335
                self.transport.delete_tree(tmpname)
324
336
            self._trace("... unlock succeeded after %dms",
325
337
                    (time.time() - start_time) * 1000)
 
338
            result = lock.LockResult(self.transport.abspath(self.path),
 
339
                                     old_nonce)
 
340
            for hook in self.hooks['lock_released']:
 
341
                hook(result)
326
342
 
327
343
    def break_lock(self):
328
344
        """Break a lock not held by this instance of LockDir.
337
353
            lock_info = '\n'.join(self._format_lock_info(holder_info))
338
354
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
339
355
                self.force_break(holder_info)
340
 
        
 
356
 
341
357
    def force_break(self, dead_holder_info):
342
358
        """Release a lock held by another process.
343
359
 
351
367
        LockBreakMismatch is raised.
352
368
 
353
369
        After the lock is broken it will not be held by any process.
354
 
        It is possible that another process may sneak in and take the 
 
370
        It is possible that another process may sneak in and take the
355
371
        lock before the breaking process acquires it.
356
372
        """
357
373
        if not isinstance(dead_holder_info, dict):
366
382
        tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20))
367
383
        self.transport.rename(self._held_dir, tmpname)
368
384
        # check that we actually broke the right lock, not someone else;
369
 
        # there's a small race window between checking it and doing the 
 
385
        # there's a small race window between checking it and doing the
370
386
        # rename.
371
387
        broken_info_path = tmpname + self.__INFO_NAME
372
388
        broken_info = self._read_info_file(broken_info_path)
374
390
            raise LockBreakMismatch(self, broken_info, dead_holder_info)
375
391
        self.transport.delete(broken_info_path)
376
392
        self.transport.rmdir(tmpname)
 
393
        result = lock.LockResult(self.transport.abspath(self.path),
 
394
                                 current_info.get('nonce'))
 
395
        for hook in self.hooks['lock_broken']:
 
396
            hook(result)
377
397
 
378
398
    def _check_not_locked(self):
379
399
        """If the lock is held by this instance, raise an error."""
387
407
        or if the lock has been affected by a bug.
388
408
 
389
409
        If the lock is not thought to be held, raises LockNotHeld.  If
390
 
        the lock is thought to be held but has been broken, raises 
 
410
        the lock is thought to be held but has been broken, raises
391
411
        LockBroken.
392
412
        """
393
413
        if not self._lock_held:
399
419
        if info.get('nonce') != self.nonce:
400
420
            # there is a lock, but not ours
401
421
            raise LockBroken(self)
402
 
        
 
422
 
403
423
    def _read_info_file(self, path):
404
424
        """Read one given info file.
405
425
 
406
426
        peek() reads the info file of the lock holder, if any.
407
427
        """
408
 
        return self._parse_info(self.transport.get(path))
 
428
        return self._parse_info(self.transport.get_bytes(path))
409
429
 
410
430
    def peek(self):
411
431
        """Check if the lock is held by anyone.
412
 
        
413
 
        If it is held, this returns the lock info structure as a rio Stanza,
 
432
 
 
433
        If it is held, this returns the lock info structure as a dict
414
434
        which contains some information about the current lock holder.
415
435
        Otherwise returns None.
416
436
        """
417
437
        try:
418
438
            info = self._read_info_file(self._held_info_path)
419
439
            self._trace("peek -> held")
420
 
            assert isinstance(info, dict), \
421
 
                    "bad parse result %r" % info
422
440
            return info
423
441
        except NoSuchFile, e:
424
442
            self._trace("peek -> not held")
426
444
    def _prepare_info(self):
427
445
        """Write information about a pending lock to a temporary file.
428
446
        """
429
 
        import socket
430
447
        # XXX: is creating this here inefficient?
431
448
        config = bzrlib.config.GlobalConfig()
432
449
        try:
433
450
            user = config.user_email()
434
451
        except errors.NoEmailInUsername:
435
452
            user = config.username()
436
 
        s = Stanza(hostname=socket.gethostname(),
 
453
        s = rio.Stanza(hostname=get_host_name(),
437
454
                   pid=str(os.getpid()),
438
455
                   start_time=str(int(time.time())),
439
456
                   nonce=self.nonce,
441
458
                   )
442
459
        return s.to_string()
443
460
 
444
 
    def _parse_info(self, info_file):
445
 
        return read_stanza(info_file.readlines()).as_dict()
 
461
    def _parse_info(self, info_bytes):
 
462
        stanza = rio.read_stanza(osutils.split_lines(info_bytes))
 
463
        if stanza is None:
 
464
            # see bug 185013; we fairly often end up with the info file being
 
465
            # empty after an interruption; we could log a message here but
 
466
            # there may not be much we can say
 
467
            return {}
 
468
        else:
 
469
            return stanza.as_dict()
446
470
 
447
471
    def attempt_lock(self):
448
472
        """Take the lock; fail if it's already held.
449
 
        
 
473
 
450
474
        If you wish to block until the lock can be obtained, call wait_lock()
451
475
        instead.
452
476
 
455
479
        """
456
480
        if self._fake_read_lock:
457
481
            raise LockContention(self)
458
 
        return self._attempt_lock()
 
482
        result = self._attempt_lock()
 
483
        hook_result = lock.LockResult(self.transport.abspath(self.path),
 
484
                self.nonce)
 
485
        for hook in self.hooks['lock_acquired']:
 
486
            hook(hook_result)
 
487
        return result
459
488
 
460
489
    def wait_lock(self, timeout=None, poll=None, max_attempts=None):
461
490
        """Wait a certain period for a lock.
468
497
 
469
498
        :param timeout: Approximate maximum amount of time to wait for the
470
499
        lock, in seconds.
471
 
         
 
500
 
472
501
        :param poll: Delay in seconds between retrying the lock.
473
502
 
474
503
        :param max_attempts: Maximum number of times to try to lock.
510
539
                if deadline_str is None:
511
540
                    deadline_str = time.strftime('%H:%M:%S',
512
541
                                                 time.localtime(deadline))
 
542
                lock_url = self.transport.abspath(self.path)
 
543
                # See <https://bugs.edge.launchpad.net/bzr/+bug/250451>
 
544
                # the URL here is sometimes not one that is useful to the
 
545
                # user, perhaps being wrapped in a lp-%d or chroot decorator,
 
546
                # especially if this error is issued from the server.
513
547
                self._report_function('%s %s\n'
514
 
                                      '%s\n' # held by
515
 
                                      '%s\n' # locked ... ago
516
 
                                      'Will continue to try until %s\n',
517
 
                                      start,
518
 
                                      formatted_info[0],
519
 
                                      formatted_info[1],
520
 
                                      formatted_info[2],
521
 
                                      deadline_str)
 
548
                    '%s\n' # held by
 
549
                    '%s\n' # locked ... ago
 
550
                    'Will continue to try until %s, unless '
 
551
                    'you press Ctrl-C.\n'
 
552
                    'See "bzr help break-lock" for more.',
 
553
                    start,
 
554
                    formatted_info[0],
 
555
                    formatted_info[1],
 
556
                    formatted_info[2],
 
557
                    deadline_str,
 
558
                    )
522
559
 
523
560
            if (max_attempts is not None) and (attempt_count >= max_attempts):
524
561
                self._trace("exceeded %d attempts")
529
566
            else:
530
567
                self._trace("timeout after waiting %ss", timeout)
531
568
                raise LockContention(self)
532
 
    
 
569
 
533
570
    def leave_in_place(self):
534
571
        self._locked_via_token = True
535
572
 
538
575
 
539
576
    def lock_write(self, token=None):
540
577
        """Wait for and acquire the lock.
541
 
        
 
578
 
542
579
        :param token: if this is already locked, then lock_write will fail
543
580
            unless the token matches the existing lock.
544
581
        :returns: a token if this instance supports tokens, otherwise None.
550
587
        A token should be passed in if you know that you have locked the object
551
588
        some other way, and need to synchronise this object's state with that
552
589
        fact.
553
 
         
 
590
 
554
591
        XXX: docstring duplicated from LockableFiles.lock_write.
555
592
        """
556
593
        if token is not None:
565
602
    def lock_read(self):
566
603
        """Compatibility-mode shared lock.
567
604
 
568
 
        LockDir doesn't support shared read-only locks, so this 
 
605
        LockDir doesn't support shared read-only locks, so this
569
606
        just pretends that the lock is taken but really does nothing.
570
607
        """
571
 
        # At the moment Branches are commonly locked for read, but 
 
608
        # At the moment Branches are commonly locked for read, but
572
609
        # we can't rely on that remotely.  Once this is cleaned up,
573
 
        # reenable this warning to prevent it coming back in 
 
610
        # reenable this warning to prevent it coming back in
574
611
        # -- mbp 20060303
575
612
        ## warn("LockDir.lock_read falls back to write lock")
576
613
        if self._lock_held or self._fake_read_lock:
580
617
    def _format_lock_info(self, info):
581
618
        """Turn the contents of peek() into something for the user"""
582
619
        lock_url = self.transport.abspath(self.path)
583
 
        delta = time.time() - int(info['start_time'])
 
620
        start_time = info.get('start_time')
 
621
        if start_time is None:
 
622
            time_ago = '(unknown)'
 
623
        else:
 
624
            time_ago = format_delta(time.time() - int(info['start_time']))
584
625
        return [
585
626
            'lock %s' % (lock_url,),
586
 
            'held by %(user)s on host %(hostname)s [process #%(pid)s]' % info,
587
 
            'locked %s' % (format_delta(delta),),
 
627
            'held by %s on host %s [process #%s]' %
 
628
                tuple([info.get(x, '<unknown>') for x in ['user', 'hostname', 'pid']]),
 
629
            'locked %s' % (time_ago,),
588
630
            ]
589
631
 
590
632
    def validate_token(self, token):