/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/lock.py

  • Committer: Jelmer Vernooij
  • Date: 2018-02-18 21:42:57 UTC
  • mto: This revision was merged to the branch mainline in revision 6859.
  • Revision ID: jelmer@jelmer.uk-20180218214257-jpevutp1wa30tz3v
Update TODO to reference Breezy, not Bazaar.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
 
18
17
"""Locking using OS file locks or file existence.
19
18
 
20
19
Note: This method of locking is generally deprecated in favour of LockDir, but
34
33
unlock() method.
35
34
"""
36
35
 
 
36
from __future__ import absolute_import
 
37
 
 
38
import contextlib
37
39
import errno
38
40
import os
39
41
import sys
40
42
import warnings
41
43
 
42
 
from bzrlib import (
 
44
from . import (
43
45
    debug,
44
46
    errors,
45
47
    osutils,
46
48
    trace,
47
49
    )
48
 
from bzrlib.hooks import HookPoint, Hooks
49
 
 
 
50
from .hooks import Hooks
 
51
from .i18n import gettext
50
52
 
51
53
class LockHooks(Hooks):
52
54
 
53
55
    def __init__(self):
54
 
        Hooks.__init__(self)
55
 
        self.create_hook(HookPoint('lock_acquired',
56
 
            "Called with a bzrlib.lock.LockResult when a physical lock is "
57
 
            "acquired.", (1, 8), None))
58
 
        self.create_hook(HookPoint('lock_released',
59
 
            "Called with a bzrlib.lock.LockResult when a physical lock is "
60
 
            "released.", (1, 8), None))
61
 
        self.create_hook(HookPoint('lock_broken',
62
 
            "Called with a bzrlib.lock.LockResult when a physical lock is "
63
 
            "broken.", (1, 15), None))
 
56
        Hooks.__init__(self, "breezy.lock", "Lock.hooks")
 
57
        self.add_hook('lock_acquired',
 
58
            "Called with a breezy.lock.LockResult when a physical lock is "
 
59
            "acquired.", (1, 8))
 
60
        self.add_hook('lock_released',
 
61
            "Called with a breezy.lock.LockResult when a physical lock is "
 
62
            "released.", (1, 8))
 
63
        self.add_hook('lock_broken',
 
64
            "Called with a breezy.lock.LockResult when a physical lock is "
 
65
            "broken.", (1, 15))
64
66
 
65
67
 
66
68
class Lock(object):
94
96
    :ivar unlock: A callable which will unlock the lock.
95
97
    """
96
98
 
97
 
    def __init__(self, unlock):
 
99
    def __init__(self, unlock, token=None):
98
100
        self.unlock = unlock
 
101
        self.token = token
99
102
 
100
103
    def __repr__(self):
101
104
        return "LogicalLockResult(%s)" % (self.unlock)
102
105
 
 
106
    def __enter__(self):
 
107
        return self
 
108
 
 
109
    def __exit__(self, exc_type, exc_val, exc_tb):
 
110
        # If there was an error raised, prefer the original one
 
111
        try:
 
112
            self.unlock()
 
113
        except:
 
114
            if exc_type is None:
 
115
                raise
 
116
        return False
103
117
 
104
118
 
105
119
def cant_unlock_not_held(locked_object):
153
167
        try:
154
168
            self.f = open(self.filename, filemode)
155
169
            return self.f
156
 
        except IOError, e:
 
170
        except IOError as e:
157
171
            if e.errno in (errno.EACCES, errno.EPERM):
158
172
                raise errors.LockFailed(self.filename, str(e))
159
173
            if e.errno != errno.ENOENT:
171
185
            self.f.close()
172
186
            self.f = None
173
187
 
174
 
    def __del__(self):
175
 
        if self.f:
176
 
            from warnings import warn
177
 
            warn("lock on %r not released" % self.f)
178
 
            self.unlock()
179
 
 
180
188
    def unlock(self):
181
189
        raise NotImplementedError()
182
190
 
221
229
                # LOCK_NB will cause IOError to be raised if we can't grab a
222
230
                # lock right away.
223
231
                fcntl.lockf(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB)
224
 
            except IOError, e:
 
232
            except IOError as e:
225
233
                if e.errno in (errno.EAGAIN, errno.EACCES):
226
234
                    # We couldn't grab the lock
227
235
                    self.unlock()
256
264
                # LOCK_NB will cause IOError to be raised if we can't grab a
257
265
                # lock right away.
258
266
                fcntl.lockf(self.f, fcntl.LOCK_SH | fcntl.LOCK_NB)
259
 
            except IOError, e:
 
267
            except IOError as e:
260
268
                # we should be more precise about whats a locking
261
269
                # error and whats a random-other error
262
270
                raise errors.LockContention(self.filename, e)
317
325
            # done by _fcntl_ReadLock
318
326
            try:
319
327
                new_f = open(self.filename, 'rb+')
320
 
            except IOError, e:
 
328
            except IOError as e:
321
329
                if e.errno in (errno.EACCES, errno.EPERM):
322
330
                    raise errors.LockFailed(self.filename, str(e))
323
331
                raise
325
333
                # LOCK_NB will cause IOError to be raised if we can't grab a
326
334
                # lock right away.
327
335
                fcntl.lockf(new_f, fcntl.LOCK_EX | fcntl.LOCK_NB)
328
 
            except IOError, e:
 
336
            except IOError as e:
329
337
                # TODO: Raise a more specific error based on the type of error
330
338
                raise errors.LockContention(self.filename, e)
331
339
            _fcntl_WriteLock._open_locks.add(self.filename)
349
357
 
350
358
 
351
359
if have_pywin32 and sys.platform == 'win32':
352
 
    if os.path.supports_unicode_filenames:
353
 
        # for Windows NT/2K/XP/etc
354
 
        win32file_CreateFile = win32file.CreateFileW
355
 
    else:
356
 
        # for Windows 98
357
 
        win32file_CreateFile = win32file.CreateFile
 
360
    win32file_CreateFile = win32file.CreateFileW
358
361
 
359
362
    class _w32c_FileLock(_OSLock):
360
363
 
364
367
                self._handle = win32file_CreateFile(filename, access, share,
365
368
                    None, win32file.OPEN_ALWAYS,
366
369
                    win32file.FILE_ATTRIBUTE_NORMAL, None)
367
 
            except pywintypes.error, e:
 
370
            except pywintypes.error as e:
368
371
                if e.args[0] == winerror.ERROR_ACCESS_DENIED:
369
372
                    raise errors.LockFailed(filename, e)
370
373
                if e.args[0] == winerror.ERROR_SHARING_VIOLATION:
427
430
    from ctypes.wintypes import DWORD, LPCSTR, LPCWSTR
428
431
    LPSECURITY_ATTRIBUTES = ctypes.c_void_p # used as NULL no need to declare
429
432
    HANDLE = ctypes.c_int # rather than unsigned as in ctypes.wintypes
430
 
    if os.path.supports_unicode_filenames:
431
 
        _function_name = "CreateFileW"
432
 
        LPTSTR = LPCWSTR
433
 
    else:
434
 
        _function_name = "CreateFileA"
435
 
        class LPTSTR(LPCSTR):
436
 
            def __new__(cls, obj):
437
 
                return LPCSTR.__new__(cls, obj.encode("mbcs"))
 
433
    _function_name = "CreateFileW"
438
434
 
439
435
    # CreateFile <http://msdn.microsoft.com/en-us/library/aa363858.aspx>
440
436
    _CreateFile = ctypes.WINFUNCTYPE(
441
437
            HANDLE,                # return value
442
 
            LPTSTR,                # lpFileName
 
438
            LPWSTR,                # lpFileName
443
439
            DWORD,                 # dwDesiredAccess
444
440
            DWORD,                 # dwShareMode
445
441
            LPSECURITY_ATTRIBUTES, # lpSecurityAttributes
541
537
    locked the same way), and -Drelock is set, then this will trace.note a
542
538
    message about it.
543
539
    """
544
 
    
 
540
 
545
541
    _prev_lock = None
546
542
 
547
543
    def _note_lock(self, lock_type):
550
546
                type_name = 'read'
551
547
            else:
552
548
                type_name = 'write'
553
 
            trace.note('%r was %s locked again', self, type_name)
 
549
            trace.note(gettext('{0!r} was {1} locked again'), self, type_name)
554
550
        self._prev_lock = lock_type
555
551
 
 
552
@contextlib.contextmanager
 
553
def write_locked(lockable):
 
554
    lockable.lock_write()
 
555
    try:
 
556
        yield lockable
 
557
    finally:
 
558
        lockable.unlock()