~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_lockdir.py

  • Committer: Patch Queue Manager
  • Date: 2011-09-22 14:12:18 UTC
  • mfrom: (6155.3.1 jam)
  • Revision ID: pqm@pqm.ubuntu.com-20110922141218-86s4uu6nqvourw4f
(jameinel) Cleanup comments bzrlib/smart/__init__.py (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006 Canonical Ltd
2
 
 
 
1
# Copyright (C) 2006-2011 Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
 
 
7
#
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
"""Tests for LockDir"""
18
18
 
19
 
from cStringIO import StringIO
20
 
from threading import Thread
 
19
import os
21
20
import time
22
21
 
23
22
import bzrlib
 
23
from bzrlib import (
 
24
    config,
 
25
    errors,
 
26
    lock,
 
27
    lockdir,
 
28
    osutils,
 
29
    tests,
 
30
    transport,
 
31
    )
24
32
from bzrlib.errors import (
25
 
        LockBreakMismatch,
26
 
        LockContention, LockError, UnlockableTransport,
27
 
        LockNotHeld, LockBroken
28
 
        )
29
 
from bzrlib.lockdir import LockDir
30
 
from bzrlib.tests import TestCaseWithTransport
31
 
 
32
 
# These tests sometimes use threads to test the behaviour of lock files with
33
 
# concurrent actors.  This is not a typical (or necessarily supported) use;
34
 
# they're really meant for guarding between processes.
 
33
    LockBreakMismatch,
 
34
    LockBroken,
 
35
    LockContention,
 
36
    LockFailed,
 
37
    LockNotHeld,
 
38
    )
 
39
from bzrlib.lockdir import (
 
40
    LockDir,
 
41
    LockHeldInfo,
 
42
    )
 
43
from bzrlib.tests import (
 
44
    features,
 
45
    TestCase,
 
46
    TestCaseWithTransport,
 
47
    )
35
48
 
36
49
# These tests are run on the default transport provided by the test framework
37
50
# (typically a local disk transport).  That can be changed by the --transport
39
52
# implementation are tested separately.  (The main requirement is just that
40
53
# they don't allow overwriting nonempty directories.)
41
54
 
 
55
 
42
56
class TestLockDir(TestCaseWithTransport):
43
57
    """Test LockDir operations"""
44
58
 
 
59
    def logging_report_function(self, fmt, *args):
 
60
        self._logged_reports.append((fmt, args))
 
61
 
 
62
    def setup_log_reporter(self, lock_dir):
 
63
        self._logged_reports = []
 
64
        lock_dir._report_function = self.logging_report_function
 
65
 
45
66
    def test_00_lock_creation(self):
46
67
        """Creation of lock file on a transport"""
47
68
        t = self.get_transport()
89
110
        """Fail to create lock on readonly transport"""
90
111
        t = self.get_readonly_transport()
91
112
        lf = LockDir(t, 'test_lock')
92
 
        self.assertRaises(UnlockableTransport, lf.create)
 
113
        self.assertRaises(LockFailed, lf.create)
93
114
 
94
115
    def test_12_lock_readonly_transport(self):
95
116
        """Fail to lock on readonly transport"""
96
117
        lf = LockDir(self.get_transport(), 'test_lock')
97
118
        lf.create()
98
119
        lf = LockDir(self.get_readonly_transport(), 'test_lock')
99
 
        self.assertRaises(UnlockableTransport, lf.attempt_lock)
 
120
        self.assertRaises(LockFailed, lf.attempt_lock)
100
121
 
101
122
    def test_20_lock_contested(self):
102
123
        """Contention to get a lock"""
106
127
        lf1.attempt_lock()
107
128
        lf2 = LockDir(t, 'test_lock')
108
129
        try:
109
 
            # locking is between LockDir instances; aliases within 
 
130
            # locking is between LockDir instances; aliases within
110
131
            # a single process are not detected
111
132
            lf2.attempt_lock()
112
133
            self.fail('Failed to detect lock collision')
122
143
        lf1 = LockDir(t, 'test_lock')
