~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lock.py

  • Committer: Robert Collins
  • Date: 2007-03-05 03:10:21 UTC
  • mto: (2255.11.4 dirstate)
  • mto: This revision was merged to the branch mainline in revision 2322.
  • Revision ID: robertc@robertcollins.net-20070305031021-ypbakvagbivyw5mu
Teach delta.report_changes about unversioned files, removing all inventory access during status --short.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
 
17
 
 
18
"""Locking using OS file locks or file existence.
 
19
 
 
20
Note: This method of locking is generally deprecated in favour of LockDir, but
 
21
is used to lock local WorkingTrees, and by some old formats.  It's accessed
 
22
through Transport.lock_read(), etc.
 
23
 
 
24
This module causes two methods, lock() and unlock() to be defined in
 
25
any way that works on the current platform.
 
26
 
 
27
It is not specified whether these locks are reentrant (i.e. can be
 
28
taken repeatedly by a single process) or whether they exclude
 
29
different threads in a single process.  That reentrancy is provided by 
 
30
LockableFiles.
 
31
 
 
32
This defines two classes: ReadLock and WriteLock, which can be
 
33
implemented in different ways on different platforms.  Both have an
 
34
unlock() method.
 
35
"""
 
36
 
 
37
import errno
 
38
import os
 
39
import sys
 
40
 
 
41
from bzrlib.errors import LockError, LockContention
 
42
from bzrlib.osutils import realpath
 
43
from bzrlib.trace import mutter
 
44
 
 
45
 
 
46
class _base_Lock(object):
 
47
 
 
48
    def _open(self, filename, filemode):
 
49
        try:
 
50
            self.f = open(filename, filemode)
 
51
            return self.f
 
52
        except IOError, e:
 
53
            if e.errno != errno.ENOENT:
 
54
                raise
 
55
 
 
56
            # maybe this is an old branch (before may 2005)
 
57
            mutter("trying to create missing branch lock %r", filename)
 
58
            
 
59
            self.f = open(filename, 'wb+')
 
60
            return self.f
 
61
 
 
62
    def __del__(self):
 
63
        if self.f:
 
64
            from warnings import warn
 
65
            warn("lock on %r not released" % self.f)
 
66
            self.unlock()
 
67
            
 
68
    def unlock(self):
 
69
        raise NotImplementedError()
 
70
 
 
71
 
 
72
############################################################
 
73
# msvcrt locks
 
74
 
 
75
 
 
76
try:
 
77
    import fcntl
 
78
 
 
79
    class _fcntl_FileLock(_base_Lock):
 
80
 
 
81
        f = None
 
82
 
 
83
        def _unlock(self):
 
84
            fcntl.lockf(self.f, fcntl.LOCK_UN)
 
85
            self._clear_f()
 
86
 
 
87
        def _clear_f(self):
 
88
            """Clear the self.f attribute cleanly."""
 
89
            self.f.close()
 
90
            del self.f
 
91
 
 
92
 
 
93
    class _fcntl_WriteLock(_fcntl_FileLock):
 
94
 
 
95
        open_locks = {}
 
96
 
 
97
        def __init__(self, filename):
 
98
            # standard IO errors get exposed directly.
 
99
            self._open(filename, 'rb+')
 
100
            self.filename = realpath(filename)
 
101
            if self.filename in self.open_locks:
 
102
                self._clear_f()
 
103
                raise LockContention("Lock already held.")
 
104
            # reserve a slot for this lock - even if the lockf call fails,
 
105
            # at thisi point unlock() will be called, because self.f is set.
 
106
            # TODO: make this fully threadsafe, if we decide we care.
 
107
            self.open_locks[self.filename] = self.filename
 
108
            try:
 
109
                # LOCK_NB will cause IOError to be raised if we can't grab a
 
110
                # lock right away.
 
111
                fcntl.lockf(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB)
 
112
            except IOError, e:
 
113
                if e.errno in (errno.EAGAIN, errno.EACCES):
 
114
                    # We couldn't grab the lock
 
115
                    self.unlock()
 
116
                # we should be more precise about whats a locking
 
117
                # error and whats a random-other error
 
118
                raise LockError(e)
 
119
 
 
120
        def unlock(self):
 
121
            del self.open_locks[self.filename]
 
122
            self._unlock()
 
123
 
 
124
 
 
125
    class _fcntl_ReadLock(_fcntl_FileLock):
 
126
 
 
127
        def __init__(self, filename):
 
128
            # standard IO errors get exposed directly.
 
129
            self._open(filename, 'rb')
 
130
            try:
 
131
                # LOCK_NB will cause IOError to be raised if we can't grab a
 
132
                # lock right away.
 
133
                fcntl.lockf(self.f, fcntl.LOCK_SH | fcntl.LOCK_NB)
 
134
            except IOError, e:
 
135
                # we should be more precise about whats a locking
 
136
                # error and whats a random-other error
 
137
                raise LockError(e)
 
138
 
 
139
        def unlock(self):
 
140
            self._unlock()
 
141
 
 
142
 
 
143
    WriteLock = _fcntl_WriteLock
 
144
    ReadLock = _fcntl_ReadLock
 
145
 
 
146
 
 
147
except ImportError:
 
148
    try:
 
149
        import win32con, win32file, pywintypes
 
150
 
 
151
 
 
152
        LOCK_SH = 0 # the default
 
153
        LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
 
154
        LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
 
155
 
 
156
        class _w32c_FileLock(_base_Lock):
 
157
            def _lock(self, filename, openmode, lockmode):
 
158
                try:
 
