/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: Martin Pool
  • Date: 2009-12-14 06:06:59 UTC
  • mfrom: (4889 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4891.
  • Revision ID: mbp@sourcefrog.net-20091214060659-1ucv8hpnky0cbnaj
merge trunk

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, 2009 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
174
        self.transport = transport
189
193
    def create(self, mode=None):
190
194
        """Create the on-disk lock.
191
195
 
192
 
        This is typically only called when the object/directory containing the 
 
196
        This is typically only called when the object/directory containing the
193
197
        directory is first created.  The lock is not held when it's created.
194
198
        """
195
199
        self._trace("create lock directory")
201
205
 
202
206
    def _attempt_lock(self):
203
207
        """Make the pending directory and attempt to rename into place.
204
 
        
 
208
 
205
209
        If the rename succeeds, we read back the info file to check that we
206
210
        really got the lock.
207
211
 
252
256
    def _remove_pending_dir(self, tmpname):
253
257
        """Remove the pending directory
254
258
 
255
 
        This is called if we failed to rename into place, so that the pending 
 
259
        This is called if we failed to rename into place, so that the pending
256
260
        dirs don't clutter up the lockdir.
257
261
        """
258
262
        self._trace("remove %s", tmpname)
284
288
                                            info_bytes)
285
289
        return tmpname
286
290
 
 
291
    @only_raises(LockNotHeld, LockBroken)
287
292
    def unlock(self):
288
293
        """Release a held lock
289
294
        """
291
296
            self._fake_read_lock = False
292
297
            return
293
298
        if not self._lock_held:
294
 
            raise LockNotHeld(self)
 
299
            return lock.cant_unlock_not_held(self)
295
300
        if self._locked_via_token:
296
301
            self._locked_via_token = False
297
302
            self._lock_held = False
298
303
        else:
 
304
            old_nonce = self.nonce
299
305
            # rename before deleting, because we can't atomically remove the
300
306
            # whole tree
301
307
            start_time = time.time()
321
327
                self.transport.delete_tree(tmpname)
322
328
            self._trace("... unlock succeeded after %dms",
323
329
                    (time.time() - start_time) * 1000)
 
330
            result = lock.LockResult(self.transport.abspath(self.path),
 
331
                                     old_nonce)
 
332
            for hook in self.hooks['lock_released']:
 
333
                hook(result)
324
334
 
325
335
    def break_lock(self):
326
336
        """Break a lock not held by this instance of LockDir.
335
345
            lock_info = '\n'.join(self._format_lock_info(holder_info))
336
346
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
337
347
                self.force_break(holder_info)
338
 
        
 
348
 
339
349
    def force_break(self, dead_holder_info):
340
350
        """Release a lock held by another process.
341
351
 
349
359
        LockBreakMismatch is raised.
350
360
 
351
361
        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 
 
362
        It is possible that another process may sneak in and take the
353
363
        lock before the breaking process acquires it.
354
364
        """
355
365
        if not isinstance(dead_holder_info, dict):
364
374
        tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20))
365
375
        self.transport.rename(self._held_dir, tmpname)
366
376
        # check that we actually broke the right lock, not someone else;
367
 
        # there's a small race window between checking it and doing the 
 
377
        # there's a small race window between checking it and doing the
368
378
        # rename.
369
379
        broken_info_path = tmpname + self.__INFO_NAME
370
380
        broken_info = self._read_info_file(broken_info_path)
372
382
            raise LockBreakMismatch(self, broken_info, dead_holder_info)
373
383
        self.transport.delete(broken_info_path)
374
384
        self.transport.rmdir(tmpname)
 
385
        result = lock.LockResult(self.transport.abspath(self.path),
 
386
                                 current_info.get('nonce'))
 
387
        for hook in self.hooks['lock_broken']:
 
388
            hook(result)
375
389
 
376
390
    def _check_not_locked(self):
377
391
        """If the lock is held by this instance, raise an error."""
385
399
        or if the lock has been affected by a bug.
386
400
 
387
401
        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 
 
402
        the lock is thought to be held but has been broken, raises
389
403
        LockBroken.
390
404
        """
391
405
        if not self._lock_held:
397
411
        if info.get('nonce') != self.nonce:
398
412
            # there is a lock, but not ours
399
413
            raise LockBroken(self)
400
 
        
 
414
 
401
415
    def _read_info_file(self, path):
402
416
        """Read one given info file.
403
417
 
404
418
        peek() reads the info file of the lock holder, if any.
405
419
        """
406
 
        return self._parse_info(self.transport.get(path))
 
420
        return self._parse_info(self.transport.get_bytes(path))
407
421
 
408
422
    def peek(self):
409
423
        """Check if the lock is held by anyone.
410
 
        
 
424
 
411
425
        If it is held, this returns the lock info structure as a rio Stanza,
412
426
        which contains some information about the current lock holder.
