~bzr-pqm/bzr/bzr.dev

577 by Martin Pool
- merge portable lock module from John
1
# Copyright (C) 2005 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 wrappers.
19
20
This only does local locking using OS locks for now.
21
22
This module causes two methods, lock() and unlock() to be defined in
23
any way that works on the current platform.
24
25
It is not specified whether these locks are reentrant (i.e. can be
26
taken repeatedly by a single process) or whether they exclude
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)
48
49
try:
50
    import fcntl
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)
65
66
except ImportError:
67
    try:
68
        import win32con, win32file, pywintypes
69
        LOCK_SH = 0 # the default
70
        LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
71
        LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY
72
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)
94
    except ImportError:
95
        try:
96
            import msvcrt
97
            # Unfortunately, msvcrt.locking() doesn't distinguish between
98
            # read locks and write locks. Also, the way the combinations
99
            # work to get non-blocking is not the same, so we
100
            # have to write extra special functions here.
101
102
            LOCK_SH = 1
103
            LOCK_EX = 2
104
            LOCK_NB = 4
105
106
            def lock(f, flags):
107
                try:
108
                    # Unfortunately, msvcrt.LK_RLCK is equivalent to msvcrt.LK_LOCK
109
                    # according to the comments, LK_RLCK is open the lock for writing.
110
111
                    # Unfortunately, msvcrt.locking() also has the side effect that it
112
                    # will only block for 10 seconds at most, and then it will throw an
113
                    # exception, this isn't terrible, though.
114
                    if type(f) == file:
115
                        fpos = f.tell()
116
                        fn = f.fileno()
117
                        f.seek(0)
118
                    else:
119
                        fn = f
120
                        fpos = os.lseek(fn, 0,0)
121
                        os.lseek(fn, 0,0)
122
                    
123
                    if flags & LOCK_SH:
124
                        if flags & LOCK_NB:
125
                            lock_mode = msvcrt.LK_NBLCK
126
                        else:
127
                            lock_mode = msvcrt.LK_LOCK
128
                    elif flags & LOCK_EX:
129
                        if flags & LOCK_NB:
130
                            lock_mode = msvcrt.LK_NBRLCK
131
                        else:
132
                            lock_mode = msvcrt.LK_RLCK
133
                    else:
134
                        raise ValueError('Invalid lock mode: %r' % flags)
135
                    try:
136
                        msvcrt.locking(fn, lock_mode, -1)
137
                    finally:
138
                        os.lseek(fn, fpos, 0)
139
                except Exception, e:
140
                    raise LockError(e)
141
142
            def unlock(f):
143
                try:
144
                    if type(f) == file:
145
                        fpos = f.tell()
146
                        fn = f.fileno()
147
                        f.seek(0)
148
                    else:
149
                        fn = f
150
                        fpos = os.lseek(fn, 0,0)
151
                        os.lseek(fn, 0,0)
152
153
                    try:
154
                        msvcrt.locking(fn, msvcrt.LK_UNLCK, -1)
155
                    finally:
156
                        os.lseek(fn, fpos, 0)
157
                except Exception, e:
158
                    raise LockError(e)
159
        except ImportError:
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