159
                    self._open(filename, openmode)
 
160
                    self.hfile = win32file._get_osfhandle(self.f.fileno())
 
161
                    overlapped = pywintypes.OVERLAPPED()
 
162
                    win32file.LockFileEx(self.hfile, lockmode, 0, 0x7fff0000, overlapped)
 
163
                except Exception, e:
 
164
                    if self.f:
 
165
                        self.f.close()
 
166
                        self.f = None
 
167
                    raise LockError(e)
 
168
 
 
169
            def unlock(self):
 
170
                try:
 
171
                    overlapped = pywintypes.OVERLAPPED()
 
172
                    win32file.UnlockFileEx(self.hfile, 0, 0x7fff0000, overlapped)
 
173
                    self.f.close()
 
174
                    self.f = None
 
175
                except Exception, e:
 
176
                    raise LockError(e)
 
177
 
 
178
 
 
179
        class _w32c_ReadLock(_w32c_FileLock):
 
180
            def __init__(self, filename):
 
181
                _w32c_FileLock._lock(self, filename, 'rb',
 
182
                                     LOCK_NB)
 
183
 
 
184
        class _w32c_WriteLock(_w32c_FileLock):
 
185
            def __init__(self, filename):
 
186
                _w32c_FileLock._lock(self, filename, 'rb+',
 
187
                                     LOCK_EX + LOCK_NB)
 
188
 
 
189
 
 
190
        WriteLock = _w32c_WriteLock
 
191
        ReadLock = _w32c_ReadLock
 
192
 
 
193
    except ImportError:
 
194
        try:
 
195
            import msvcrt
 
196
 
 
197
 
 
198
            # Unfortunately, msvcrt.locking() doesn't distinguish between
 
199
            # read locks and write locks. Also, the way the combinations
 
200
            # work to get non-blocking is not the same, so we
 
201
            # have to write extra special functions here.
 
202
 
 
203
 
 
204
            class _msvc_FileLock(_base_Lock):
 
205
                LOCK_SH = 1
 
206
                LOCK_EX = 2
 
207
                LOCK_NB = 4
 
208
 
 
209
                def unlock(self):
 
210
                    _msvc_unlock(self.f)
 
211
                    self.f.close()
 
212
                    self.f = None
 
213
 
 
214
 
 
215
            class _msvc_ReadLock(_msvc_FileLock):
 
216
                def __init__(self, filename):
 
217
                    _msvc_lock(self._open(filename, 'rb'),
 
218
                               self.LOCK_SH | self.LOCK_NB)
 
219
 
 
220
 
 
221
            class _msvc_WriteLock(_msvc_FileLock):
 
222
                def __init__(self, filename):
 
223
                    _msvc_lock(self._open(filename, 'rb+'),
 
224
                               self.LOCK_EX | self.LOCK_NB)
 
225
 
 
226
 
 
227
            def _msvc_lock(f, flags):
 
228
                try:
 
229
                    # Unfortunately, msvcrt.LK_RLCK is equivalent to msvcrt.LK_LOCK
 
230
                    # according to the comments, LK_RLCK is open the lock for writing.
 
231
 
 
232
                    # Unfortunately, msvcrt.locking() also has the side effect that it
 
233
                    # will only block for 10 seconds at most, and then it will throw an
 
234
                    # exception, this isn't terrible, though.
 
235
                    if type(f) == file:
 
236
                        fpos = f.tell()
 
237
                        fn = f.fileno()
 
238
                        f.seek(0)
 
239
                    else:
 
240
                        fn = f
 
241
                        fpos = os.lseek(fn, 0,0)
 
242
                        os.lseek(fn, 0,0)
 
243
 
 
244
                    if flags & _msvc_FileLock.LOCK_SH:
 
245
                        if flags & _msvc_FileLock.LOCK_NB:
 
246
                            lock_mode = msvcrt.LK_NBLCK
 
247
                        else:
 
248
                            lock_mode = msvcrt.LK_LOCK
 
249
                    elif flags & _msvc_FileLock.LOCK_EX:
 
250
                        if flags & _msvc_FileLock.LOCK_NB:
 
251
                            lock_mode = msvcrt.LK_NBRLCK
 
252
                        else:
 
253
                            lock_mode = msvcrt.LK_RLCK
 
254
                    else:
 
255
                        raise ValueError('Invalid lock mode: %r' % flags)
 
256
                    try:
 
257
                        msvcrt.locking(fn, lock_mode, -1)
 
258
                    finally:
 
259
                        os.lseek(fn, fpos, 0)
 
260
                except Exception, e:
 
261
                    raise LockError(e)
 
262
 
 
263
            def _msvc_unlock(f):
 
264
                try:
 
265
                    if type(f) == file:
 
266
                        fpos = f.tell()
 
267
                        fn = f.fileno()
 
268
                        f.seek(0)
 
269
                    else:
 
270
                        fn = f
 
271
                        fpos = os.lseek(fn, 0,0)
 
272
                        os.lseek(fn, 0,0)
 
273
 
 
274
                    try:
 
275
                        msvcrt.locking(fn, msvcrt.LK_UNLCK, -1)
 
276
                    finally:
 
277
                        os.lseek(fn, fpos, 0)
 
278
                except Exception, e:
 
279
                    raise LockError(e)
 
280
 
 
281
 
 
282
            WriteLock = _msvc_WriteLock
 
283
            ReadLock = _msvc_ReadLock
 
284
        except ImportError:
 
285
            raise NotImplementedError("please write a locking method "
 
286
                                      "for platform %r" % sys.platform)