123
144
        lf1.create()
124
145
        lf1.attempt_lock()
 
146
        self.addCleanup(lf1.unlock)
125
147
        # lock is held, should get some info on it
126
148
        info1 = lf1.peek()
127
 
        self.assertEqual(set(info1.keys()),
128
 
                         set(['user', 'nonce', 'hostname', 'pid', 'start_time']))
 
149
        self.assertEqual(set(info1.info_dict.keys()),
 
150
            set(['user', 'nonce', 'hostname', 'pid', 'start_time']))
129
151
        # should get the same info if we look at it through a different
130
152
        # instance
131
153
        info2 = LockDir(t, 'test_lock').peek()
141
163
        lf2 = LockDir(self.get_readonly_transport(), 'test_lock')
142
164
        self.assertEqual(lf2.peek(), None)
143
165
        lf1.attempt_lock()
 
166
        self.addCleanup(lf1.unlock)
144
167
        info2 = lf2.peek()
145
168
        self.assertTrue(info2)
146
 
        self.assertEqual(info2['nonce'], lf1.nonce)
 
169
        self.assertEqual(info2.get('nonce'), lf1.nonce)
147
170
 
148
171
    def test_30_lock_wait_fail(self):
149
172
        """Wait on a lock, then fail
150
 
        
 
173
 
151
174
        We ask to wait up to 400ms; this should fail within at most one
152
175
        second.  (Longer times are more realistic but we don't want the test
153
176
        suite to take too long, and this should do for now.)
156
179
        lf1 = LockDir(t, 'test_lock')
157
180
        lf1.create()
158
181
        lf2 = LockDir(t, 'test_lock')
 
182
        self.setup_log_reporter(lf2)
159
183
        lf1.attempt_lock()
160
184
        try:
161
185
            before = time.time()
164
188
            after = time.time()
165
189
            # it should only take about 0.4 seconds, but we allow more time in
166
190
            # case the machine is heavily loaded
167
 
            self.assertTrue(after - before <= 8.0, 
168
 
                    "took %f seconds to detect lock contention" % (after - before))
 
191
            self.assertTrue(after - before <= 8.0,
 
192
                "took %f seconds to detect lock contention" % (after - before))
169
193
        finally:
170
194
            lf1.unlock()
 
195
        self.assertEqual(1, len(self._logged_reports))
 
196
        self.assertContainsRe(self._logged_reports[0][0],
 
197
            r'Unable to obtain lock .* held by jrandom@example\.com on .*'
 
198
            r' \(process #\d+\), acquired .* ago\.\n'
 
199
            r'Will continue to try until \d{2}:\d{2}:\d{2}, unless '
 
200
            r'you press Ctrl-C.\n'
 
201
            r'See "bzr help break-lock" for more.')
171
202
 
172
203
    def test_31_lock_wait_easy(self):
173
204
        """Succeed when waiting on a lock with no contention.
175
206
        t = self.get_transport()
176
207
        lf1 = LockDir(t, 'test_lock')
177
208
        lf1.create()
 
209
        self.setup_log_reporter(lf1)
178
210
        try:
179
211
            before = time.time()
180
212
            lf1.wait_lock(timeout=0.4, poll=0.1)
182
214
            self.assertTrue(after - before <= 1.0)
183
215
        finally:
184
216
            lf1.unlock()
185
 
 
186
 
    def test_32_lock_wait_succeed(self):
187
 
        """Succeed when trying to acquire a lock that gets released
188
 
 
189
 
        One thread holds on a lock and then releases it; another 
190
 
        tries to lock it.
191
 
        """
192
 
        t = self.get_transport()
193
 
        lf1 = LockDir(t, 'test_lock')
194
 
        lf1.create()
195
 
        lf1.attempt_lock()
196
 
 
197
 
        def wait_and_unlock():
198
 
            time.sleep(0.1)
199
 
            lf1.unlock()
200
 
        unlocker = Thread(target=wait_and_unlock)
201
 
        unlocker.start()
202
 
        try:
