~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
# Copyright (C) 2005 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 wrappers.

This only does local locking using OS locks for now.

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.  

Eventually we may need to use some kind of lock representation that
will work on a dumb filesystem without actual locking primitives."""


import sys, os

import bzrlib
from trace import mutter, note, warning

class LockError(Exception):
    """All exceptions from the lock/unlock functions should be from this exception class.
    They will be translated as necessary. The original exception is available as e.original_error
    """
    def __init__(self, e=None):
        self.original_error = e
        if e:
            Exception.__init__(self, e)
        else:
            Exception.__init__(self)

try:
    import fcntl
    LOCK_SH = fcntl.LOCK_SH
    LOCK_EX = fcntl.LOCK_EX
    LOCK_NB = fcntl.LOCK_NB
    def lock(f, flags):
        try:
            fcntl.flock(f, flags)
        except Exception, e:
            raise LockError(e)

    def unlock(f):
        try:
            fcntl.flock(f, fcntl.LOCK_UN)
        except Exception, e:
            raise LockError(e)

except ImportError:
    try:
        import win32con, win32file, pywintypes
        LOCK_SH = 0 # the default
        LOCK_EX = win32con.LOCKFILE_EXCLUSIVE_LOCK
        LOCK_NB = win32con.LOCKFILE_FAIL_IMMEDIATELY

        def lock(f, flags):
            try:
                if type(f) == file:
                    hfile = win32file._get_osfhandle(f.fileno())
                else:
                    hfile = win32file._get_osfhandle(f)
                overlapped = pywintypes.OVERLAPPED()
                win32file.LockFileEx(hfile, flags, 0, 0x7fff0000, overlapped)
            except Exception, e:
                raise LockError(e)

        def unlock(f):
            try:
                if type(f) == file:
                    hfile = win32file._get_osfhandle(f.fileno())
                else:
                    hfile = win32file._get_osfhandle(f)
                overlapped = pywintypes.OVERLAPPED()
                win32file.UnlockFileEx(hfile, 0, 0x7fff0000, overlapped)
            except Exception, e:
                raise LockError(e)
    except ImportError:
        try:
            import msvcrt
            # Unfortunately, msvcrt.locking() doesn't distinguish between
            # read locks and write locks. Also, the way the combinations
            # work to get non-blocking is not the same, so we
            # have to write extra special functions here.

            LOCK_SH = 1
            LOCK_EX = 2
            LOCK_NB = 4

            def lock(f, flags):
                try:
                    # Unfortunately, msvcrt.LK_RLCK is equivalent to msvcrt.LK_LOCK
                    # according to the comments, LK_RLCK is open the lock for writing.

                    # Unfortunately, msvcrt.locking() also has the side effect that it
                    # will only block for 10 seconds at most, and then it will throw an
                    # exception, this isn't terrible, though.
                    if type(f) == file:
                        fpos = f.tell()
                        fn = f.fileno()
                        f.seek(0)
                    else:
                        fn = f
                        fpos = os.lseek(fn, 0,0)
                        os.lseek(fn, 0,0)
                    
                    if flags & LOCK_SH:
                        if flags & LOCK_NB:
                            lock_mode = msvcrt.LK_NBLCK
                        else:
                            lock_mode = msvcrt.LK_LOCK
                    elif flags & LOCK_EX:
                        if flags & LOCK_NB:
                            lock_mode = msvcrt.LK_NBRLCK
                        else:
                            lock_mode = msvcrt.LK_RLCK
                    else:
                        raise ValueError('Invalid lock mode: %r' % flags)
                    try:
                        msvcrt.locking(fn, lock_mode, -1)
                    finally:
                        os.lseek(fn, fpos, 0)
                except Exception, e:
                    raise LockError(e)

            def unlock(f):
                try:
                    if type(f) == file:
                        fpos = f.tell()
                        fn = f.fileno()
                        f.seek(0)
                    else:
                        fn = f
                        fpos = os.lseek(fn, 0,0)
                        os.lseek(fn, 0,0)

                    try:
                        msvcrt.locking(fn, msvcrt.LK_UNLCK, -1)
                    finally:
                        os.lseek(fn, fpos, 0)
                except Exception, e:
                    raise LockError(e)
        except ImportError:
            from warnings import Warning
            
            warning("please write a locking method for platform %r" % sys.platform)

            # Creating no-op lock/unlock for now
            def lock(f, flags):
                pass
            def unlock(f):
                pass