1
# Copyright (C) 2006 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
"""Tests for LockDir"""
19
from cStringIO import StringIO
21
from threading import Thread, Lock
31
from bzrlib.errors import (
33
LockContention, LockError, UnlockableTransport,
34
LockNotHeld, LockBroken
36
from bzrlib.lockdir import LockDir, _DEFAULT_TIMEOUT_SECONDS
37
from bzrlib.tests import TestCaseWithTransport
38
from bzrlib.trace import note
40
# These tests sometimes use threads to test the behaviour of lock files with
41
# concurrent actors. This is not a typical (or necessarily supported) use;
42
# they're really meant for guarding between processes.
44
# These tests are run on the default transport provided by the test framework
45
# (typically a local disk transport). That can be changed by the --transport
46
# option to bzr selftest. The required properties of the transport
47
# implementation are tested separately. (The main requirement is just that
48
# they don't allow overwriting nonempty directories.)
50
class TestLockDir(TestCaseWithTransport):
51
"""Test LockDir operations"""
53
def logging_report_function(self, fmt, *args):
54
self._logged_reports.append((fmt, args))
56
def setup_log_reporter(self, lock_dir):
57
self._logged_reports = []
58
lock_dir._report_function = self.logging_report_function
60
def test_00_lock_creation(self):
61
"""Creation of lock file on a transport"""
62
t = self.get_transport()
63
lf = LockDir(t, 'test_lock')
64
self.assertFalse(lf.is_held)
66
def test_01_lock_repr(self):
67
"""Lock string representation"""
68
lf = LockDir(self.get_transport(), 'test_lock')
70
self.assertContainsRe(r, r'^LockDir\(.*/test_lock\)$')
72
def test_02_unlocked_peek(self):
73
lf = LockDir(self.get_transport(), 'test_lock')
74
self.assertEqual(lf.peek(), None)
77
return LockDir(self.get_transport(), 'test_lock')
79
def test_unlock_after_break_raises(self):
84
ld2.force_break(ld2.peek())
85
self.assertRaises(LockBroken, ld.unlock)
87
def test_03_readonly_peek(self):
88
lf = LockDir(self.get_readonly_transport(), 'test_lock')
89
self.assertEqual(lf.peek(), None)
91
def test_10_lock_uncontested(self):
92
"""Acquire and release a lock"""
93
t = self.get_transport()
94
lf = LockDir(t, 'test_lock')
98
self.assertTrue(lf.is_held)
101
self.assertFalse(lf.is_held)
103
def test_11_create_readonly_transport(self):
104
"""Fail to create lock on readonly transport"""
105
t = self.get_readonly_transport()
106
lf = LockDir(t, 'test_lock')
107
self.assertRaises(UnlockableTransport, lf.create)
109
def test_12_lock_readonly_transport(self):
110
"""Fail to lock on readonly transport"""
111
lf = LockDir(self.get_transport(), 'test_lock')
113
lf = LockDir(self.get_readonly_transport(), 'test_lock')
114
self.assertRaises(UnlockableTransport, lf.attempt_lock)
116
def test_20_lock_contested(self):
117
"""Contention to get a lock"""
118
t = self.get_transport()
119
lf1 = LockDir(t, 'test_lock')
122
lf2 = LockDir(t, 'test_lock')
124
# locking is between LockDir instances; aliases within
125
# a single process are not detected
127
self.fail('Failed to detect lock collision')
128
except LockContention, e:
129
self.assertEqual(e.lock, lf2)
130
self.assertContainsRe(str(e),
131
r'^Could not acquire.*test_lock.*$')
134
def test_20_lock_peek(self):
135
"""Peek at the state of a lock"""
136
t = self.get_transport()
137
lf1 = LockDir(t, 'test_lock')
140
# lock is held, should get some info on it
142
self.assertEqual(set(info1.keys()),
143
set(['user', 'nonce', 'hostname', 'pid', 'start_time']))
144
# should get the same info if we look at it through a different
146
info2 = LockDir(t, 'test_lock').peek()
147
self.assertEqual(info1, info2)
148
# locks which are never used should be not-held
149
self.assertEqual(LockDir(t, 'other_lock').peek(), None)
151
def test_21_peek_readonly(self):
152
"""Peek over a readonly transport"""
153
t = self.get_transport()
154
lf1 = LockDir(t, 'test_lock')
156
lf2 = LockDir(self.get_readonly_transport(), 'test_lock')
157
self.assertEqual(lf2.peek(), None)
160
self.assertTrue(info2)
161
self.assertEqual(info2['nonce'], lf1.nonce)
163
def test_30_lock_wait_fail(self):
164
"""Wait on a lock, then fail
166
We ask to wait up to 400ms; this should fail within at most one
167
second. (Longer times are more realistic but we don't want the test
168
suite to take too long, and this should do for now.)
170
t = self.get_transport()
171
lf1 = LockDir(t, 'test_lock')
173
lf2 = LockDir(t, 'test_lock')
174
self.setup_log_reporter(lf2)
178
self.assertRaises(LockContention, lf2.wait_lock,
179
timeout=0.4, poll=0.1)
181
# it should only take about 0.4 seconds, but we allow more time in
182
# case the machine is heavily loaded
183
self.assertTrue(after - before <= 8.0,
184
"took %f seconds to detect lock contention" % (after - before))
187
lock_base = lf2.transport.abspath(lf2.path)
188
self.assertEqual(1, len(self._logged_reports))
189
self.assertEqual('%s %s\n'
191
'Will continue to try until %s\n',
192
self._logged_reports[0][0])
193
args = self._logged_reports[0][1]
194
self.assertEqual('Unable to obtain', args[0])
195
self.assertEqual('lock %s' % (lock_base,), args[1])
196
self.assertStartsWith(args[2], 'held by ')
197
self.assertStartsWith(args[3], 'locked ')
198
self.assertEndsWith(args[3], ' ago')
199
self.assertContainsRe(args[4], r'\d\d:\d\d:\d\d')
201
def test_31_lock_wait_easy(self):
202
"""Succeed when waiting on a lock with no contention.
204
t = self.get_transport()
205
lf1 = LockDir(t, 'test_lock')
207
self.setup_log_reporter(lf1)
210
lf1.wait_lock(timeout=0.4, poll=0.1)
212
self.assertTrue(after - before <= 1.0)
215
self.assertEqual([], self._logged_reports)
217
def test_32_lock_wait_succeed(self):
218
"""Succeed when trying to acquire a lock that gets released
220
One thread holds on a lock and then releases it; another
223
t = self.get_transport()
224
lf1 = LockDir(t, 'test_lock')
228
def wait_and_unlock():
231
unlocker = Thread(target=wait_and_unlock)
234
lf2 = LockDir(t, 'test_lock')
235
self.setup_log_reporter(lf2)
238
lf2.wait_lock(timeout=0.4, poll=0.1)
240
self.assertTrue(after - before <= 1.0)
244
# There should be only 1 report, even though it should have to
246
lock_base = lf2.transport.abspath(lf2.path)
247
self.assertEqual(1, len(self._logged_reports))
248
self.assertEqual('%s %s\n'
250
'Will continue to try until %s\n',
251
self._logged_reports[0][0])
252
args = self._logged_reports[0][1]
253
self.assertEqual('Unable to obtain', args[0])
254
self.assertEqual('lock %s' % (lock_base,), args[1])
255
self.assertStartsWith(args[2], 'held by ')
256
self.assertStartsWith(args[3], 'locked ')
257
self.assertEndsWith(args[3], ' ago')
258
self.assertContainsRe(args[4], r'\d\d:\d\d:\d\d')
260
def test_33_wait(self):
261
"""Succeed when waiting on a lock that gets released
263
The difference from test_32_lock_wait_succeed is that the second
264
caller does not actually acquire the lock, but just waits for it
265
to be released. This is done over a readonly transport.
267
t = self.get_transport()
268
lf1 = LockDir(t, 'test_lock')
272
def wait_and_unlock():
275
unlocker = Thread(target=wait_and_unlock)
278
lf2 = LockDir(self.get_readonly_transport(), 'test_lock')
280
# wait but don't lock
281
lf2.wait(timeout=0.4, poll=0.1)
283
self.assertTrue(after - before <= 1.0)
287
def test_34_lock_write_waits(self):
288
"""LockDir.lock_write() will wait for the lock."""
289
t = self.get_transport()
290
lf1 = LockDir(t, 'test_lock')
294
def wait_and_unlock():
297
unlocker = Thread(target=wait_and_unlock)
300
lf2 = LockDir(t, 'test_lock')
301
self.setup_log_reporter(lf2)
309
# There should be only 1 report, even though it should have to
311
lock_base = lf2.transport.abspath(lf2.path)
312
self.assertEqual(1, len(self._logged_reports))
313
self.assertEqual('%s %s\n'
315
'Will continue to try until %s\n',
316
self._logged_reports[0][0])
317
args = self._logged_reports[0][1]
318
self.assertEqual('Unable to obtain', args[0])
319
self.assertEqual('lock %s' % (lock_base,), args[1])
320
self.assertStartsWith(args[2], 'held by ')
321
self.assertStartsWith(args[3], 'locked ')
322
self.assertEndsWith(args[3], ' ago')
323
self.assertContainsRe(args[4], r'\d\d:\d\d:\d\d')
325
def test_35_wait_lock_changing(self):
326
"""LockDir.wait_lock() will report if the lock changes underneath.
328
This is the stages we want to happen:
330
0) Synchronization locks are created and locked.
331
1) Lock1 obtains the lockdir, and releases the 'check' lock.
332
2) Lock2 grabs the 'check' lock, and checks the lockdir.
333
It sees the lockdir is already acquired, reports the fact,
334
and unsets the 'checked' lock.
335
3) Thread1 blocks on acquiring the 'checked' lock, and then tells
336
Lock1 to release and acquire the lockdir. This resets the 'check'
338
4) Lock2 acquires the 'check' lock, and checks again. It notices
339
that the holder of the lock has changed, and so reports a new
341
5) Thread1 blocks on the 'checked' lock, this time, it completely
342
unlocks the lockdir, allowing Lock2 to acquire the lock.
345
wait_to_check_lock = Lock()
346
wait_until_checked_lock = Lock()
348
wait_to_check_lock.acquire()
349
wait_until_checked_lock.acquire()
350
note('locked check and checked locks')
352
class LockDir1(LockDir):
353
"""Use the synchronization points for the first lock."""
355
def attempt_lock(self):
356
# Once we have acquired the lock, it is okay for
357
# the other lock to check it
359
return super(LockDir1, self).attempt_lock()
361
note('lock1: releasing check lock')
362
wait_to_check_lock.release()
364
class LockDir2(LockDir):
365
"""Use the synchronization points for the second lock."""
367
def attempt_lock(self):
368
note('lock2: waiting for check lock')
369
wait_to_check_lock.acquire()
370
note('lock2: acquired check lock')
372
return super(LockDir2, self).attempt_lock()
374
note('lock2: releasing checked lock')
375
wait_until_checked_lock.release()
377
t = self.get_transport()
378
lf1 = LockDir1(t, 'test_lock')
381
lf2 = LockDir2(t, 'test_lock')
382
self.setup_log_reporter(lf2)
384
def wait_and_switch():
386
# Block until lock2 has had a chance to check
387
note('lock1: waiting 1 for checked lock')
388
wait_until_checked_lock.acquire()
389
note('lock1: acquired for checked lock')
390
note('lock1: released lockdir')
392
note('lock1: acquiring lockdir')
393
# Create a new nonce, so the lock looks different.
394
lf1.nonce = osutils.rand_chars(20)
396
note('lock1: acquired lockdir')
398
# Block until lock2 has peeked again
399
note('lock1: waiting 2 for checked lock')
400
wait_until_checked_lock.acquire()
401
note('lock1: acquired for checked lock')
402
# Now unlock, and let lock 2 grab the lock
404
wait_to_check_lock.release()
406
unlocker = Thread(target=wait_and_switch)
409
# Wait and play against the other thread
410
lf2.wait_lock(timeout=1.0, poll=0.01)
415
# There should be 2 reports, because the lock changed
416
lock_base = lf2.transport.abspath(lf2.path)
417
self.assertEqual(2, len(self._logged_reports))
419
self.assertEqual('%s %s\n'
421
'Will continue to try until %s\n',
422
self._logged_reports[0][0])
423
args = self._logged_reports[0][1]
424
self.assertEqual('Unable to obtain', args[0])
425
self.assertEqual('lock %s' % (lock_base,), args[1])
426
self.assertStartsWith(args[2], 'held by ')
427
self.assertStartsWith(args[3], 'locked ')
428
self.assertEndsWith(args[3], ' ago')
429
self.assertContainsRe(args[4], r'\d\d:\d\d:\d\d')
431
self.assertEqual('%s %s\n'
433
'Will continue to try until %s\n',
434
self._logged_reports[1][0])
435
args = self._logged_reports[1][1]
436
self.assertEqual('Lock owner changed for', args[0])
437
self.assertEqual('lock %s' % (lock_base,), args[1])
438
self.assertStartsWith(args[2], 'held by ')
439
self.assertStartsWith(args[3], 'locked ')
440
self.assertEndsWith(args[3], ' ago')
441
self.assertContainsRe(args[4], r'\d\d:\d\d:\d\d')
443
def test_40_confirm_easy(self):
444
"""Confirm a lock that's already held"""
445
t = self.get_transport()
446
lf1 = LockDir(t, 'test_lock')
451
def test_41_confirm_not_held(self):
452
"""Confirm a lock that's already held"""
453
t = self.get_transport()
454
lf1 = LockDir(t, 'test_lock')
456
self.assertRaises(LockNotHeld, lf1.confirm)
458
def test_42_confirm_broken_manually(self):
459
"""Confirm a lock broken by hand"""
460
t = self.get_transport()
461
lf1 = LockDir(t, 'test_lock')
464
t.move('test_lock', 'lock_gone_now')
465
self.assertRaises(LockBroken, lf1.confirm)
467
def test_43_break(self):
468
"""Break a lock whose caller has forgotten it"""
469
t = self.get_transport()
470
lf1 = LockDir(t, 'test_lock')
473
# we incorrectly discard the lock object without unlocking it
475
# someone else sees it's still locked
476
lf2 = LockDir(t, 'test_lock')
477
holder_info = lf2.peek()
478
self.assertTrue(holder_info)
479
lf2.force_break(holder_info)
480
# now we should be able to take it
484
def test_44_break_already_released(self):
485
"""Lock break races with regular release"""
486
t = self.get_transport()
487
lf1 = LockDir(t, 'test_lock')
490
# someone else sees it's still locked
491
lf2 = LockDir(t, 'test_lock')
492
holder_info = lf2.peek()
493
# in the interim the lock is released
495
# break should succeed
496
lf2.force_break(holder_info)
497
# now we should be able to take it
501
def test_45_break_mismatch(self):
502
"""Lock break races with someone else acquiring it"""
503
t = self.get_transport()
504
lf1 = LockDir(t, 'test_lock')
507
# someone else sees it's still locked
508
lf2 = LockDir(t, 'test_lock')
509
holder_info = lf2.peek()
510
# in the interim the lock is released
512
lf3 = LockDir(t, 'test_lock')
514
# break should now *fail*
515
self.assertRaises(LockBreakMismatch, lf2.force_break,
519
def test_46_fake_read_lock(self):
520
t = self.get_transport()
521
lf1 = LockDir(t, 'test_lock')
526
def test_50_lockdir_representation(self):
527
"""Check the on-disk representation of LockDirs is as expected.
529
There should always be a top-level directory named by the lock.
530
When the lock is held, there should be a lockname/held directory
531
containing an info file.
533
t = self.get_transport()
534
lf1 = LockDir(t, 'test_lock')
536
self.assertTrue(t.has('test_lock'))
538
self.assertTrue(t.has('test_lock/held/info'))
540
self.assertFalse(t.has('test_lock/held/info'))
542
def test_break_lock(self):
543
# the ui based break_lock routine should Just Work (tm)
544
ld1 = self.get_lock()
545
ld2 = self.get_lock()
548
# do this without IO redirection to ensure it doesn't prompt.
549
self.assertRaises(AssertionError, ld1.break_lock)
550
orig_factory = bzrlib.ui.ui_factory
551
# silent ui - no need for stdout
552
bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
553
bzrlib.ui.ui_factory.stdin = StringIO("y\n")
556
self.assertRaises(LockBroken, ld1.unlock)
558
bzrlib.ui.ui_factory = orig_factory
560
def test_create_missing_base_directory(self):
561
"""If LockDir.path doesn't exist, it can be created
563
Some people manually remove the entire lock/ directory trying
564
to unlock a stuck repository/branch/etc. Rather than failing
565
after that, just create the lock directory when needed.
567
t = self.get_transport()
568
lf1 = LockDir(t, 'test_lock')
571
self.failUnless(t.has('test_lock'))
574
self.failIf(t.has('test_lock'))
576
# This will create 'test_lock' if it needs to
578
self.failUnless(t.has('test_lock'))
579
self.failUnless(t.has('test_lock/held/info'))
582
self.failIf(t.has('test_lock/held/info'))
584
def test__format_lock_info(self):
585
ld1 = self.get_lock()
589
info_list = ld1._format_lock_info(ld1.peek())
592
self.assertEqual('lock %s' % (ld1.transport.abspath(ld1.path),),
594
self.assertContainsRe(info_list[1],
595
r'^held by .* on host .* \[process #\d*\]$')
596
self.assertContainsRe(info_list[2], r'locked \d+ seconds? ago$')
598
def test_lock_without_email(self):
599
global_config = config.GlobalConfig()
600
# Intentionally has no email address
601
global_config.set_user_option('email', 'User Identity')
602
ld1 = self.get_lock()
607
def test_lock_permission(self):
608
if not osutils.supports_posix_readonly():
609
raise tests.TestSkipped('Cannot induce a permission failure')
610
ld1 = self.get_lock()
611
lock_path = ld1.transport.local_abspath('test_lock')
613
osutils.make_readonly(lock_path)
614
self.assertRaises(errors.PermissionDenied, ld1.attempt_lock)