/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 breezy/tests/test_lockdir.py

  • Committer: Jelmer Vernooij
  • Date: 2017-12-03 15:14:22 UTC
  • mfrom: (6829.1.1 no-branch-nick)
  • Revision ID: jelmer@jelmer.uk-20171203151422-54pwtld2ae5cx11l
Merge lp:~jelmer/brz/no-branch-nick.

Show diffs side-by-side

added added

removed removed

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