413
427
        Otherwise returns None.
422
436
    def _prepare_info(self):
423
437
        """Write information about a pending lock to a temporary file.
424
438
        """
425
 
        import socket
426
439
        # XXX: is creating this here inefficient?
427
440
        config = bzrlib.config.GlobalConfig()
428
441
        try:
429
442
            user = config.user_email()
430
443
        except errors.NoEmailInUsername:
431
444
            user = config.username()
432
 
        s = Stanza(hostname=socket.gethostname(),
 
445
        s = rio.Stanza(hostname=get_host_name(),
433
446
                   pid=str(os.getpid()),
434
447
                   start_time=str(int(time.time())),
435
448
                   nonce=self.nonce,
437
450
                   )
438
451
        return s.to_string()
439
452
 
440
 
    def _parse_info(self, info_file):
441
 
        return read_stanza(info_file.readlines()).as_dict()
 
453
    def _parse_info(self, info_bytes):
 
454
        # TODO: Handle if info_bytes is empty
 
455
        return rio.read_stanza(osutils.split_lines(info_bytes)).as_dict()
442
456
 
443
457
    def attempt_lock(self):
444
458
        """Take the lock; fail if it's already held.
445
 
        
 
459
 
446
460
        If you wish to block until the lock can be obtained, call wait_lock()
447
461
        instead.
448
462
 
451
465
        """
452
466
        if self._fake_read_lock:
453
467
            raise LockContention(self)
454
 
        return self._attempt_lock()
 
468
        result = self._attempt_lock()
 
469
        hook_result = lock.LockResult(self.transport.abspath(self.path),
 
470
                self.nonce)
 
471
        for hook in self.hooks['lock_acquired']:
 
472
            hook(hook_result)
 
473
        return result
455
474
 
456
475
    def wait_lock(self, timeout=None, poll=None, max_attempts=None):
457
476
        """Wait a certain period for a lock.
464
483
 
465
484
        :param timeout: Approximate maximum amount of time to wait for the
466
485
        lock, in seconds.
467
 
         
 
486
 
468
487
        :param poll: Delay in seconds between retrying the lock.
469
488
 
470
489
        :param max_attempts: Maximum number of times to try to lock.
506
525
                if deadline_str is None:
507
526
                    deadline_str = time.strftime('%H:%M:%S',
508
527
                                                 time.localtime(deadline))
 
528
                lock_url = self.transport.abspath(self.path)
509
529
                self._report_function('%s %s\n'
510
530
                                      '%s\n' # held by
511
531
                                      '%s\n' # locked ... ago
512
 
                                      'Will continue to try until %s\n',
 
532
                                      'Will continue to try until %s, unless '
 
533
                                      'you press Ctrl-C\n'
 
534
                                      'If you\'re sure that it\'s not being '
 
535
                                      'modified, use bzr break-lock %s',
513
536
                                      start,
514
537
                                      formatted_info[0],
515
538
                                      formatted_info[1],
516
539
                                      formatted_info[2],
517
 
                                      deadline_str)
 
540
                                      deadline_str,
 
541
                                      lock_url)
518
542
 
519
543
            if (max_attempts is not None) and (attempt_count >= max_attempts):
520
544
                self._trace("exceeded %d attempts")
525
549
            else:
526
550
                self._trace("timeout after waiting %ss", timeout)
527
551
                raise LockContention(self)
528
 
    
 
552
 
529
553
    def leave_in_place(self):
530
554
        self._locked_via_token = True
531
555
 
534
558
 
535
559
    def lock_write(self, token=None):
536
560
        """Wait for and acquire the lock.
537
 
        
 
561
 
538
562
        :param token: if this is already locked, then lock_write will fail
539
563
            unless the token matches the existing lock.
540
564
        :returns: a token if this instance supports tokens, otherwise None.
546
570
        A token should be passed in if you know that you have locked the object
547
571
        some other way, and need to synchronise this object's state with that
548
572
        fact.
549
 
         
 
573
 
550
574
        XXX: docstring duplicated from LockableFiles.lock_write.
551
575
        """
552
576
        if token is not None:
561
585
    def lock_read(self):
562
586
        """Compatibility-mode shared lock.
563
587
 
564
 
        LockDir doesn't support shared read-only locks, so this 
 
588
        LockDir doesn't support shared read-only locks, so this
565
589
        just pretends that the lock is taken but really does nothing.
566
590
        """
567
 
        # At the moment Branches are commonly locked for read, but 
 
591
        # At the moment Branches are commonly locked for read, but
568
592
        # we can't rely on that remotely.  Once this is cleaned up,
569
 
        # reenable this warning to prevent it coming back in 
 
593
        # reenable this warning to prevent it coming back in
570
594
        # -- mbp 20060303
571
595
        ## warn("LockDir.lock_read falls back to write lock")
572
596
        if self._lock_held or self._fake_read_lock: