~bzr-pqm/bzr/bzr.dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


"""Locking using OS file locks or file existence.

Note: This method of locking is generally deprecated in favour of LockDir, but
is used to lock local WorkingTrees, and by some old formats.  It's accessed
through Transport.lock_read(), etc.

This module causes two methods, lock() and unlock() to be defined in
any way that works on the current platform.

It is not specified whether these locks are reentrant (i.e. can be
taken repeatedly by a single process) or whether they exclude
different threads in a single process.  That reentrancy is provided by
LockableFiles.

This defines two classes: ReadLock and WriteLock, which can be
implemented in different ways on different platforms.  Both have an
unlock() method.
"""

import errno
import os
import sys

from bzrlib import errors
from bzrlib.errors import LockError, LockContention
from bzrlib.osutils import realpath
from bzrlib.trace import mutter


class _base_Lock(object):

    def __init__(self):
        self.f = None

    def _open(self, filename, filemode):
        try:
            self.f = open(filename, filemode)
            return self.f
        except IOError, e:
            if e.errno in (errno.EACCES, errno.EPERM):
                raise errors.ReadOnlyLockError(e)
            if e.errno != errno.ENOENT:
                raise

            # maybe this is an old branch (before may 2005)
            mutter("trying to create missing branch lock %r", filename)

            self.f = open(filename, 'wb+')
            return self.f

    def _clear_f(self):
        """Clear the self.f attribute cleanly."""
        if self.f:
            self.f.close()
            self.f = None

    def __del__(self):
        if self.f:
            from warnings import warn
            warn("lock on %r not released" % self.f)
            self.unlock()

    def unlock(self):
        raise NotImplementedError()


have_ctypes = have_pywin32 = have_fcntl = False
try:
    import fcntl
    have_fcntl = True
except ImportError:
    have_fcntl = False
try:
    import win32con, win32file, pywintypes, winerror, msvcrt
    have_pywin32 = True
except ImportError:
    have_pywin32 = False
try:
    import ctypes, msvcrt
    have_ctypes = True
except ImportError:
    have_ctypes = False


_lock_classes = []


if have_fcntl:
    LOCK_SH = fcntl.LOCK_SH
    LOCK_NB = fcntl.LOCK_NB
    lock_EX = fcntl.LOCK_EX


    class _fcntl_FileLock(_base_Lock):

        def _unlock(self):
            fcntl.lockf(self.f, fcntl.LOCK_UN)
            self._clear_f()


    class _fcntl_WriteLock(_fcntl_FileLock):

        open_locks = {}

        def __init__(self, filename):
            # standard IO errors get exposed directly.
            super(_fcntl_WriteLock, self).__init__()
            self._open(filename, 'rb+')
            self.filename = realpath(filename)
            if self.filename in self.open_locks:
                self._clear_f()
                raise LockContention(self.filename)
            # reserve a slot for this lock - even if the lockf call fails,
            # at thisi point unlock() will be called, because self.f is set.
            # TODO: make this fully threadsafe, if we decide we care.
            self.open_locks[self.filename] = self.filename
            try:
                # LOCK_NB will cause IOError to be raised if we can't grab a
                # lock right away.
                fcntl.lockf(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError, e:
                if e.errno in (errno.EAGAIN, errno.EACCES):
                    # We couldn't grab the lock
                    self.unlock()
                # we should be more precise about whats a locking
                # error and whats a random-other error
                raise LockError(e)

        def unlock(self):
            del self.open_locks[self.filename]
            self._unlock()


    class _fcntl_ReadLock(_fcntl_FileLock):

        open_locks = {}

        def __init__(self, filename):
            super(_fcntl_ReadLock, self).__init__()
            self._open(filename, 'rb')
            try:
                # LOCK_NB will cause IOError to be raised if we can't grab a
                # lock right away.
                fcntl.lockf(self.f, fcntl.LOCK_SH | fcntl.LOCK_NB)
            except IOError, e:
                # we should be more precise about whats a locking
                # error and whats a random-other error
                raise LockError(e)

        def unlock(self):
            self._unlock()


    _lock_classes.append(('fcntl', _fcntl_WriteLock, _fcntl_ReadLock))

if have_pywin32:
    LOCK_SH = 0 # the default
    LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
    LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY


    class _w32c_FileLock(_base_Lock):

        def _lock(self, filename, openmode, lockmode):
            self._open(filename, openmode)

            self.hfile = msvcrt.get_osfhandle(self.f.fileno())
            overlapped = pywintypes.OVERLAPPED()
            try:
                win32file.LockFileEx(self.hfile, lockmode, 0, 0x7fff0000,
                                     overlapped)
            except pywintypes.error, e:
                self._clear_f()
                if e.args[0] in (winerror.ERROR_LOCK_VIOLATION,):
                    raise errors.LockContention(filename)
                ## import pdb; pdb.set_trace()
                raise
            except Exception, e:
                self._clear_f()
                raise LockError(e)

        def unlock(self):
            overlapped = pywintypes.OVERLAPPED()
            try:
                win32file.UnlockFileEx(self.hfile, 0, 0x7fff0000, overlapped)
                self._clear_f()
            except Exception, e:
                raise LockError(e)


    class _w32c_ReadLock(_w32c_FileLock):
        def __init__(self, filename):
            super(_w32c_ReadLock, self).__init__()
            self._lock(filename, 'rb', LOCK_SH + LOCK_NB)

    class _w32c_WriteLock(_w32c_FileLock):
        def __init__(self, filename):
            super(_w32c_WriteLock, self).__init__()
            self._lock(filename, 'rb+', LOCK_EX + LOCK_NB)

    _lock_classes.append(('pywin32', _w32c_WriteLock, _w32c_ReadLock))

if have_ctypes:
    # These constants were copied from the win32con.py module.
    LOCKFILE_FAIL_IMMEDIATELY = 1
    LOCKFILE_EXCLUSIVE_LOCK = 2
    # Constant taken from winerror.py module
    ERROR_LOCK_VIOLATION = 33

    LOCK_SH = 0
    LOCK_EX = LOCKFILE_EXCLUSIVE_LOCK
    LOCK_NB = LOCKFILE_FAIL_IMMEDIATELY
    _LockFileEx = ctypes.windll.kernel32.LockFileEx
    _UnlockFileEx = ctypes.windll.kernel32.UnlockFileEx
    _GetLastError = ctypes.windll.kernel32.GetLastError

    ### Define the OVERLAPPED structure.
    #   http://msdn2.microsoft.com/en-us/library/ms684342.aspx
    # typedef struct _OVERLAPPED {
    #   ULONG_PTR Internal;
    #   ULONG_PTR InternalHigh;
    #   union {
    #     struct {
    #       DWORD Offset;
    #       DWORD OffsetHigh;
    #     };
    #     PVOID Pointer;
    #   };
    #   HANDLE hEvent;
    # } OVERLAPPED,

    class _inner_struct(ctypes.Structure):
        _fields_ = [('Offset', ctypes.c_uint), # DWORD
                    ('OffsetHigh', ctypes.c_uint), # DWORD
                   ]

    class _inner_union(ctypes.Union):
        _fields_  = [('anon_struct', _inner_struct), # struct
                     ('Pointer', ctypes.c_void_p), # PVOID
                    ]

    class OVERLAPPED(ctypes.Structure):
        _fields_ = [('Internal', ctypes.c_void_p), # ULONG_PTR
                    ('InternalHigh', ctypes.c_void_p), # ULONG_PTR
                    ('_inner_union', _inner_union),
                    ('hEvent', ctypes.c_void_p), # HANDLE
                   ]

    class _ctypes_FileLock(_base_Lock):

        def _lock(self, filename, openmode, lockmode):
            self._open(filename, openmode)

            self.hfile = msvcrt.get_osfhandle(self.f.fileno())
            overlapped = OVERLAPPED()
            p_overlapped = ctypes.pointer(overlapped)
            result = _LockFileEx(self.hfile, # HANDLE hFile
                                 lockmode,   # DWORD dwFlags
                                 0,          # DWORD dwReserved
                                 0x7fffffff, # DWORD nNumberOfBytesToLockLow
                                 0x00000000, # DWORD nNumberOfBytesToLockHigh
                                 p_overlapped, # lpOverlapped
                                )
            if result == 0:
                self._clear_f()
                last_err = _GetLastError()
                if last_err in (ERROR_LOCK_VIOLATION,):
                    raise errors.LockContention(filename)
                raise errors.LockError('Unknown locking error: %s'
                                       % (last_err,))

        def unlock(self):
            overlapped = OVERLAPPED()
            p_overlapped = ctypes.pointer(overlapped)
            result = _UnlockFileEx(self.hfile, # HANDLE hFile
                                   0,          # DWORD dwReserved
                                   0x7fffffff, # DWORD nNumberOfBytesToLockLow
                                   0x00000000, # DWORD nNumberOfBytesToLockHigh
                                   p_overlapped, # lpOverlapped
                                  )
            self._clear_f()
            if result == 0:
                self._clear_f()
                last_err = _GetLastError()
                raise errors.LockError('Unknown unlocking error: %s'
                                       % (last_err,))


    class _ctypes_ReadLock(_ctypes_FileLock):
        def __init__(self, filename):
            super(_ctypes_ReadLock, self).__init__()
            self._lock(filename, 'rb', LOCK_SH + LOCK_NB)

    class _ctypes_WriteLock(_ctypes_FileLock):
        def __init__(self, filename):
            super(_ctypes_WriteLock, self).__init__()
            self._lock(filename, 'rb+', LOCK_EX + LOCK_NB)

    _lock_classes.append(('ctypes', _ctypes_WriteLock, _ctypes_ReadLock))


if len(_lock_classes) == 0:
    raise NotImplementedError("We only have support for"
                              " fcntl, pywin32 or ctypes locking."
                              " If your platform (windows) does not"
                              " support fcntl locks, you must have"
                              " either pywin32 or ctypes installed.")

# We default to using the first available lock class.
_lock_type, WriteLock, ReadLock = _lock_classes[0]


class LockTreeTestProviderAdapter(object):
    """A tool to generate a suite testing multiple lock formats at once.

    This is done by copying the test once for each lock and injecting the
    read_lock and write_lock classes.
    They are also given a new test id.
    """

    def __init__(self, lock_classes):
        self._lock_classes = lock_classes

    def _clone_test(self, test, write_lock, read_lock, variation):
        """Clone test for adaption."""
        new_test = deepcopy(test)
        new_test.write_lock = write_lock
        new_test.read_lock = read_lock
        def make_new_test_id():
            new_id = "%s(%s)" % (test.id(), variation)
            return lambda: new_id
        new_test.id = make_new_test_id()
        return new_test

    def adapt(self, test):
        from bzrlib.tests import TestSuite
        result = TestSuite()
        for name, write_lock, read_lock in self._lock_classes:
            new_test = self._clone_test(test, write_lock, read_lock, name)
            result.addTest(new_test)
        return result