1
# Copyright (C) 2006, 2007 Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
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
 
 
17
"""On-disk mutex protecting a resource
 
 
19
bzr on-disk objects are locked by the existence of a directory with a
 
 
20
particular name within the control directory.  We use this rather than OS
 
 
21
internal locks (such as flock etc) because they can be seen across all
 
 
22
transports, including http.
 
 
24
Objects can be read if there is only physical read access; therefore 
 
 
25
readers can never be required to create a lock, though they will
 
 
26
check whether a writer is using the lock.  Writers can't detect
 
 
27
whether anyone else is reading from the resource as they write.
 
 
28
This works because of ordering constraints that make sure readers
 
 
29
see a consistent view of existing data.
 
 
31
Waiting for a lock must be done by polling; this can be aborted after
 
 
34
Locks must always be explicitly released, typically from a try/finally
 
 
35
block -- they are not released from a finalizer or when Python
 
 
38
Locks may fail to be released if the process is abruptly terminated
 
 
39
(machine stop, SIGKILL) or if a remote transport becomes permanently
 
 
40
disconnected.  There is therefore a method to break an existing lock.
 
 
41
This should rarely be used, and generally only with user approval.
 
 
42
Locks contain some information on when the lock was taken and by who
 
 
43
which may guide in deciding whether it can safely be broken.  (This is
 
 
44
similar to the messages displayed by emacs and vim.) Note that if the
 
 
45
lock holder is still alive they will get no notification that the lock
 
 
46
has been broken and will continue their work -- so it is important to be
 
 
47
sure they are actually dead.
 
 
49
A lock is represented on disk by a directory of a particular name,
 
 
50
containing an information file.  Taking a lock is done by renaming a
 
 
51
temporary directory into place.  We use temporary directories because
 
 
52
for all known transports and filesystems we believe that exactly one
 
 
53
attempt to claim the lock will succeed and the others will fail.  (Files
 
 
54
won't do because some filesystems or transports only have
 
 
55
rename-and-overwrite, making it hard to tell who won.)
 
 
57
The desired characteristics are:
 
 
59
* Locks are not reentrant.  (That is, a client that tries to take a 
 
 
60
  lock it already holds may deadlock or fail.)
 
 
61
* Stale locks can be guessed at by a heuristic
 
 
62
* Lost locks can be broken by any client
 
 
63
* Failed lock operations leave little or no mess
 
 
64
* Deadlocks are avoided by having a timeout always in use, clients
 
 
65
  desiring indefinite waits can retry or set a silly big timeout.
 
 
67
Storage formats use the locks, and also need to consider concurrency
 
 
68
issues underneath the lock.  A format may choose not to use a lock
 
 
69
at all for some operations.
 
 
71
LockDirs always operate over a Transport.  The transport may be readonly, in
 
 
72
which case the lock can be queried but not acquired.
 
 
74
Locks are identified by a path name, relative to a base transport.
 
 
76
Calling code will typically want to make sure there is exactly one LockDir
 
 
77
object per actual lock on disk.  This module does nothing to prevent aliasing
 
 
78
and deadlocks will likely occur if the locks are aliased.
 
 
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 
 
 
82
update the timestamp within it.
 
 
86
>>> from bzrlib.transport.memory import MemoryTransport
 
 
87
>>> # typically will be obtained from a BzrDir, Branch, etc
 
 
88
>>> t = MemoryTransport()
 
 
89
>>> l = LockDir(t, 'sample-lock')
 
 
91
>>> token = l.wait_lock()
 
 
92
>>> # do something here
 
 
98
# TODO: We sometimes have the problem that our attempt to rename '1234' to
 
 
99
# 'held' fails because the transport server moves into an existing directory,
 
 
100
# rather than failing the rename.  If we made the info file name the same as
 
 
101
# the locked directory name we would avoid this problem because moving into
 
 
102
# the held directory would implicitly clash.  However this would not mesh with
 
 
103
# the existing locking code and needs a new format of the containing object.
 
 
104
# -- robertc, mbp 20070628
 
 
108
from cStringIO import StringIO
 
 
115
from bzrlib.errors import (
 
 
129
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
 
 
136
# XXX: At the moment there is no consideration of thread safety on LockDir
 
 
137
# objects.  This should perhaps be updated - e.g. if two threads try to take a
 
 
138
# lock at the same time they should *both* get it.  But then that's unlikely
 
 
141
# TODO: Perhaps store some kind of note like the bzr command line in the lock
 
 
144
# TODO: Some kind of callback run while polling a lock to show progress
 
 
147
# TODO: Make sure to pass the right file and directory mode bits to all
 
 
148
# files/dirs created.
 
 
151
_DEFAULT_TIMEOUT_SECONDS = 300
 
 
152
_DEFAULT_POLL_SECONDS = 1.0
 
 
155
class LockDir(object):
 
 
156
    """Write-lock guarding access to data."""
 
 
158
    __INFO_NAME = '/info'
 
 
160
    def __init__(self, transport, path, file_modebits=0644, dir_modebits=0755):
 
 
161
        """Create a new LockDir object.
 
 