203
 
            lf2 = LockDir(t, 'test_lock')
204
 
            before = time.time()
205
 
            # wait and then lock
206
 
            lf2.wait_lock(timeout=0.4, poll=0.1)
207
 
            after = time.time()
208
 
            self.assertTrue(after - before <= 1.0)
209
 
        finally:
210
 
            unlocker.join()
211
 
 
212
 
    def test_33_wait(self):
213
 
        """Succeed when waiting on a lock that gets released
214
 
 
215
 
        The difference from test_32_lock_wait_succeed is that the second 
216
 
        caller does not actually acquire the lock, but just waits for it
217
 
        to be released.  This is done over a readonly transport.
218
 
        """
219
 
        t = self.get_transport()
220
 
        lf1 = LockDir(t, 'test_lock')
221
 
        lf1.create()
222
 
        lf1.attempt_lock()
223
 
 
224
 
        def wait_and_unlock():
225
 
            time.sleep(0.1)
226
 
            lf1.unlock()
227
 
        unlocker = Thread(target=wait_and_unlock)
228
 
        unlocker.start()
229
 
        try:
230
 
            lf2 = LockDir(self.get_readonly_transport(), 'test_lock')
231
 
            before = time.time()
232
 
            # wait but don't lock
233
 
            lf2.wait(timeout=0.4, poll=0.1)
234
 
            after = time.time()
235
 
            self.assertTrue(after - before <= 1.0)
236
 
        finally:
237
 
            unlocker.join()
 
217
        self.assertEqual([], self._logged_reports)
238
218
 
239
219
    def test_40_confirm_easy(self):
240
220
        """Confirm a lock that's already held"""
242
222
        lf1 = LockDir(t, 'test_lock')
243
223
        lf1.create()
244
224
        lf1.attempt_lock()
 
225
        self.addCleanup(lf1.unlock)
245
226
        lf1.confirm()
246
227
 
247
228
    def test_41_confirm_not_held(self):
259
240
        lf1.attempt_lock()
260
241
        t.move('test_lock', 'lock_gone_now')
261
242
        self.assertRaises(LockBroken, lf1.confirm)
 
243
        # Clean up
 
244
        t.move('lock_gone_now', 'test_lock')
 
245
        lf1.unlock()
262
246
 
263
247
    def test_43_break(self):
264
248
        """Break a lock whose caller has forgotten it"""
275
259
        lf2.force_break(holder_info)
276
260
        # now we should be able to take it
277
261
        lf2.attempt_lock()
 
262
        self.addCleanup(lf2.unlock)
278
263
        lf2.confirm()
279
264
 
280
265
    def test_44_break_already_released(self):
292
277
        lf2.force_break(holder_info)
293
278
        # now we should be able to take it
294
279
        lf2.attempt_lock()
 
280
        self.addCleanup(lf2.unlock)
295
281
        lf2.confirm()
296
282
 
297
283
    def test_45_break_mismatch(self):
323
309
        """Check the on-disk representation of LockDirs is as expected.
324
310
 
325
311
        There should always be a top-level directory named by the lock.
326
 
        When the lock is held, there should be a lockname/held directory 
 
312
        When the lock is held, there should be a lockname/held directory
327
313
        containing an info file.
328
314
        """
329
315
        t = self.get_transport()
344
330
        # do this without IO redirection to ensure it doesn't prompt.
345
331
        self.assertRaises(AssertionError, ld1.break_lock)
346
332
        orig_factory = bzrlib.ui.ui_factory
347
 
        # silent ui - no need for stdout
348
 
        bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
349
 
        bzrlib.ui.ui_factory.stdin = StringIO("y\n")
 
333
        bzrlib.ui.ui_factory = bzrlib.ui.CannedInputUIFactory([True])
350
334
        try:
351
335
            ld2.break_lock()
352
336
            self.assertRaises(LockBroken, ld1.unlock)
353
337
        finally:
354
338
            bzrlib.ui.ui_factory = orig_factory
 
339
 
 
340
    def test_break_lock_corrupt_info(self):
 
341
        """break_lock works even if the info file is corrupt (and tells the UI
 
342
        that it is corrupt).
 
343
        """
 
344
        ld = self.get_lock()
 
345
        ld2 = self.get_lock()
 
346
        ld.create()
 
347
        ld.lock_write()
 
348
        ld.transport.put_bytes_non_atomic('test_lock/held/info', '\0')
 
349
 
 
350
        class LoggingUIFactory(bzrlib.ui.SilentUIFactory):
 
351
            def __init__(self):
 
352
                self.prompts = []
 
353
 
 
354
            def get_boolean(self, prompt):
 
355
                self.prompts.append(('boolean', prompt))
 
356
                return True
 
357
 
 
358
        ui = LoggingUIFactory()
 
359
        self.overrideAttr(bzrlib.ui, 'ui_factory', ui)
 
360
        ld2.break_lock()
 
361
        self.assertLength(1, ui.prompts)
 
362
        self.assertEqual('boolean', ui.prompts[0][0])
 
363
        self.assertStartsWith(ui.prompts[0][1], 'Break (corrupt LockDir')
 
364
        self.assertRaises(LockBroken, ld.unlock)
 
365
 
 
366
    def test_break_lock_missing_info(self):
 
367
        """break_lock works even if the info file is missing (and tells the UI
 
368
        that it is corrupt).
 
369
        """
 
370
        ld = self.get_lock()
 
371
        ld2 = self.get_lock()
 
372
        ld.create()
 
373
        ld.lock_write()
 
374
        ld.transport.delete('test_lock/held/info')
 
375
 
 
376
        class LoggingUIFactory(bzrlib.ui.SilentUIFactory):
 
377
            def __init__(self):
 
378
                self.prompts = []
 
379
 
 
380
            def get_boolean(self, prompt):
 
381
                self.prompts.append(('boolean', prompt))
 
382
                return True
 
383
 
 
384
        ui = LoggingUIFactory()
 
385
        orig_factory = bzrlib.ui.ui_factory
 
386
        bzrlib.ui.ui_factory = ui
 
387
        try:
 
388
            ld2.break_lock()
 
389
            self.assertRaises(LockBroken, ld.unlock)
 
390
            self.assertLength(0, ui.prompts)
 
391
        finally:
 
392
            bzrlib.ui.ui_factory = orig_factory
 
393
        # Suppress warnings due to ld not being unlocked
 
394
        # XXX: if lock_broken hook was invoked in this case, this hack would
 
395
        # not be necessary.  - Andrew Bennetts, 2010-09-06.
 
396
        del self._lock_actions[:]
 
397
 
 
398
    def test_create_missing_base_directory(self):
 
399
        """If LockDir.path doesn't exist, it can be created
 
400
 
 
401
        Some people manually remove the entire lock/ directory trying
 
402
        to unlock a stuck repository/branch/etc. Rather than failing
 
403
        after that, just create the lock directory when needed.
 
404
        """
 
405
        t = self.get_transport()
 
406
        lf1 = LockDir(t, 'test_lock')
 
407
 
 
408
        lf1.create()
 
409
        self.assertTrue(t.has('test_lock'))
 
410
 
 
411
        t.rmdir('test_lock')
 
412
        self.assertFalse(t.has('test_lock'))
 
413
 
 
414
        # This will create 'test_lock' if it needs to
 
415
        lf1.lock_write()
 
416
        self.assertTrue(t.has('test_lock'))
 
417
        self.assertTrue(t.has('test_lock/held/info'))
 
418
 
 
419
        lf1.unlock()
 
420
        self.assertFalse(t.has('test_lock/held/info'))
 
421
 
 
422
    def test_display_form(self):
 
423
        ld1 = self.get_lock()
 
424
        ld1.create()
 
425
        ld1.lock_write()
 
426
        try:
 
427
            info_list = ld1.peek().to_readable_dict()
 
428
        finally:
 
429
            ld1.unlock()
 
430
        self.assertEqual(info_list['user'], u'jrandom@example.com')
 
