bzr branch
http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
1 |
# Copyright (C) 2006, 2007 Canonical Ltd
|
|
1887.1.1
by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines, |
2 |
#
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
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.
|
|
|
1887.1.1
by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines, |
7 |
#
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
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.
|
|
|
1887.1.1
by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines, |
12 |
#
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
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
|
|
16 |
||
|
1553.5.31
by Martin Pool
LockDir doc corrections |
17 |
"""On-disk mutex protecting a resource
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
18 |
|
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
19 |
bzr on-disk objects are locked by the existence of a directory with a
|
20 |
particular name within the control directory. We use this rather than OS
|
|
21 |
internal locks (such as flock etc) because they can be seen across all
|
|
22 |
transports, including http.
|
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
23 |
|
24 |
Objects can be read if there is only physical read access; therefore
|
|
25 |
readers can never be required to create a lock, though they will
|
|
26 |
check whether a writer is using the lock. Writers can't detect
|
|
27 |
whether anyone else is reading from the resource as they write.
|
|
28 |
This works because of ordering constraints that make sure readers
|
|
29 |
see a consistent view of existing data.
|
|
30 |
||
31 |
Waiting for a lock must be done by polling; this can be aborted after
|
|
32 |
a timeout.
|
|
33 |
||
34 |
Locks must always be explicitly released, typically from a try/finally
|
|
35 |
block -- they are not released from a finalizer or when Python
|
|
36 |
exits.
|
|
37 |
||
38 |
Locks may fail to be released if the process is abruptly terminated
|
|
39 |
(machine stop, SIGKILL) or if a remote transport becomes permanently
|
|
40 |
disconnected. There is therefore a method to break an existing lock.
|
|
41 |
This should rarely be used, and generally only with user approval.
|
|
42 |
Locks contain some information on when the lock was taken and by who
|
|
43 |
which may guide in deciding whether it can safely be broken. (This is
|
|
44 |
similar to the messages displayed by emacs and vim.) Note that if the
|
|
45 |
lock holder is still alive they will get no notification that the lock
|
|
46 |
has been broken and will continue their work -- so it is important to be
|
|
47 |
sure they are actually dead.
|
|
48 |
||
49 |
A lock is represented on disk by a directory of a particular name,
|
|
50 |
containing an information file. Taking a lock is done by renaming a
|
|
51 |
temporary directory into place. We use temporary directories because
|
|
52 |
for all known transports and filesystems we believe that exactly one
|
|
53 |
attempt to claim the lock will succeed and the others will fail. (Files
|
|
54 |
won't do because some filesystems or transports only have
|
|
55 |
rename-and-overwrite, making it hard to tell who won.)
|
|
56 |
||
57 |
The desired characteristics are:
|
|
58 |
||
59 |
* Locks are not reentrant. (That is, a client that tries to take a
|
|
60 |
lock it already holds may deadlock or fail.)
|
|
61 |
* Stale locks can be guessed at by a heuristic
|
|
62 |
* Lost locks can be broken by any client
|
|
63 |
* Failed lock operations leave little or no mess
|
|
64 |
* Deadlocks are avoided by having a timeout always in use, clients
|
|
65 |
desiring indefinite waits can retry or set a silly big timeout.
|
|
66 |
||
67 |
Storage formats use the locks, and also need to consider concurrency
|
|
68 |
issues underneath the lock. A format may choose not to use a lock
|
|
69 |
at all for some operations.
|
|
70 |
||
71 |
LockDirs always operate over a Transport. The transport may be readonly, in
|
|
72 |
which case the lock can be queried but not acquired.
|
|
73 |
||
74 |
Locks are identified by a path name, relative to a base transport.
|
|
75 |
||
76 |
Calling code will typically want to make sure there is exactly one LockDir
|
|
77 |
object per actual lock on disk. This module does nothing to prevent aliasing
|
|
78 |
and deadlocks will likely occur if the locks are aliased.
|
|
79 |
||
80 |
In the future we may add a "freshen" method which can be called
|
|
81 |
by a lock holder to check that their lock has not been broken, and to
|
|
82 |
update the timestamp within it.
|
|
83 |
||
|
1553.5.18
by Martin Pool
LockDir should use Transport.rename when releasing locks too. |
84 |
Example usage:
|
85 |
||
86 |
>>> from bzrlib.transport.memory import MemoryTransport
|
|
87 |
>>> # typically will be obtained from a BzrDir, Branch, etc
|
|
88 |
>>> t = MemoryTransport()
|
|
89 |
>>> l = LockDir(t, 'sample-lock')
|
|
|
1553.5.61
by Martin Pool
Locks protecting LockableFiles must now be explicitly created before use. |
90 |
>>> l.create()
|
|
1553.5.18
by Martin Pool
LockDir should use Transport.rename when releasing locks too. |
91 |
>>> l.wait_lock()
|
92 |
>>> # do something here
|
|
93 |
>>> l.unlock()
|
|
94 |
||
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
95 |
"""
|
96 |
||
97 |
import os |
|
98 |
import time |
|
|
1957.1.1
by John Arbash Meinel
Report to the user when we are spinning on a lock |
99 |
from cStringIO import StringIO |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
100 |
|
|
2055.2.1
by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email |
101 |
from bzrlib import ( |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
102 |
debug, |
|
2055.2.1
by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email |
103 |
errors, |
104 |
)
|
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
105 |
import bzrlib.config |
106 |
from bzrlib.errors import ( |
|
107 |
DirectoryNotEmpty, |
|
108 |
FileExists, |
|
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
109 |
LockBreakMismatch, |
|
1553.5.23
by Martin Pool
Start LockDir.confirm method and LockBroken exception |
110 |
LockBroken, |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
111 |
LockContention, |
112 |
LockNotHeld, |
|
113 |
NoSuchFile, |
|
|
1662.1.12
by Martin Pool
Translate unknown sftp errors to PathError, no NoSuchFile |
114 |
PathError, |
|
1558.10.1
by Aaron Bentley
Handle lockdirs over NFS properly |
115 |
ResourceBusy, |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
116 |
UnlockableTransport, |
117 |
)
|
|
|
1957.1.1
by John Arbash Meinel
Report to the user when we are spinning on a lock |
118 |
from bzrlib.trace import mutter, note |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
119 |
from bzrlib.transport import Transport |
|
1957.1.5
by John Arbash Meinel
Create a helper function for formatting lock information |
120 |
from bzrlib.osutils import rand_chars, format_delta |
|
1993.1.2
by John Arbash Meinel
Use Stanza.to_string() rather than a RioWriter |
121 |
from bzrlib.rio import read_stanza, Stanza |
|
2094.3.5
by John Arbash Meinel
Fix imports to ensure modules are loaded before they are used |
122 |
import bzrlib.ui |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
123 |
|
|
1957.1.15
by John Arbash Meinel
Review feedback from Robert |
124 |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
125 |
# XXX: At the moment there is no consideration of thread safety on LockDir
|
126 |
# objects. This should perhaps be updated - e.g. if two threads try to take a
|
|
127 |
# lock at the same time they should *both* get it. But then that's unlikely
|
|
128 |
# to be a good idea.
|
|
129 |
||
130 |
# TODO: Perhaps store some kind of note like the bzr command line in the lock
|
|
131 |
# info?
|
|
132 |
||
133 |
# TODO: Some kind of callback run while polling a lock to show progress
|
|
134 |
# indicators.
|
|
135 |
||
|
1553.5.59
by Martin Pool
Pass file/mode bits through to creation of lock files/dirs |
136 |
# TODO: Make sure to pass the right file and directory mode bits to all
|
137 |
# files/dirs created.
|
|
138 |
||
|
1957.1.15
by John Arbash Meinel
Review feedback from Robert |
139 |
|
140 |
_DEFAULT_TIMEOUT_SECONDS = 300 |
|
|
1957.1.9
by John Arbash Meinel
Change default timeouts, and report differently the first failure |
141 |
_DEFAULT_POLL_SECONDS = 1.0 |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
142 |
|
|
1957.1.15
by John Arbash Meinel
Review feedback from Robert |
143 |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
144 |
class LockDir(object): |
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
145 |
"""Write-lock guarding access to data.""" |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
146 |
|
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
147 |
__INFO_NAME = '/info' |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
148 |
|
|
1553.5.59
by Martin Pool
Pass file/mode bits through to creation of lock files/dirs |
149 |
def __init__(self, transport, path, file_modebits=0644, dir_modebits=0755): |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
150 |
"""Create a new LockDir object. |
151 |
||
152 |
The LockDir is initially unlocked - this just creates the object.
|
|
153 |
||
154 |
:param transport: Transport which will contain the lock
|
|
155 |
||
156 |
:param path: Path to the lock within the base directory of the
|
|
157 |
transport.
|
|
158 |
"""
|
|
159 |
assert isinstance(transport, Transport), \ |
|
160 |
("not a transport: %r" % transport) |
|
161 |
self.transport = transport |
|
162 |
self.path = path |
|
163 |
self._lock_held = False |
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
164 |
self._locked_via_token = False |
|
1553.5.54
by Martin Pool
Add LockDir.read_lock fake method |
165 |
self._fake_read_lock = False |
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
166 |
self._held_dir = path + '/held' |
167 |
self._held_info_path = self._held_dir + self.__INFO_NAME |
|
|
1553.5.59
by Martin Pool
Pass file/mode bits through to creation of lock files/dirs |
168 |
self._file_modebits = file_modebits |
169 |
self._dir_modebits = dir_modebits |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
170 |
|
|
1957.1.1
by John Arbash Meinel
Report to the user when we are spinning on a lock |
171 |
self._report_function = note |
172 |
||
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
173 |
def __repr__(self): |
174 |
return '%s(%s%s)' % (self.__class__.__name__, |
|
175 |
self.transport.base, |
|
176 |
self.path) |
|
177 |
||
|
1553.5.13
by Martin Pool
New Transport.rename that mustn't overwrite |
178 |
is_held = property(lambda self: self._lock_held) |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
179 |
|
|
1666.1.4
by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in |
180 |
def create(self, mode=None): |
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
181 |
"""Create the on-disk lock. |
182 |
||
183 |
This is typically only called when the object/directory containing the
|
|
184 |
directory is first created. The lock is not held when it's created.
|
|
185 |
"""
|
|
186 |
if self.transport.is_readonly(): |
|
187 |
raise UnlockableTransport(self.transport) |
|
|
1666.1.4
by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in |
188 |
self.transport.mkdir(self.path, mode=mode) |
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
189 |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
190 |
def attempt_lock(self): |
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
191 |
"""Take the lock; fail if it's already held. |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
192 |
|
193 |
If you wish to block until the lock can be obtained, call wait_lock()
|
|
194 |
instead.
|
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
195 |
|
196 |
:return: The lock token.
|
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
197 |
"""
|
|
1553.5.54
by Martin Pool
Add LockDir.read_lock fake method |
198 |
if self._fake_read_lock: |
199 |
raise LockContention(self) |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
200 |
if self.transport.is_readonly(): |
201 |
raise UnlockableTransport(self.transport) |
|
202 |
try: |
|
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
203 |
self._trace("lock_write...") |
204 |
start_time = time.time() |
|
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
205 |
tmpname = '%s/pending.%s.tmp' % (self.path, rand_chars(20)) |
|
1955.1.1
by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile. |
206 |
try: |
207 |
self.transport.mkdir(tmpname) |
|
208 |
except NoSuchFile: |
|
209 |
# This may raise a FileExists exception
|
|
210 |
# which is okay, it will be caught later and determined
|
|
211 |
# to be a LockContention.
|
|
212 |
self.create(mode=self._dir_modebits) |
|
213 |
||
214 |
# After creating the lock directory, try again
|
|
215 |
self.transport.mkdir(tmpname) |
|
216 |
||
|
2018.5.75
by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place. |
217 |
self.nonce = rand_chars(20) |
|
1993.1.2
by John Arbash Meinel
Use Stanza.to_string() rather than a RioWriter |
218 |
info_bytes = self._prepare_info() |
|
1993.1.1
by John Arbash Meinel
Use put_file_non_atomic in lockdir() to save some sftp round trips |
219 |
# We use put_file_non_atomic because we just created a new unique
|
220 |
# directory so we don't have to worry about files existing there.
|
|
221 |
# We'll rename the whole directory into place to get atomic
|
|
222 |
# properties
|
|
|
1993.1.2
by John Arbash Meinel
Use Stanza.to_string() rather than a RioWriter |
223 |
self.transport.put_bytes_non_atomic(tmpname + self.__INFO_NAME, |
224 |
info_bytes) |
|
|
1955.1.1
by John Arbash Meinel
LockDir can create the root directory if it fails to create a pending directory due to NoSuchFile. |
225 |
|
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
226 |
self.transport.rename(tmpname, self._held_dir) |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
227 |
self._lock_held = True |
|
2555.3.4
by Martin Pool
Remove unnecessary confirmation after acquiring LockDir |
228 |
# we used to do self.confirm() at this point, but it's really
|
229 |
# unnecessary, we have no substantial chance of having it broken
|
|
230 |
# just as it's acquired, and we believe that this lock design is
|
|
231 |
# safe on all platforms.
|
|
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
232 |
# FIXME: we should remove the pending lock if we fail,
|
233 |
# https://bugs.launchpad.net/bzr/+bug/109169
|
|
|
1551.10.3
by Aaron Bentley
Lock attempts don't treat permission problems as lock contention |
234 |
except errors.PermissionDenied: |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
235 |
self._trace("... lock failed, permission denied") |
|
1551.10.3
by Aaron Bentley
Lock attempts don't treat permission problems as lock contention |
236 |
raise
|
|
1662.1.12
by Martin Pool
Translate unknown sftp errors to PathError, no NoSuchFile |
237 |
except (PathError, DirectoryNotEmpty, FileExists, ResourceBusy), e: |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
238 |
self._trace("... contention, %s", e) |
|
1662.1.12
by Martin Pool
Translate unknown sftp errors to PathError, no NoSuchFile |
239 |
raise LockContention(self) |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
240 |
self._trace("... lock succeeded after %dms", |
241 |
(time.time() - start_time) * 1000) |
|
|
2555.3.6
by Martin Pool
Restore disabled LockDir trace message |
242 |
return self.nonce |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
243 |
|
244 |
def unlock(self): |
|
|
1553.5.30
by Martin Pool
docstring for LockDir.unlock |
245 |
"""Release a held lock |
246 |
"""
|
|
|
1553.5.54
by Martin Pool
Add LockDir.read_lock fake method |
247 |
if self._fake_read_lock: |
248 |
self._fake_read_lock = False |
|
249 |
return
|
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
250 |
if not self._lock_held: |
251 |
raise LockNotHeld(self) |
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
252 |
if self._locked_via_token: |
253 |
self._locked_via_token = False |
|
254 |
self._lock_held = False |
|
255 |
else: |
|
256 |
# rename before deleting, because we can't atomically remove the
|
|
257 |
# whole tree
|
|
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
258 |
start_time = time.time() |
259 |
self._trace("unlocking") |
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
260 |
tmpname = '%s/releasing.%s.tmp' % (self.path, rand_chars(20)) |
261 |
# gotta own it to unlock
|
|
262 |
self.confirm() |
|
263 |
self.transport.rename(self._held_dir, tmpname) |
|
264 |
self._lock_held = False |
|
265 |
self.transport.delete(tmpname + self.__INFO_NAME) |
|
266 |
self.transport.rmdir(tmpname) |
|
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
267 |
self._trace("... unlock succeeded after %dms", |
268 |
(time.time() - start_time) * 1000) |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
269 |
|
|
1687.1.5
by Robert Collins
Add break_lock utility function to LockDir. |
270 |
def break_lock(self): |
271 |
"""Break a lock not held by this instance of LockDir. |
|
272 |
||
273 |
This is a UI centric function: it uses the bzrlib.ui.ui_factory to
|
|
274 |
prompt for input if a lock is detected and there is any doubt about
|
|
275 |
it possibly being still active.
|
|
276 |
"""
|
|
|
1687.1.6
by Robert Collins
Extend LockableFiles to support break_lock() calls. |
277 |
self._check_not_locked() |
|
1687.1.5
by Robert Collins
Add break_lock utility function to LockDir. |
278 |
holder_info = self.peek() |
279 |
if holder_info is not None: |
|
|
1957.1.5
by John Arbash Meinel
Create a helper function for formatting lock information |
280 |
lock_info = '\n'.join(self._format_lock_info(holder_info)) |
281 |
if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info): |
|
|
1687.1.5
by Robert Collins
Add break_lock utility function to LockDir. |
282 |
self.force_break(holder_info) |
283 |
||
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
284 |
def force_break(self, dead_holder_info): |
|
1553.5.25
by Martin Pool
New LockDir.force_break and simple test case |
285 |
"""Release a lock held by another process. |
286 |
||
287 |
WARNING: This should only be used when the other process is dead; if
|
|
288 |
it still thinks it has the lock there will be two concurrent writers.
|
|
289 |
In general the user's approval should be sought for lock breaks.
|
|
290 |
||
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
291 |
dead_holder_info must be the result of a previous LockDir.peek() call;
|
292 |
this is used to check that it's still held by the same process that
|
|
293 |
the user decided was dead. If this is not the current holder,
|
|
294 |
LockBreakMismatch is raised.
|
|
295 |
||
|
1553.5.25
by Martin Pool
New LockDir.force_break and simple test case |
296 |
After the lock is broken it will not be held by any process.
|
297 |
It is possible that another process may sneak in and take the
|
|
298 |
lock before the breaking process acquires it.
|
|
299 |
"""
|
|
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
300 |
if not isinstance(dead_holder_info, dict): |
301 |
raise ValueError("dead_holder_info: %r" % dead_holder_info) |
|
|
1687.1.6
by Robert Collins
Extend LockableFiles to support break_lock() calls. |
302 |
self._check_not_locked() |
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
303 |
current_info = self.peek() |
304 |
if current_info is None: |
|
|
1553.5.26
by Martin Pool
Breaking an already-released lock should just succeed |
305 |
# must have been recently released
|
306 |
return
|
|
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
307 |
if current_info != dead_holder_info: |
308 |
raise LockBreakMismatch(self, current_info, dead_holder_info) |
|
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
309 |
tmpname = '%s/broken.%s.tmp' % (self.path, rand_chars(20)) |
310 |
self.transport.rename(self._held_dir, tmpname) |
|
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
311 |
# check that we actually broke the right lock, not someone else;
|
312 |
# there's a small race window between checking it and doing the
|
|
313 |
# rename.
|
|
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
314 |
broken_info_path = tmpname + self.__INFO_NAME |
315 |
broken_info = self._read_info_file(broken_info_path) |
|
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
316 |
if broken_info != dead_holder_info: |
317 |
raise LockBreakMismatch(self, broken_info, dead_holder_info) |
|
318 |
self.transport.delete(broken_info_path) |
|
|
1553.5.25
by Martin Pool
New LockDir.force_break and simple test case |
319 |
self.transport.rmdir(tmpname) |
320 |
||
|
1687.1.6
by Robert Collins
Extend LockableFiles to support break_lock() calls. |
321 |
def _check_not_locked(self): |
322 |
"""If the lock is held by this instance, raise an error.""" |
|
323 |
if self._lock_held: |
|
324 |
raise AssertionError("can't break own lock: %r" % self) |
|
325 |
||
|
1553.5.20
by Martin Pool
Start adding LockDir.confirm() method |
326 |
def confirm(self): |
327 |
"""Make sure that the lock is still held by this locker. |
|
328 |
||
329 |
This should only fail if the lock was broken by user intervention,
|
|
330 |
or if the lock has been affected by a bug.
|
|
331 |
||
332 |
If the lock is not thought to be held, raises LockNotHeld. If
|
|
333 |
the lock is thought to be held but has been broken, raises
|
|
334 |
LockBroken.
|
|
335 |
"""
|
|
336 |
if not self._lock_held: |
|
337 |
raise LockNotHeld(self) |
|
|
1553.5.23
by Martin Pool
Start LockDir.confirm method and LockBroken exception |
338 |
info = self.peek() |
339 |
if info is None: |
|
340 |
# no lock there anymore!
|
|
341 |
raise LockBroken(self) |
|
342 |
if info.get('nonce') != self.nonce: |
|
343 |
# there is a lock, but not ours
|
|
344 |
raise LockBroken(self) |
|
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
345 |
|
346 |
def _read_info_file(self, path): |
|
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
347 |
"""Read one given info file. |
348 |
||
349 |
peek() reads the info file of the lock holder, if any.
|
|
350 |
"""
|
|
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
351 |
return self._parse_info(self.transport.get(path)) |
|
1553.5.20
by Martin Pool
Start adding LockDir.confirm() method |
352 |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
353 |
def peek(self): |
354 |
"""Check if the lock is held by anyone. |
|
355 |
|
|
356 |
If it is held, this returns the lock info structure as a rio Stanza,
|
|
357 |
which contains some information about the current lock holder.
|
|
358 |
Otherwise returns None.
|
|
359 |
"""
|
|
360 |
try: |
|
|
1553.5.58
by Martin Pool
Change LockDirs to format "lock-name/held/info" |
361 |
info = self._read_info_file(self._held_info_path) |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
362 |
self._trace("peek -> held") |
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
363 |
assert isinstance(info, dict), \ |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
364 |
"bad parse result %r" % info |
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
365 |
return info |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
366 |
except NoSuchFile, e: |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
367 |
self._trace("peek -> not held") |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
368 |
|
|
1993.1.2
by John Arbash Meinel
Use Stanza.to_string() rather than a RioWriter |
369 |
def _prepare_info(self): |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
370 |
"""Write information about a pending lock to a temporary file. |
371 |
"""
|
|
372 |
import socket |
|
373 |
# XXX: is creating this here inefficient?
|
|
374 |
config = bzrlib.config.GlobalConfig() |
|
|
2055.2.1
by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email |
375 |
try: |
376 |
user = config.user_email() |
|
|
2055.2.2
by John Arbash Meinel
Switch extract_email_address() to use a more specific exception |
377 |
except errors.NoEmailInUsername: |
|
2055.2.1
by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email |
378 |
user = config.username() |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
379 |
s = Stanza(hostname=socket.gethostname(), |
380 |
pid=str(os.getpid()), |
|
381 |
start_time=str(int(time.time())), |
|
382 |
nonce=self.nonce, |
|
|
2055.2.1
by John Arbash Meinel
Make LockDir less sensitive to invalid configuration of email |
383 |
user=user, |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
384 |
)
|
|
1993.1.2
by John Arbash Meinel
Use Stanza.to_string() rather than a RioWriter |
385 |
return s.to_string() |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
386 |
|
387 |
def _parse_info(self, info_file): |
|
|
1553.5.27
by Martin Pool
Confirm that only the intended holder of a lock was broken. |
388 |
return read_stanza(info_file.readlines()).as_dict() |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
389 |
|
|
1957.1.17
by John Arbash Meinel
Change tests that expect locking to fail to timeout sooner. |
390 |
def wait_lock(self, timeout=None, poll=None): |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
391 |
"""Wait a certain period for a lock. |
392 |
||
393 |
If the lock can be acquired within the bounded time, it
|
|
394 |
is taken and this returns. Otherwise, LockContention
|
|
395 |
is raised. Either way, this function should return within
|
|
396 |
approximately `timeout` seconds. (It may be a bit more if
|
|
397 |
a transport operation takes a long time to complete.)
|
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
398 |
|
399 |
:return: The lock token.
|
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
400 |
"""
|
|
1957.1.17
by John Arbash Meinel
Change tests that expect locking to fail to timeout sooner. |
401 |
if timeout is None: |
402 |
timeout = _DEFAULT_TIMEOUT_SECONDS |
|
403 |
if poll is None: |
|
404 |
poll = _DEFAULT_POLL_SECONDS |
|
405 |
||
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
406 |
# XXX: the transport interface doesn't let us guard
|
407 |
# against operations there taking a long time.
|
|
408 |
deadline = time.time() + timeout |
|
|
1957.1.13
by John Arbash Meinel
Change to reporting the time when we will stop trying to grab the lock |
409 |
deadline_str = None |
|
1957.1.7
by John Arbash Meinel
Add the ability to report if the lock changes from underneath you |
410 |
last_info = None |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
411 |
while True: |
412 |
try: |
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
413 |
return self.attempt_lock() |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
414 |
except LockContention: |
415 |
pass
|
|
|
1957.1.7
by John Arbash Meinel
Add the ability to report if the lock changes from underneath you |
416 |
new_info = self.peek() |
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
417 |
self._trace('last_info: %s, new info: %s', last_info, new_info) |
|
1957.1.7
by John Arbash Meinel
Add the ability to report if the lock changes from underneath you |
418 |
if new_info is not None and new_info != last_info: |
|
1957.1.9
by John Arbash Meinel
Change default timeouts, and report differently the first failure |
419 |
if last_info is None: |
420 |
start = 'Unable to obtain' |
|
421 |
else: |
|
422 |
start = 'Lock owner changed for' |
|
|
1957.1.7
by John Arbash Meinel
Add the ability to report if the lock changes from underneath you |
423 |
last_info = new_info |
424 |
formatted_info = self._format_lock_info(new_info) |
|
|
1957.1.13
by John Arbash Meinel
Change to reporting the time when we will stop trying to grab the lock |
425 |
if deadline_str is None: |
426 |
deadline_str = time.strftime('%H:%M:%S', |
|
427 |
time.localtime(deadline)) |
|
|
1957.1.9
by John Arbash Meinel
Change default timeouts, and report differently the first failure |
428 |
self._report_function('%s %s\n' |
|
1957.1.7
by John Arbash Meinel
Add the ability to report if the lock changes from underneath you |
429 |
'%s\n' # held by |
430 |
'%s\n' # locked ... ago |
|
|
1957.1.13
by John Arbash Meinel
Change to reporting the time when we will stop trying to grab the lock |
431 |
'Will continue to try until %s\n', |
|
1957.1.9
by John Arbash Meinel
Change default timeouts, and report differently the first failure |
432 |
start, |
|
1957.1.7
by John Arbash Meinel
Add the ability to report if the lock changes from underneath you |
433 |
formatted_info[0], |
434 |
formatted_info[1], |
|
435 |
formatted_info[2], |
|
|
1957.1.13
by John Arbash Meinel
Change to reporting the time when we will stop trying to grab the lock |
436 |
deadline_str) |
|
1957.1.1
by John Arbash Meinel
Report to the user when we are spinning on a lock |
437 |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
438 |
if time.time() + poll < deadline: |
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
439 |
self._trace("waiting %ss", poll) |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
440 |
time.sleep(poll) |
441 |
else: |
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
442 |
self._trace("timeout after waiting %ss", timeout) |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
443 |
raise LockContention(self) |
|
2018.5.75
by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place. |
444 |
|
445 |
def leave_in_place(self): |
|
446 |
self._locked_via_token = True |
|
447 |
||
448 |
def dont_leave_in_place(self): |
|
449 |
self._locked_via_token = False |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
450 |
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
451 |
def lock_write(self, token=None): |
452 |
"""Wait for and acquire the lock. |
|
453 |
|
|
454 |
:param token: if this is already locked, then lock_write will fail
|
|
455 |
unless the token matches the existing lock.
|
|
456 |
:returns: a token if this instance supports tokens, otherwise None.
|
|
457 |
:raises TokenLockingNotSupported: when a token is given but this
|
|
458 |
instance doesn't support using token locks.
|
|
|
2279.7.7
by Andrew Bennetts
LockDir, Repository and Branch lock token changes from the hpss branch. |
459 |
:raises MismatchedToken: if the specified token doesn't match the token
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
460 |
of the existing lock.
|
|
2018.5.145
by Andrew Bennetts
Add a brief explanation of what tokens are used for to lock_write docstrings. |
461 |
|
462 |
A token should be passed in if you know that you have locked the object
|
|
463 |
some other way, and need to synchronise this object's state with that
|
|
464 |
fact.
|
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
465 |
|
466 |
XXX: docstring duplicated from LockableFiles.lock_write.
|
|
467 |
"""
|
|
468 |
if token is not None: |
|
469 |
self.validate_token(token) |
|
|
2018.5.75
by Andrew Bennetts
Add Repository.{dont_,}leave_lock_in_place. |
470 |
self.nonce = token |
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
471 |
self._lock_held = True |
472 |
self._locked_via_token = True |
|
|
2018.5.78
by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the |
473 |
return token |
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
474 |
else: |
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
475 |
return self.wait_lock() |
|
1553.5.44
by Martin Pool
LockableFiles can now call LockDir directly |
476 |
|
477 |
def lock_read(self): |
|
|
1759.2.1
by Jelmer Vernooij
Fix some types (found using aspell). |
478 |
"""Compatibility-mode shared lock. |
|
1553.5.44
by Martin Pool
LockableFiles can now call LockDir directly |
479 |
|
480 |
LockDir doesn't support shared read-only locks, so this
|
|
|
1553.5.54
by Martin Pool
Add LockDir.read_lock fake method |
481 |
just pretends that the lock is taken but really does nothing.
|
|
1553.5.44
by Martin Pool
LockableFiles can now call LockDir directly |
482 |
"""
|
483 |
# At the moment Branches are commonly locked for read, but
|
|
484 |
# we can't rely on that remotely. Once this is cleaned up,
|
|
485 |
# reenable this warning to prevent it coming back in
|
|
486 |
# -- mbp 20060303
|
|
487 |
## warn("LockDir.lock_read falls back to write lock")
|
|
|
1553.5.54
by Martin Pool
Add LockDir.read_lock fake method |
488 |
if self._lock_held or self._fake_read_lock: |
489 |
raise LockContention(self) |
|
490 |
self._fake_read_lock = True |
|
|
1553.5.44
by Martin Pool
LockableFiles can now call LockDir directly |
491 |
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
492 |
def wait(self, timeout=20, poll=0.5): |
|
1553.5.33
by Martin Pool
LockDir review comment fixes |
493 |
"""Wait a certain period for a lock to be released.""" |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
494 |
# XXX: the transport interface doesn't let us guard
|
495 |
# against operations there taking a long time.
|
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
496 |
#
|
497 |
# XXX: Is this really needed? Do people want to wait for the lock but
|
|
498 |
# not acquire it? As of bzr 0.17, this seems to only be called from
|
|
499 |
# the test suite.
|
|
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
500 |
deadline = time.time() + timeout |
501 |
while True: |
|
502 |
if self.peek(): |
|
503 |
return
|
|
504 |
if time.time() + poll < deadline: |
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
505 |
self._trace("waiting %ss", poll) |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
506 |
time.sleep(poll) |
507 |
else: |
|
|
2555.3.5
by Martin Pool
Return token directly from LockDir.acquire to avoid unnecessary peek() |
508 |
self._trace("temeout after waiting %ss", timeout) |
|
1553.5.12
by Martin Pool
New LockDir locking mechanism |
509 |
raise LockContention(self) |
|
1553.5.25
by Martin Pool
New LockDir.force_break and simple test case |
510 |
|
|
1957.1.5
by John Arbash Meinel
Create a helper function for formatting lock information |
511 |
def _format_lock_info(self, info): |
512 |
"""Turn the contents of peek() into something for the user""" |
|
513 |
lock_url = self.transport.abspath(self.path) |
|
514 |
delta = time.time() - int(info['start_time']) |
|
515 |
return [ |
|
516 |
'lock %s' % (lock_url,), |
|
517 |
'held by %(user)s on host %(hostname)s [process #%(pid)s]' % info, |
|
518 |
'locked %s' % (format_delta(delta),), |
|
519 |
]
|
|
520 |
||
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
521 |
def validate_token(self, token): |
522 |
if token is not None: |
|
523 |
info = self.peek() |
|
524 |
if info is None: |
|
525 |
# Lock isn't held
|
|
526 |
lock_token = None |
|
527 |
else: |
|
528 |
lock_token = info.get('nonce') |
|
529 |
if token != lock_token: |
|
530 |
raise errors.TokenMismatch(token, lock_token) |
|
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
531 |
else: |
532 |
self._trace("Revalidated by token %r", token) |
|
|
2279.7.1
by Andrew Bennetts
``LockableFiles.lock_write()`` now accepts a ``token`` keyword argument, so that |
533 |
|
|
2555.3.3
by Martin Pool
Simple lock tracing in LockDir |
534 |
def _trace(self, format, *args): |
535 |
if 'lock' not in debug.debug_flags: |
|
536 |
return
|
|
537 |
mutter(str(self) + ": " + (format % args)) |