163
        The LockDir is initially unlocked - this just creates the object.
 
 
165
        :param transport: Transport which will contain the lock
 
 
167
        :param path: Path to the lock within the base directory of the 
 
 
170
        assert isinstance(transport, Transport), \
 
 
171
            ("not a transport: %r" % transport)
 
 
172
        self.transport = transport
 
 
174
        self._lock_held = False
 
 
175
        self._locked_via_token = False
 
 
176
        self._fake_read_lock = False
 
 
177
        self._held_dir = path + '/held'
 
 
178
        self._held_info_path = self._held_dir + self.__INFO_NAME
 
 
179
        self._file_modebits = file_modebits
 
 
180
        self._dir_modebits = dir_modebits
 
 
182
        self._report_function = note
 
 
185
        return '%s(%s%s)' % (self.__class__.__name__,
 
 
189
    is_held = property(lambda self: self._lock_held)
 
 
191
    def create(self, mode=None):
 
 
192
        """Create the on-disk lock.
 
 
194
        This is typically only called when the object/directory containing the 
 
 
195
        directory is first created.  The lock is not held when it's created.
 
 
197
        self._trace("create lock directory")
 
 
199
            self.transport.mkdir(self.path, mode=mode)
 
 
200
        except (TransportError, PathError), e:
 
 
201
            raise LockFailed(self, e)
 
 
204
    def _attempt_lock(self):
 
 
205
        """Make the pending directory and attempt to rename into place.
 
 
207
        If the rename succeeds, we read back the info file to check that we
 
 
210
        If we fail to acquire the lock, this method is responsible for
 
 
211
        cleaning up the pending directory if possible.  (But it doesn't do
 
 
214
        :returns: The nonce of the lock, if it was successfully acquired.
 
 
216
        :raises LockContention: If the lock is held by someone else.  The exception
 
 
217
            contains the info of the current holder of the lock.
 
 
219
        self._trace("lock_write...")
 
 
220
        start_time = time.time()
 
 
222
            tmpname = self._create_pending_dir()
 
 
223
        except (errors.TransportError, PathError), e:
 
 
224
            self._trace("... failed to create pending dir, %s", e)
 
 
225
            raise LockFailed(self, e)
 
 
227
            self.transport.rename(tmpname, self._held_dir)
 
 
228
        except (errors.TransportError, PathError, DirectoryNotEmpty,
 
 
229
                FileExists, ResourceBusy), e:
 
 
230
            self._trace("... contention, %s", e)
 
 
231
            self._remove_pending_dir(tmpname)
 
 
232
            raise LockContention(self)
 
 
234
            self._trace("... lock failed, %s", e)
 
 
235
            self._remove_pending_dir(tmpname)
 
 
237
        # We must check we really got the lock, because Launchpad's sftp
 
 
238
        # server at one time had a bug were the rename would successfully
 
 
239
        # move the new directory into the existing directory, which was
 
 
240
        # incorrect.  It's possible some other servers or filesystems will
 
 
241
        # have a similar bug allowing someone to think they got the lock
 
 
242
        # when it's already held.
 
 
244
        self._trace("after locking, info=%r", info)
 
 
245
        if info['nonce'] != self.nonce:
 
 
246
            self._trace("rename succeeded, "
 
 
247
                "but lock is still held by someone else")
 
 
248
            raise LockContention(self)
 
 
249
        self._lock_held = True
 
 
250
        self._trace("... lock succeeded after %dms",
 
 
251
                (time.time() - start_time) * 1000)
 
 
254
    def _remove_pending_dir(self, tmpname):
 
 
255
        """Remove the pending directory
 
 
257
        This is called if we failed to rename into place, so that the pending 
 
 
258
        dirs don't clutter up the lockdir.
 
 
260
        self._trace("remove %s", tmpname)
 
 
262
            self.transport.delete(tmpname + self.__INFO_NAME)
 
 
263
            self.transport.rmdir(tmpname)
 
 
265
            note("error removing pending lock: %s", e)
 
 
267
    def _create_pending_dir(self):
 
 
268
        tmpname = '%s/%s.tmp' % (self.path, rand_chars(10))
 
 
270
            self.transport.mkdir(tmpname)
 
 
272
            # This may raise a FileExists exception
 
 
273
            # which is okay, it will be caught later and determined
 
 
274
            # to be a LockContention.
 
 
275
            self._trace("lock directory does not exist, creating it")
 
 
276
            self.create(mode=self._dir_modebits)
 
 
277
            # After creating the lock directory, try again
 
 
278
            self.transport.mkdir(tmpname)
 
 
279
        self.nonce = rand_chars(20)
 
 
280
        info_bytes = self._prepare_info()
 
 
281
        # We use put_file_non_atomic because we just created a new unique
 
 
282
        # directory so we don't have to worry about files existing there.
 
 
283
        # We'll rename the whole directory into place to get atomic
 
 
285
        self.transport.put_bytes_non_atomic(tmpname + self.__INFO_NAME,
 
 
290
        """Release a held lock
 
 
292
        if self._fake_read_lock:
 
 
293
            self._fake_read_lock = False
 
 
295
        if not self._lock_held:
 
 
296
            raise LockNotHeld(self)
 
 
297
        if self._locked_via_token:
 
 
298
            self._locked_via_token = False
 
 
299
            self._lock_held = False
 
 
301
            # rename before deleting, because we can't atomically remove the
 
 
303
            start_time = time.time()
 
 
304
            self._trace("unlocking")
 
 
305
            tmpname = '%s/releasing.%s.tmp' % (self.path, rand_chars(20))
 
 
306
            # gotta own it to unlock
 
 
308
            self.transport.rename(self._held_dir, tmpname)
 
 
309
            self._lock_held = False
 
 
310
            self.transport.delete(tmpname + self.__INFO_NAME)
 
 
312
                self.transport.rmdir(tmpname)
 
 
313
            except DirectoryNotEmpty, e:
 
 
314
                # There might have been junk left over by a rename that moved
 
 
315
                # another locker within the 'held' directory.  do a slower
 
 
316
                # deletion where we list the directory and remove everything
 
 
319
                # Maybe this should be broader to allow for ftp servers with
 
 
320
                # non-specific error messages?
 
 
321
                self._trace("doing recursive deletion of non-empty directory "
 
 
323
                self.transport.delete_tree(tmpname)
 
 
324
            self._trace("... unlock succeeded after %dms",
 
 
325
                    (time.time() - start_time) * 1000)
 
 
327
    def break_lock(self):
 
 
328
        """Break a lock not held by this instance of LockDir.
 
 
330
        This is a UI centric function: it uses the bzrlib.ui.ui_factory to
 
 
331
        prompt for input if a lock is detected and there is any doubt about
 
 
332
        it possibly being still active.
 
 
334
        self._check_not_locked()
 
 
335
        holder_info = self.peek()
 
 
336
        if holder_info is not None:
 
 
337
            lock_info = '\n'.join(self._format_lock_info(holder_info))
 
 
338
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
 
 
339
                self.force_break(holder_info)
 
 
341
    def force_break(self, dead_holder_info):
 
 
342
        """Release a lock held by another process.
 
 
344
        WARNING: This should only be used when the other process is dead; if
 
 
345
        it still thinks it has the lock there will be two concurrent writers.
 
 
346
        In general the user's approval should be sought for lock breaks.
 
 
348
        dead_holder_info must be the result of a previous LockDir.peek() call;
 
 
349
        this is used to check that it's still held by the same process that
 
 
350
        the user decided was dead.  If this is not the current holder,
 
 
351
        LockBreakMismatch is raised.
 
 
353
        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 
 
 
355
        lock before the breaking process acquires it.
 
 
357
        if not isinstance(dead_holder_info, dict):
 
 
358
            raise ValueError("dead_holder_info: %r" % dead_holder_info)
 
 
359
        self._check_not_locked()
 
 
360
        current_info = self.peek()
 
 
361
        if current_info is None:
 
 
362
            # must have been recently released
 
 
364
        if current_info != dead_holder_info:
 
 
365
            raise LockBreakMismatch(self, current_info, dead_holder_info)
 
 
366
        tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20))
 
 
367
        self.transport.rename(self._held_dir, tmpname)
 
 
368
        # check that we actually broke the right lock, not someone else;
 
 
369
        # there's a small race window between checking it and doing the 
 
 
371
        broken_info_path = tmpname + self.__INFO_NAME
 
 
372
        broken_info = self._read_info_file(broken_info_path)
 
 
373
        if broken_info != dead_holder_info:
 
 
374
            raise LockBreakMismatch(self, broken_info, dead_holder_info)
 
 
375
        self.transport.delete(broken_info_path)
 
 
376
        self.transport.rmdir(tmpname)
 
 
378
    def _check_not_locked(self):
 
 
379
        """If the lock is held by this instance, raise an error."""
 
 
381
            raise AssertionError("can't break own lock: %r" % self)
 
 
384
        """Make sure that the lock is still held by this locker.
 
 
386
        This should only fail if the lock was broken by user intervention,
 
 
387
        or if the lock has been affected by a bug.
 
 
389
        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 
 
 
393
        if not self._lock_held:
 
 
394
            raise LockNotHeld(self)
 
 
397
            # no lock there anymore!
 
 
398
            raise LockBroken(self)
 
 
399
        if info.get('nonce') != self.nonce:
 
 
400
            # there is a lock, but not ours
 
 
401
            raise LockBroken(self)
 
 
403
    def _read_info_file(self, path):
 
 
404
        """Read one given info file.
 
 
406
        peek() reads the info file of the lock holder, if any.
 
 
408
        return self._parse_info(self.transport.get(path))
 
 
411
        """Check if the lock is held by anyone.
 
 
413
        If it is held, this returns the lock info structure as a rio Stanza,
 
 
414
        which contains some information about the current lock holder.
 
 
415
        Otherwise returns None.
 
 
418
            info = self._read_info_file(self._held_info_path)
 
 
419
            self._trace("peek -> held")
 
 
420
            assert isinstance(info, dict), \
 
 
421
                    "bad parse result %r" % info
 
 
423
        except NoSuchFile, e:
 
 
424
            self._trace("peek -> not held")
 
 
426
    def _prepare_info(self):
 
 
427
        """Write information about a pending lock to a temporary file.
 
 
430
        # XXX: is creating this here inefficient?
 
 
431
        config = bzrlib.config.GlobalConfig()
 
 
433
            user = config.user_email()
 
 
434
        except errors.NoEmailInUsername:
 
 
435
            user = config.username()
 
 
436
        s = Stanza(hostname=socket.gethostname(),
 
 
437
                   pid=str(os.getpid()),
 
 
438
                   start_time=str(int(time.time())),
 
 
444
    def _parse_info(self, info_file):
 
 
445
        return read_stanza(info_file.readlines()).as_dict()
 
 
447
    def attempt_lock(self):
 
 
448
        """Take the lock; fail if it's already held.
 
 
450
        If you wish to block until the lock can be obtained, call wait_lock()
 
 
453
        :return: The lock token.
 
 
454
        :raises LockContention: if the lock is held by someone else.
 
 
456
        if self._fake_read_lock:
 
 
457
            raise LockContention(self)
 
 
458
        return self._attempt_lock()
 
 
460
    def wait_lock(self, timeout=None, poll=None, max_attempts=None):
 
 
461
        """Wait a certain period for a lock.
 
 
463
        If the lock can be acquired within the bounded time, it
 
 
464
        is taken and this returns.  Otherwise, LockContention
 
 
465
        is raised.  Either way, this function should return within
 
 
466
        approximately `timeout` seconds.  (It may be a bit more if
 
 
467
        a transport operation takes a long time to complete.)
 
 
469
        :param timeout: Approximate maximum amount of time to wait for the
 
 
472
        :param poll: Delay in seconds between retrying the lock.
 
 
474
        :param max_attempts: Maximum number of times to try to lock.
 
 
476
        :return: The lock token.
 
 
479
            timeout = _DEFAULT_TIMEOUT_SECONDS
 
 
481
            poll = _DEFAULT_POLL_SECONDS
 
 
482
        # XXX: the transport interface doesn't let us guard against operations
 
 
483
        # there taking a long time, so the total elapsed time or poll interval
 
 
484
        # may be more than was requested.
 
 
485
        deadline = time.time() + timeout
 
 
492
                return self.attempt_lock()
 
 
493
            except LockContention:
 
 
494
                # possibly report the blockage, then try again
 
 
496
            # TODO: In a few cases, we find out that there's contention by
 
 
497
            # reading the held info and observing that it's not ours.  In
 
 
498
            # those cases it's a bit redundant to read it again.  However,
 
 
499
            # the normal case (??) is that the rename fails and so we
 
 
500
            # don't know who holds the lock.  For simplicity we peek
 
 
502
            new_info = self.peek()
 
 
503
            if new_info is not None and new_info != last_info:
 
 
504
                if last_info is None:
 
 
505
                    start = 'Unable to obtain'
 
 
507
                    start = 'Lock owner changed for'
 
 
509
                formatted_info = self._format_lock_info(new_info)
 
 
510
                if deadline_str is None:
 
 
511
                    deadline_str = time.strftime('%H:%M:%S',
 
 
512
                                                 time.localtime(deadline))
 
 
513
                self._report_function('%s %s\n'
 
 
515
                                      '%s\n' # locked ... ago
 
 
516
                                      'Will continue to try until %s\n',
 
 
523
            if (max_attempts is not None) and (attempt_count >= max_attempts):
 
 
524
                self._trace("exceeded %d attempts")
 
 
525
                raise LockContention(self)
 
 
526
            if time.time() + poll < deadline:
 
 
527
                self._trace("waiting %ss", poll)
 
 
530
                self._trace("timeout after waiting %ss", timeout)
 
 
531
                raise LockContention(self)
 
 
533
    def leave_in_place(self):
 
 
534
        self._locked_via_token = True
 
 
536
    def dont_leave_in_place(self):
 
 
537
        self._locked_via_token = False
 
 
539
    def lock_write(self, token=None):
 
 
540
        """Wait for and acquire the lock.
 
 
542
        :param token: if this is already locked, then lock_write will fail
 
 
543
            unless the token matches the existing lock.
 
 
544
        :returns: a token if this instance supports tokens, otherwise None.
 
 
545
        :raises TokenLockingNotSupported: when a token is given but this
 
 
546
            instance doesn't support using token locks.
 
 
547
        :raises MismatchedToken: if the specified token doesn't match the token
 
 
548
            of the existing lock.
 
 
550
        A token should be passed in if you know that you have locked the object
 
 
551
        some other way, and need to synchronise this object's state with that
 
 
554
        XXX: docstring duplicated from LockableFiles.lock_write.
 
 
556
        if token is not None:
 
 
557
            self.validate_token(token)
 
 
559
            self._lock_held = True
 
 
560
            self._locked_via_token = True
 
 
563
            return self.wait_lock()
 
 
566
        """Compatibility-mode shared lock.
 
 
568
        LockDir doesn't support shared read-only locks, so this 
 
 
569
        just pretends that the lock is taken but really does nothing.
 
 
571
        # At the moment Branches are commonly locked for read, but 
 
 
572
        # we can't rely on that remotely.  Once this is cleaned up,
 
 
573
        # reenable this warning to prevent it coming back in 
 
 
575
        ## warn("LockDir.lock_read falls back to write lock")
 
 
576
        if self._lock_held or self._fake_read_lock:
 
 
577
            raise LockContention(self)
 
 
578
        self._fake_read_lock = True
 
 
580
    def _format_lock_info(self, info):
 
 
581
        """Turn the contents of peek() into something for the user"""
 
 
582
        lock_url = self.transport.abspath(self.path)
 
 
583
        delta = time.time() - int(info['start_time'])
 
 
585
            'lock %s' % (lock_url,),
 
 
586
            'held by %(user)s on host %(hostname)s [process #%(pid)s]' % info,
 
 
587
            'locked %s' % (format_delta(delta),),
 
 
590
    def validate_token(self, token):
 
 
591
        if token is not None:
 
 
597
                lock_token = info.get('nonce')
 
 
598
            if token != lock_token:
 
 
599
                raise errors.TokenMismatch(token, lock_token)
 
 
601
                self._trace("revalidated by token %r", token)
 
 
603
    def _trace(self, format, *args):
 
 
604
        if 'lock' not in debug.debug_flags:
 
 
606
        mutter(str(self) + ": " + (format % args))