431
        self.assertContainsRe(info_list['pid'], '^\d+$')
 
432
        self.assertContainsRe(info_list['time_ago'], r'^\d+ seconds? ago$')
 
433
 
 
434
    def test_lock_without_email(self):
 
435
        global_config = config.GlobalConfig()
 
436
        # Intentionally has no email address
 
437
        global_config.set_user_option('email', 'User Identity')
 
438
        ld1 = self.get_lock()
 
439
        ld1.create()
 
440
        ld1.lock_write()
 
441
        ld1.unlock()
 
442
 
 
443
    def test_lock_permission(self):
 
444
        self.requireFeature(features.not_running_as_root)
 
445
        if not osutils.supports_posix_readonly():
 
446
            raise tests.TestSkipped('Cannot induce a permission failure')
 
447
        ld1 = self.get_lock()
 
448
        lock_path = ld1.transport.local_abspath('test_lock')
 
449
        os.mkdir(lock_path)
 
450
        osutils.make_readonly(lock_path)
 
451
        self.assertRaises(errors.LockFailed, ld1.attempt_lock)
 
452
 
 
453
    def test_lock_by_token(self):
 
454
        ld1 = self.get_lock()
 
455
        token = ld1.lock_write()
 
456
        self.addCleanup(ld1.unlock)
 
457
        self.assertNotEqual(None, token)
 
458
        ld2 = self.get_lock()
 
459
        t2 = ld2.lock_write(token)
 
460
        self.addCleanup(ld2.unlock)
 
461
        self.assertEqual(token, t2)
 
462
 
 
463
    def test_lock_with_buggy_rename(self):
 
464
        # test that lock acquisition handles servers which pretend they
 
465
        # renamed correctly but that actually fail
 
466
        t = transport.get_transport_from_url(
 
467
            'brokenrename+' + self.get_url())
 
468
        ld1 = LockDir(t, 'test_lock')
 
469
        ld1.create()
 
470
        ld1.attempt_lock()
 
471
        ld2 = LockDir(t, 'test_lock')
 
472
        # we should fail to lock
 
473
        e = self.assertRaises(errors.LockContention, ld2.attempt_lock)
 
474
        # now the original caller should succeed in unlocking
 
475
        ld1.unlock()
 
476
        # and there should be nothing left over
 
477
        self.assertEquals([], t.list_dir('test_lock'))
 
478
 
 
479
    def test_failed_lock_leaves_no_trash(self):
 
480
        # if we fail to acquire the lock, we don't leave pending directories
 
481
        # behind -- https://bugs.launchpad.net/bzr/+bug/109169
 
482
        ld1 = self.get_lock()
 
483
        ld2 = self.get_lock()
 
484
        # should be nothing before we start
 
485
        ld1.create()
 
486
        t = self.get_transport().clone('test_lock')
 
487
 
 
488
        def check_dir(a):
 
489
            self.assertEquals(a, t.list_dir('.'))
 
490
 
 
491
        check_dir([])
 
492
        # when held, that's all we see
 
493
        ld1.attempt_lock()
 
494
        self.addCleanup(ld1.unlock)
 
495
        check_dir(['held'])
 
496
        # second guy should fail
 
497
        self.assertRaises(errors.LockContention, ld2.attempt_lock)
 
498
        # no kibble
 
499
        check_dir(['held'])
 
500
 
 
501
    def test_no_lockdir_info(self):
 
502
        """We can cope with empty info files."""
 
503
        # This seems like a fairly common failure case - see
 
504
        # <https://bugs.launchpad.net/bzr/+bug/185103> and all its dupes.
 
505
        # Processes are often interrupted after opening the file
 
506
        # before the actual contents are committed.
 
507
        t = self.get_transport()
 
508
        t.mkdir('test_lock')
 
509
        t.mkdir('test_lock/held')
 
510
        t.put_bytes('test_lock/held/info', '')
 
511
        lf = LockDir(t, 'test_lock')
 
512
        info = lf.peek()
 
513
        formatted_info = info.to_readable_dict()
 
514
        self.assertEquals(
 
515
            dict(user='<unknown>', hostname='<unknown>', pid='<unknown>',
 
516
                time_ago='(unknown)'),
 
517
            formatted_info)
 
518
 
 
519
    def test_corrupt_lockdir_info(self):
 
520
        """We can cope with corrupt (and thus unparseable) info files."""
 
521
        # This seems like a fairly common failure case too - see
 
522
        # <https://bugs.launchpad.net/bzr/+bug/619872> for instance.
 
523
        # In particular some systems tend to fill recently created files with
 
524
        # nul bytes after recovering from a system crash.
 
525
        t = self.get_transport()
 
526
        t.mkdir('test_lock')
 
527
        t.mkdir('test_lock/held')
 
528
        t.put_bytes('test_lock/held/info', '\0')
 
529
        lf = LockDir(t, 'test_lock')
 
530
        self.assertRaises(errors.LockCorrupt, lf.peek)
 
531
        # Currently attempt_lock gives LockContention, but LockCorrupt would be
 
532
        # a reasonable result too.
 
533
        self.assertRaises(
 
534
            (errors.LockCorrupt, errors.LockContention), lf.attempt_lock)
 
535
        self.assertRaises(errors.LockCorrupt, lf.validate_token, 'fake token')
 
536
 
 
537
    def test_missing_lockdir_info(self):
 
538
        """We can cope with absent info files."""
 
539
        t = self.get_transport()
 
540
        t.mkdir('test_lock')
 
541
        t.mkdir('test_lock/held')
 
542
        lf = LockDir(t, 'test_lock')
 
543
        # In this case we expect the 'not held' result from peek, because peek
 
544
        # cannot be expected to notice that there is a 'held' directory with no
 
545
        # 'info' file.
 
546
        self.assertEqual(None, lf.peek())
 
547
        # And lock/unlock may work or give LockContention (but not any other
 
548
        # error).
 
549
        try:
 
550
            lf.attempt_lock()
 
551
        except LockContention:
 
552
            # LockContention is ok, and expected on Windows
 
553
            pass
 
554
        else:
 
555
            # no error is ok, and expected on POSIX (because POSIX allows
 
556
            # os.rename over an empty directory).
 
557
            lf.unlock()
 
558
        # Currently raises TokenMismatch, but LockCorrupt would be reasonable
 
559
        # too.
 
560
        self.assertRaises(
 
561
            (errors.TokenMismatch, errors.LockCorrupt),
 
562
            lf.validate_token, 'fake token')
 
563
 
 
564
 
 
565
class TestLockDirHooks(TestCaseWithTransport):
 
566
 
 
567
    def setUp(self):
 
568
        super(TestLockDirHooks, self).setUp()
 
569
        self._calls = []
 
570
 
 
571
    def get_lock(self):
 
572
        return LockDir(self.get_transport(), 'test_lock')
 
573
 
 
574
    def record_hook(self, result):
 
575
        self._calls.append(result)
 
576
 
 
577
    def test_LockDir_acquired_success(self):
 
578
        # the LockDir.lock_acquired hook fires when a lock is acquired.
 
579
        LockDir.hooks.install_named_hook('lock_acquired',
 
580
                                         self.record_hook, 'record_hook')
 
581
        ld = self.get_lock()
 
582
        ld.create()
 
583
        self.assertEqual([], self._calls)
 
584
        result = ld.attempt_lock()
 
585
        lock_path = ld.transport.abspath(ld.path)
 
586
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
 
587
        ld.unlock()
 
588
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
 
589
 
 
590
    def test_LockDir_acquired_fail(self):
 
591
        # the LockDir.lock_acquired hook does not fire on failure.
 
592
        ld = self.get_lock()
 
593
        ld.create()
 
594
        ld2 = self.get_lock()
 
595
        ld2.attempt_lock()
 
596
        # install a lock hook now, when the disk lock is locked
 
597
        LockDir.hooks.install_named_hook('lock_acquired',
 
598
                                         self.record_hook, 'record_hook')
 
599
        self.assertRaises(errors.LockContention, ld.attempt_lock)
 
600
        self.assertEqual([], self._calls)
 
601
        ld2.unlock()
 
602
        self.assertEqual([], self._calls)
 
603
 
 
604
    def test_LockDir_released_success(self):
 
605
        # the LockDir.lock_released hook fires when a lock is acquired.
 
606
        LockDir.hooks.install_named_hook('lock_released',
 
607
                                         self.record_hook, 'record_hook')
 
608
        ld = self.get_lock()
 
609
        ld.create()
 
610
        self.assertEqual([], self._calls)
 
611
        result = ld.attempt_lock()
 
612
        self.assertEqual([], self._calls)
 
613
        ld.unlock()
 
614
        lock_path = ld.transport.abspath(ld.path)
 
615
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
 
616
 
 
617
    def test_LockDir_released_fail(self):
 
618
        # the LockDir.lock_released hook does not fire on failure.
 
619
        ld = self.get_lock()
 
620
        ld.create()
 
621
        ld2 = self.get_lock()
 
622
        ld.attempt_lock()
 
623
        ld2.force_break(ld2.peek())
 
624
        LockDir.hooks.install_named_hook('lock_released',
 
625
                                         self.record_hook, 'record_hook')
 
626
        self.assertRaises(LockBroken, ld.unlock)
 
627
        self.assertEqual([], self._calls)
 
628
 
 
629
    def test_LockDir_broken_success(self):
 
630
        # the LockDir.lock_broken hook fires when a lock is broken.
 
631
        ld = self.get_lock()
 
632
        ld.create()
 
633
        ld2 = self.get_lock()
 
634
        result = ld.attempt_lock()
 
635
        LockDir.hooks.install_named_hook('lock_broken',
 
636
                                         self.record_hook, 'record_hook')
 
637
        ld2.force_break(ld2.peek())
 
638
        lock_path = ld.transport.abspath(ld.path)
 
639
        self.assertEqual([lock.LockResult(lock_path, result)], self._calls)
 
640
 
 
641
    def test_LockDir_broken_failure(self):
 
642
        # the LockDir.lock_broken hook does not fires when a lock is already
 
643
        # released.
 
644
        ld = self.get_lock()
 
645
        ld.create()
 
646
        ld2 = self.get_lock()
 
647
        result = ld.attempt_lock()
 
648
        holder_info = ld2.peek()
 
649
        ld.unlock()
 
650
        LockDir.hooks.install_named_hook('lock_broken',
 
651
                                         self.record_hook, 'record_hook')
 
652
        ld2.force_break(holder_info)
 
653
        lock_path = ld.transport.abspath(ld.path)
 
654
        self.assertEqual([], self._calls)
 
655
 
 
656
 
 
657
class TestLockHeldInfo(TestCase):
 
658
    """Can get information about the lock holder, and detect whether they're
 
659
    still alive."""
 
660
 
 
661
    def test_repr(self):
 
662
        info = LockHeldInfo.for_this_process(None)
 
663
        self.assertContainsRe(repr(info), r"LockHeldInfo\(.*\)")
 
664
 
 
665
    def test_unicode(self):
 
666
        info = LockHeldInfo.for_this_process(None)
 
667
        self.assertContainsRe(unicode(info),
 
668
            r'held by .* on .* \(process #\d+\), acquired .* ago')
 
669
 
 
670
    def test_is_locked_by_this_process(self):
 
671
        info = LockHeldInfo.for_this_process(None)
 
672
        self.assertTrue(info.is_locked_by_this_process())
 
673
 
 
674
    def test_is_not_locked_by_this_process(self):
 
675
        info = LockHeldInfo.for_this_process(None)
 
676
        info.info_dict['pid'] = '123123123123123'
 
677
        self.assertFalse(info.is_locked_by_this_process())
 
678
 
 
679
    def test_lock_holder_live_process(self):
 
680
        """Detect that the holder (this process) is still running."""
 
681
        info = LockHeldInfo.for_this_process(None)
 
