~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lockdir.py

  • Committer: Naoki INADA
  • Date: 2009-10-29 10:01:19 UTC
  • mto: (4634.97.3 2.0)
  • mto: This revision was merged to the branch mainline in revision 4798.
  • Revision ID: inada-n@klab.jp-20091029100119-uckv9t7ej2qrghw3
import doc-ja rev90

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
 
        assert isinstance(transport, Transport), \
171
 
            ("not a transport: %r" % transport)
172
172
        self.transport = transport
173
173
        self.path = path
174
174
        self._lock_held = False
191
191
    def create(self, mode=None):
192
192
        """Create the on-disk lock.
193
193
 
194
 
        This is typically only called when the object/directory containing the 
 
194
        This is typically only called when the object/directory containing the
195
195
        directory is first created.  The lock is not held when it's created.
196
196
        """
197
197
        self._trace("create lock directory")
203
203
 
204
204
    def _attempt_lock(self):
205
205
        """Make the pending directory and attempt to rename into place.
206
 
        
 
206
 
207
207
        If the rename succeeds, we read back the info file to check that we
208
208
        really got the lock.
209
209
 
254
254
    def _remove_pending_dir(self, tmpname):
255
255
        """Remove the pending directory
256
256
 
257
 
        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
258
258
        dirs don't clutter up the lockdir.
259
259
        """
260
260
        self._trace("remove %s", tmpname)
293
293
            self._fake_read_lock = False
294
294
            return
295
295
        if not self._lock_held:
296
 
            raise LockNotHeld(self)
 
296
            return lock.cant_unlock_not_held(self)
297
297
        if self._locked_via_token:
298
298
            self._locked_via_token = False
299
299
            self._lock_held = False
300
300
        else:
 
301
            old_nonce = self.nonce
301
302
            # rename before deleting, because we can't atomically remove the
302
303
            # whole tree
303
304
            start_time = time.time()
323
324
                self.transport.delete_tree(tmpname)
324
325
            self._trace("... unlock succeeded after %dms",
325
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)
326
331
 
327
332
    def break_lock(self):
328
333
        """Break a lock not held by this instance of LockDir.
337
342
            lock_info = '\n'.join(self._format_lock_info(holder_info))
338
343
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
339
344
                self.force_break(holder_info)
340
 
        
 
345
 
341
346
    def force_break(self, dead_holder_info):
342
347
        """Release a lock held by another process.
343
348
 
351
356
        LockBreakMismatch is raised.
352
357
 
353
358
        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 
 
359
        It is possible that another process may sneak in and take the
355
360
        lock before the breaking process acquires it.
356
361
        """
357
362
        if not isinstance(dead_holder_info, dict):
366
371
        tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20))
367
372
        self.transport.rename(self._held_dir, tmpname)
368
373
        # check that we actually broke the right lock, not someone else;
369
 
        # 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
370
375
        # rename.
371
376
        broken_info_path = tmpname + self.__INFO_NAME
372
377
        broken_info = self._read_info_file(broken_info_path)
374
379
            raise LockBreakMismatch(self, broken_info, dead_holder_info)
375
380
        self.transport.delete(broken_info_path)
376
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)
377
386
 
378
387
    def _check_not_locked(self):
379
388
        """If the lock is held by this instance, raise an error."""
387
396
        or if the lock has been affected by a bug.
388
397
 
389
398
        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 
 
399
        the lock is thought to be held but has been broken, raises
391
400
        LockBroken.
392
401
        """
393
402
        if not self._lock_held:
399
408
        if info.get('nonce') != self.nonce:
400
409
            # there is a lock, but not ours
401
410
            raise LockBroken(self)
402
 
        
 
411
 
403
412
    def _read_info_file(self, path):
404
413
        """Read one given info file.
405
414
 
409
418
 
410
419
    def peek(self):
411
420
        """Check if the lock is held by anyone.
412
 
        
 
421
 
413
422
        If it is held, this returns the lock info structure as a rio Stanza,
414
423
        which contains some information about the current lock holder.
415
424
        Otherwise returns None.
417
426
        try:
418
427
            info = self._read_info_file(self._held_info_path)
419
428
            self._trace("peek -> held")
420
 
            assert isinstance(info, dict), \
421
 
                    "bad parse result %r" % info
422
429
            return info
423
430
        except NoSuchFile, e:
424
431
            self._trace("peek -> not held")
426
433
    def _prepare_info(self):
427
434
        """Write information about a pending lock to a temporary file.
428
435
        """
429
 
        import socket
430
436
        # XXX: is creating this here inefficient?
431
437
        config = bzrlib.config.GlobalConfig()
432
438
        try:
433
439
            user = config.user_email()
434
440
        except errors.NoEmailInUsername:
435
441
            user = config.username()
436
 
        s = Stanza(hostname=socket.gethostname(),
 
442
        s = rio.Stanza(hostname=get_host_name(),
437
443
                   pid=str(os.getpid()),
438
444
                   start_time=str(int(time.time())),
439
445
                   nonce=self.nonce,
442
448
        return s.to_string()
443
449
 
444
450
    def _parse_info(self, info_file):
445
 
        return read_stanza(info_file.readlines()).as_dict()
 
451
        return rio.read_stanza(info_file.readlines()).as_dict()
446
452
 
447
453
    def attempt_lock(self):
448
454
        """Take the lock; fail if it's already held.
449
 
        
 
455
 
450
456
        If you wish to block until the lock can be obtained, call wait_lock()
451
457
        instead.
452
458
 
455
461
        """
456
462
        if self._fake_read_lock:
457
463
            raise LockContention(self)
458
 
        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
459
470
 
460
471
    def wait_lock(self, timeout=None, poll=None, max_attempts=None):
461
472
        """Wait a certain period for a lock.
468
479
 
469
480
        :param timeout: Approximate maximum amount of time to wait for the
470
481
        lock, in seconds.
471
 
         
 
482
 
472
483
        :param poll: Delay in seconds between retrying the lock.
473
484
 
474
485
        :param max_attempts: Maximum number of times to try to lock.
510
521
                if deadline_str is None:
511
522
                    deadline_str = time.strftime('%H:%M:%S',
512
523
                                                 time.localtime(deadline))
 
524
                lock_url = self.transport.abspath(self.path)
513
525
                self._report_function('%s %s\n'
514
526
                                      '%s\n' # held by
515
527
                                      '%s\n' # locked ... ago
516
 
                                      'Will continue to try until %s\n',
 
528
                                      'Will continue to try until %s, unless '
 
529
                                      'you press Ctrl-C\n'
 
530
                                      'If you\'re sure that it\'s not being '
 
531
                                      'modified, use bzr break-lock %s',
517
532
                                      start,
518
533
                                      formatted_info[0],
519
534
                                      formatted_info[1],
520
535
                                      formatted_info[2],
521
 
                                      deadline_str)
 
536
                                      deadline_str,
 
537
                                      lock_url)
522
538
 
523
539
            if (max_attempts is not None) and (attempt_count >= max_attempts):
524
540
                self._trace("exceeded %d attempts")
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: