~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lock.py

Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
38
38
import os
39
39
import sys
40
40
 
 
41
from bzrlib.errors import LockError
 
42
from bzrlib.osutils import realpath
41
43
from bzrlib.trace import mutter
42
 
from bzrlib.errors import LockError
43
44
 
44
45
 
45
46
class _base_Lock(object):
 
47
 
46
48
    def _open(self, filename, filemode):
47
49
        try:
48
50
            self.f = open(filename, filemode)
75
77
    import fcntl
76
78
 
77
79
    class _fcntl_FileLock(_base_Lock):
 
80
 
78
81
        f = None
79
82
 
80
 
        def unlock(self):
 
83
        def _unlock(self):
81
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."""
82
89
            self.f.close()
83
90
            del self.f 
84
91
 
 
92
 
85
93
    class _fcntl_WriteLock(_fcntl_FileLock):
 
94
 
 
95
        open_locks = {}
 
96
 
86
97
        def __init__(self, filename):
87
98
            # standard IO errors get exposed directly.
88
99
            self._open(filename, 'wb')
89
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
90
109
                fcntl.lockf(self.f, fcntl.LOCK_EX)
91
110
            except IOError, e:
92
111
                # we should be more precise about whats a locking
93
112
                # error and whats a random-other error
94
113
                raise LockError(e)
95
114
 
 
115
        def unlock(self):
 
116
            del self.open_locks[self.filename]
 
117
            self._unlock()
 
118
 
 
119
 
96
120
    class _fcntl_ReadLock(_fcntl_FileLock):
97
121
 
98
122
        def __init__(self, filename):
105
129
                # error and whats a random-other error
106
130
                raise LockError(e)
107
131
 
 
132
        def unlock(self):
 
133
            self._unlock()
 
134
 
 
135
 
108
136
    WriteLock = _fcntl_WriteLock
109
137
    ReadLock = _fcntl_ReadLock
110
138