682
        self.assertFalse(info.is_lock_holder_known_dead())
 
683
 
 
684
    def test_lock_holder_dead_process(self):
 
685
        """Detect that the holder (this process) is still running."""
 
686
        self.overrideAttr(lockdir, 'get_host_name',
 
687
            lambda: 'aproperhostname')
 
688
        info = LockHeldInfo.for_this_process(None)
 
689
        info.info_dict['pid'] = '123123123'
 
690
        self.assertTrue(info.is_lock_holder_known_dead())
 
691
 
 
692
    def test_lock_holder_other_machine(self):
 
693
        """The lock holder isn't here so we don't know if they're alive."""
 
694
        info = LockHeldInfo.for_this_process(None)
 
695
        info.info_dict['hostname'] = 'egg.example.com'
 
696
        info.info_dict['pid'] = '123123123'
 
697
        self.assertFalse(info.is_lock_holder_known_dead())
 
698
 
 
699
    def test_lock_holder_other_user(self):
 
700
        """Only auto-break locks held by this user."""
 
701
        info = LockHeldInfo.for_this_process(None)
 
702
        info.info_dict['user'] = 'notme@example.com'
 
703
        info.info_dict['pid'] = '123123123'
 
704
        self.assertFalse(info.is_lock_holder_known_dead())
 
705
 
 
706
    def test_no_good_hostname(self):
 
707
        """Correctly handle ambiguous hostnames.
 
708
 
 
709
        If the lock's recorded with just 'localhost' we can't really trust
 
710
        it's the same 'localhost'.  (There are quite a few of them. :-)
 
711
        So even if the process is known not to be alive, we can't say that's
 
712
        known for sure.
 
713
        """
 
714
        self.overrideAttr(lockdir, 'get_host_name',
 
715
            lambda: 'localhost')
 
716
        info = LockHeldInfo.for_this_process(None)
 
717
        info.info_dict['pid'] = '123123123'
 
718
        self.assertFalse(info.is_lock_holder_known_dead())
 
719
 
 
720
 
 
721
class TestStaleLockDir(TestCaseWithTransport):
 
722
    """Can automatically break stale locks.
 
723
 
 
724
    :see: https://bugs.launchpad.net/bzr/+bug/220464
 
725
    """
 
726
 
 
727
    def test_auto_break_stale_lock(self):
 
728
        """Locks safely known to be stale are just cleaned up.
 
729
 
 
730
        This generates a warning but no other user interaction.
 
731
        """
 
732
        self.overrideAttr(lockdir, 'get_host_name',
 
733
            lambda: 'aproperhostname')
 
734
        # This is off by default at present; see the discussion in the bug.
 
735
        # If you change the default, don't forget to update the docs.
 
736
        config.GlobalConfig().set_user_option('locks.steal_dead', True)
 
737
        # Create a lock pretending to come from a different nonexistent
 
738
        # process on the same machine.
 
739
        l1 = LockDir(self.get_transport(), 'a',
 
740
            extra_holder_info={'pid': '12312313'})
 
741
        token_1 = l1.attempt_lock()
 
742
        l2 = LockDir(self.get_transport(), 'a')
 
743
        token_2 = l2.attempt_lock()
 
744
        # l1 will notice its lock was stolen.
 
745
        self.assertRaises(errors.LockBroken,
 
746
            l1.unlock)
 
747
        l2.unlock()
 
748
 
 
749
    def test_auto_break_stale_lock_configured_off(self):
 
750
        """Automatic breaking can be turned off"""
 
751
        l1 = LockDir(self.get_transport(), 'a',
 
752
            extra_holder_info={'pid': '12312313'})
 
753
        token_1 = l1.attempt_lock()
 
754
        self.addCleanup(l1.unlock)
 
755
        l2 = LockDir(self.get_transport(), 'a')
 
756
        # This fails now, because dead lock breaking is off by default.
 
757
        self.assertRaises(LockContention,
 
758
            l2.attempt_lock)
 
759
        # and it's in fact not broken
 
760
        l1.confirm()