~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lock.py

  • Committer: Martin Pool
  • Date: 2005-05-30 01:39:13 UTC
  • Revision ID: mbp@sourcefrog.net-20050530013913-4ac43c29e1302170
- make sure any bzr output is flushed before 
  running external diff

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2005 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
"""Locking using OS file locks or file existence.
 
18
"""Locking wrappers.
19
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.
 
20
This only does local locking using OS locks for now.
23
21
 
24
22
This module causes two methods, lock() and unlock() to be defined in
25
23
any way that works on the current platform.
26
24
 
27
25
It is not specified whether these locks are reentrant (i.e. can be
28
26
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
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
 
 
 
27
different threads in a single process.  
 
28
 
 
29
Eventually we may need to use some kind of lock representation that
 
30
will work on a dumb filesystem without actual locking primitives."""
 
31
 
 
32
 
 
33
import sys, os
 
34
 
 
35
import bzrlib
 
36
from trace import mutter, note, warning
 
37
 
 
38
class LockError(Exception):
 
39
    """All exceptions from the lock/unlock functions should be from this exception class.
 
40
    They will be translated as necessary. The original exception is available as e.original_error
 
41
    """
 
42
    def __init__(self, e=None):
 
43
        self.original_error = e
 
44
        if e:
 
45
            Exception.__init__(self, e)
 
46
        else:
 
47
            Exception.__init__(self)
75
48
 
76
49
try:
77
50
    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, 'wb')
100
 
            try:
101
 
                self.filename = realpath(filename)
102
 
                if self.filename in self.open_locks:
103
 
                    self._clear_f() 
104
 
                    raise LockError("Lock already held.")
105
 
                # reserve a slot for this lock - even if the lockf call fails, 
106
 
                # at thisi point unlock() will be called, because self.f is set.
107
 
                # TODO: make this fully threadsafe, if we decide we care.
108
 
                self.open_locks[self.filename] = self.filename
109
 
                fcntl.lockf(self.f, fcntl.LOCK_EX)
110
 
            except IOError, e:
111
 
                # we should be more precise about whats a locking
112
 
                # error and whats a random-other error
113
 
                raise LockError(e)
114
 
 
115
 
        def unlock(self):
116
 
            del self.open_locks[self.filename]
117
 
            self._unlock()
118
 
 
119
 
 
120
 
    class _fcntl_ReadLock(_fcntl_FileLock):
121
 
 
122
 
        def __init__(self, filename):
123
 
            # standard IO errors get exposed directly.
124
 
            self._open(filename, 'rb')
125
 
            try:
126
 
                fcntl.lockf(self.f, fcntl.LOCK_SH)
127
 
            except IOError, e:
128
 
                # we should be more precise about whats a locking
129
 
                # error and whats a random-other error
130
 
                raise LockError(e)
131
 
 
132
 
        def unlock(self):
133
 
            self._unlock()
134
 
 
135
 
 
136
 
    WriteLock = _fcntl_WriteLock
137
 
    ReadLock = _fcntl_ReadLock
138
 
 
 
51
    LOCK_SH = fcntl.LOCK_SH
 
52
    LOCK_EX = fcntl.LOCK_EX
 
53
    LOCK_NB = fcntl.LOCK_NB
 
54
    def lock(f, flags):
 
55
        try:
 
56
            fcntl.flock(f, flags)
 
57
        except Exception, e:
 
58
            raise LockError(e)
 
59
 
 
60
    def unlock(f):
 
61
        try:
 
62
            fcntl.flock(f, fcntl.LOCK_UN)
 
63
        except Exception, e:
 
64
            raise LockError(e)
139
65
 
140
66
except ImportError:
141
67
    try:
142
68
        import win32con, win32file, pywintypes
143
 
 
144
 
 
145
69
        LOCK_SH = 0 # the default
146
70
        LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
147
71
        LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
148
72
 
149
 
        class _w32c_FileLock(_base_Lock):
150
 
            def _lock(self, filename, openmode, lockmode):
151
 
                try:
152
 
                    self._open(filename, openmode)
153
 
                    self.hfile = win32file._get_osfhandle(self.f.fileno())
154
 
                    overlapped = pywintypes.OVERLAPPED()
155
 
                    win32file.LockFileEx(self.hfile, lockmode, 0, 0x7fff0000, overlapped)
156
 
                except Exception, e:
157
 
                    if self.f:
158
 
                        self.f.close()
159
 
                        self.f = None
160
 
                    raise LockError(e)
161
 
 
162
 
            def unlock(self):
163
 
                try:
164
 
                    overlapped = pywintypes.OVERLAPPED()
165
 
                    win32file.UnlockFileEx(self.hfile, 0, 0x7fff0000, overlapped)
166
 
                    self.f.close()
167
 
                    self.f = None
168
 
                except Exception, e:
169
 
                    raise LockError(e)
170
 
 
171
 
 
172
 
        class _w32c_ReadLock(_w32c_FileLock):
173
 
            def __init__(self, filename):
174
 
                _w32c_FileLock._lock(self, filename, 'rb',
175
 
                                     LOCK_NB)
176
 
 
177
 
        class _w32c_WriteLock(_w32c_FileLock):
178
 
            def __init__(self, filename):
179
 
                _w32c_FileLock._lock(self, filename, 'wb',
180
 
                                     LOCK_EX + LOCK_NB)
181
 
 
182
 
 
183
 
        WriteLock = _w32c_WriteLock
184
 
        ReadLock = _w32c_ReadLock
185
 
 
 
73
        def lock(f, flags):
 
74
            try:
 
75
                if type(f) == file:
 
76
                    hfile = win32file._get_osfhandle(f.fileno())
 
77
                else:
 
78
                    hfile = win32file._get_osfhandle(f)
 
79
                overlapped = pywintypes.OVERLAPPED()
 
80
                win32file.LockFileEx(hfile, flags, 0, 0x7fff0000, overlapped)
 
81
            except Exception, e:
 
82
                raise LockError(e)
 
83
 
 
84
        def unlock(f):
 
85
            try:
 
86
                if type(f) == file:
 
87
                    hfile = win32file._get_osfhandle(f.fileno())
 
88
                else:
 
89
                    hfile = win32file._get_osfhandle(f)
 
90
                overlapped = pywintypes.OVERLAPPED()
 
91
                win32file.UnlockFileEx(hfile, 0, 0x7fff0000, overlapped)
 
92
            except Exception, e:
 
93
                raise LockError(e)
186
94
    except ImportError:
187
95
        try:
188
96
            import msvcrt
189
 
 
190
 
 
191
97
            # Unfortunately, msvcrt.locking() doesn't distinguish between
192
98
            # read locks and write locks. Also, the way the combinations
193
99
            # work to get non-blocking is not the same, so we
194
100
            # have to write extra special functions here.
195
101
 
196
 
 
197
 
            class _msvc_FileLock(_base_Lock):
198
 
                LOCK_SH = 1
199
 
                LOCK_EX = 2
200
 
                LOCK_NB = 4
201
 
                def unlock(self):
202
 
                    _msvc_unlock(self.f)
203
 
                    self.f.close()
204
 
                    self.f = None
205
 
 
206
 
 
207
 
            class _msvc_ReadLock(_msvc_FileLock):
208
 
                def __init__(self, filename):
209
 
                    _msvc_lock(self._open(filename, 'rb'), self.LOCK_SH)
210
 
 
211
 
 
212
 
            class _msvc_WriteLock(_msvc_FileLock):
213
 
                def __init__(self, filename):
214
 
                    _msvc_lock(self._open(filename, 'wb'), self.LOCK_EX)
215
 
 
216
 
 
217
 
            def _msvc_lock(f, flags):
 
102
            LOCK_SH = 1
 
103
            LOCK_EX = 2
 
104
            LOCK_NB = 4
 
105
 
 
106
            def lock(f, flags):
218
107
                try:
219
108
                    # Unfortunately, msvcrt.LK_RLCK is equivalent to msvcrt.LK_LOCK
220
109
                    # according to the comments, LK_RLCK is open the lock for writing.
230
119
                        fn = f
231
120
                        fpos = os.lseek(fn, 0,0)
232
121
                        os.lseek(fn, 0,0)
233
 
 
234
 
                    if flags & _msvc_FileLock.LOCK_SH:
235
 
                        if flags & _msvc_FileLock.LOCK_NB:
 
122
                    
 
123
                    if flags & LOCK_SH:
 
124
                        if flags & LOCK_NB:
236
125
                            lock_mode = msvcrt.LK_NBLCK
237
126
                        else:
238
127
                            lock_mode = msvcrt.LK_LOCK
239
 
                    elif flags & _msvc_FileLock.LOCK_EX:
240
 
                        if flags & _msvc_FileLock.LOCK_NB:
 
128
                    elif flags & LOCK_EX:
 
129
                        if flags & LOCK_NB:
241
130
                            lock_mode = msvcrt.LK_NBRLCK
242
131
                        else:
243
132
                            lock_mode = msvcrt.LK_RLCK
250
139
                except Exception, e:
251
140
                    raise LockError(e)
252
141
 
253
 
            def _msvc_unlock(f):
 
142
            def unlock(f):
254
143
                try:
255
144
                    if type(f) == file:
256
145
                        fpos = f.tell()
267
156
                        os.lseek(fn, fpos, 0)
268
157
                except Exception, e:
269
158
                    raise LockError(e)
270
 
 
271
 
 
272
 
            WriteLock = _msvc_WriteLock
273
 
            ReadLock = _msvc_ReadLock
274
159
        except ImportError:
275
 
            raise NotImplementedError("please write a locking method "
276
 
                                      "for platform %r" % sys.platform)
 
160
            from warnings import Warning
 
161
            
 
162
            warning("please write a locking method for platform %r" % sys.platform)
 
163
 
 
164
            # Creating no-op lock/unlock for now
 
165
            def lock(f, flags):
 
166
                pass
 
167
            def unlock(f):
 
168
                pass
 
169