/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 bzrlib/lockable_files.py

  • Committer: Martin Pool
  • Date: 2009-07-27 06:28:35 UTC
  • mto: This revision was merged to the branch mainline in revision 4587.
  • Revision ID: mbp@sourcefrog.net-20090727062835-o66p8it658tq1sma
Add CountedLock.get_physical_lock_status

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2008, 2009 Canonical Ltd
2
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
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
 
from __future__ import absolute_import
 
17
from cStringIO import StringIO
18
18
 
19
 
from .lazy_import import lazy_import
 
19
from bzrlib.lazy_import import lazy_import
20
20
lazy_import(globals(), """
21
 
from breezy import (
 
21
import codecs
 
22
import warnings
 
23
 
 
24
from bzrlib import (
22
25
    counted_lock,
 
26
    errors,
23
27
    lock,
 
28
    osutils,
24
29
    transactions,
25
30
    urlutils,
26
31
    )
27
32
""")
28
33
 
29
 
from . import (
30
 
    errors,
31
 
    )
32
 
from .decorators import (
33
 
    only_raises,
34
 
    )
 
34
from bzrlib.decorators import (
 
35
    needs_read_lock,
 
36
    needs_write_lock,
 
37
    )
 
38
from bzrlib.symbol_versioning import (
 
39
    deprecated_in,
 
40
    deprecated_method,
 
41
    )
 
42
 
 
43
 
 
44
# XXX: The tracking here of lock counts and whether the lock is held is
 
45
# somewhat redundant with what's done in LockDir; the main difference is that
 
46
# LockableFiles permits reentrancy.
 
47
 
 
48
class _LockWarner(object):
 
49
    """Hold a counter for a lock and warn if GCed while the count is >= 1.
 
50
 
 
51
    This is separate from LockableFiles because putting a __del__ on
 
52
    LockableFiles can result in uncollectable cycles.
 
53
    """
 
54
 
 
55
    def __init__(self, repr):
 
56
        self.lock_count = 0
 
57
        self.repr = repr
 
58
 
 
59
    def __del__(self):
 
60
        if self.lock_count >= 1:
 
61
            # There should have been a try/finally to unlock this.
 
62
            warnings.warn("%r was gc'd while locked" % self.repr)
35
63
 
36
64
 
37
65
class LockableFiles(object):
48
76
    This class is now deprecated; code should move to using the Transport
49
77
    directly for file operations and using the lock or CountedLock for
50
78
    locking.
51
 
 
 
79
    
52
80
    :ivar _lock: The real underlying lock (e.g. a LockDir)
53
 
    :ivar _lock_count: If _lock_mode is true, a positive count of the number
54
 
        of times the lock has been taken (and not yet released) *by this
55
 
        process*, through this particular object instance.
56
 
    :ivar _lock_mode: None, or 'r' or 'w'
 
81
    :ivar _counted_lock: A lock decorated with a semaphore, so that it 
 
82
        can be re-entered.
57
83
    """
58
84
 
 
85
    # _lock_mode: None, or 'r' or 'w'
 
86
 
 
87
    # _lock_count: If _lock_mode is true, a positive count of the number of
 
88
    # times the lock has been taken *by this process*.
 
89
 
59
90
    def __init__(self, transport, lock_name, lock_class):
60
91
        """Create a LockableFiles group
61
92
 
69
100
        self.lock_name = lock_name
70
101
        self._transaction = None
71
102
        self._lock_mode = None
72
 
        self._lock_count = 0
 
103
        self._lock_warner = _LockWarner(repr(self))
73
104
        self._find_modes()
74
105
        esc_name = self._escape(lock_name)
75
106
        self._lock = lock_class(transport, esc_name,
88
119
    def __repr__(self):
89
120
        return '%s(%r)' % (self.__class__.__name__,
90
121
                           self._transport)
91
 
 
92
122
    def __str__(self):
93
123
        return 'LockableFiles(%s, %s)' % (self.lock_name, self._transport.base)
94
124
 
101
131
 
102
132
    def _escape(self, file_or_path):
103
133
        """DEPRECATED: Do not use outside this class"""
 
134
        if not isinstance(file_or_path, basestring):
 
135
            file_or_path = '/'.join(file_or_path)
104
136
        if file_or_path == '':
105
137
            return u''
106
 
        return urlutils.escape(file_or_path)
 
138
        return urlutils.escape(osutils.safe_unicode(file_or_path))
107
139
 
108
140
    def _find_modes(self):
109
141
        """Determine the appropriate modes for files and directories.
116
148
        try:
117
149
            st = self._transport.stat('.')
118
150
        except errors.TransportNotPossible:
119
 
            self._dir_mode = 0o755
120
 
            self._file_mode = 0o644
 
151
            self._dir_mode = 0755
 
152
            self._file_mode = 0644
121
153
        else:
122
154
            # Check the directory mode, but also make sure the created
123
155
            # directories and files are read-write for this user. This is
124
156
            # mostly a workaround for filesystems which lie about being able to
125
157
            # write to a directory (cygwin & win32)
126
 
            self._dir_mode = (st.st_mode & 0o7777) | 0o0700
 
158
            self._dir_mode = (st.st_mode & 07777) | 00700
127
159
            # Remove the sticky and execute bits for files
128
 
            self._file_mode = self._dir_mode & ~0o7111
 
160
            self._file_mode = self._dir_mode & ~07111
129
161
 
130
162
    def leave_in_place(self):
131
163
        """Set this LockableFiles to not clear the physical lock on unlock."""
150
182
        some other way, and need to synchronise this object's state with that
151
183
        fact.
152
184
        """
 
185
        # TODO: Upgrade locking to support using a Transport,
 
186
        # and potentially a remote locking protocol
153
187
        if self._lock_mode:
154
 
            if (self._lock_mode != 'w'
155
 
                    or not self.get_transaction().writeable()):
 
188
            if self._lock_mode != 'w' or not self.get_transaction().writeable():
156
189
                raise errors.ReadOnlyError(self)
157
190
            self._lock.validate_token(token)
158
 
            self._lock_count += 1
 
191
            self._lock_warner.lock_count += 1
159
192
            return self._token_from_lock
160
193
        else:
161
194
            token_from_lock = self._lock.lock_write(token=token)
162
 
            # traceback.print_stack()
 
195
            #traceback.print_stack()
163
196
            self._lock_mode = 'w'
164
 
            self._lock_count = 1
 
197
            self._lock_warner.lock_count = 1
165
198
            self._set_write_transaction()
166
199
            self._token_from_lock = token_from_lock
167
200
            return token_from_lock
170
203
        if self._lock_mode:
171
204
            if self._lock_mode not in ('r', 'w'):
172
205
                raise ValueError("invalid lock mode %r" % (self._lock_mode,))
173
 
            self._lock_count += 1
 
206
            self._lock_warner.lock_count += 1
174
207
        else:
175
208
            self._lock.lock_read()
176
 
            # traceback.print_stack()
 
209
            #traceback.print_stack()
177
210
            self._lock_mode = 'r'
178
 
            self._lock_count = 1
 
211
            self._lock_warner.lock_count = 1
179
212
            self._set_read_transaction()
180
213
 
181
214
    def _set_read_transaction(self):
188
221
        """Setup a write transaction."""
189
222
        self._set_transaction(transactions.WriteTransaction())
190
223
 
191
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
192
224
    def unlock(self):
193
225
        if not self._lock_mode:
194
226
            return lock.cant_unlock_not_held(self)
195
 
        if self._lock_count > 1:
196
 
            self._lock_count -= 1
 
227
        if self._lock_warner.lock_count > 1:
 
228
            self._lock_warner.lock_count -= 1
197
229
        else:
198
 
            # traceback.print_stack()
 
230
            #traceback.print_stack()
199
231
            self._finish_transaction()
200
232
            try:
201
233
                self._lock.unlock()
202
234
            finally:
203
 
                self._lock_count = 0
204
 
                self._lock_mode = None
 
235
                self._lock_mode = self._lock_warner.lock_count = None
 
236
 
 
237
    @property
 
238
    def _lock_count(self):
 
239
        return self._lock_warner.lock_count
205
240
 
206
241
    def is_locked(self):
207
242
        """Return true if this LockableFiles group is locked"""
208
 
        return self._lock_count >= 1
 
243
        return self._lock_warner.lock_count >= 1
209
244
 
210
245
    def get_physical_lock_status(self):
211
246
        """Return physical lock status.
258
293
    This is suitable for use only in WorkingTrees (which are at present
259
294
    always local).
260
295
    """
261
 
 
262
296
    def __init__(self, transport, escaped_name, file_modebits, dir_modebits):
263
297
        self._transport = transport
264
298
        self._escaped_name = escaped_name
292
326
    def create(self, mode=None):
293
327
        """Create lock mechanism"""
294
328
        # for old-style locks, create the file now
295
 
        self._transport.put_bytes(self._escaped_name, b'',
296
 
                                  mode=self._file_modebits)
 
329
        self._transport.put_bytes(self._escaped_name, '',
 
330
                            mode=self._file_modebits)
297
331
 
298
332
    def validate_token(self, token):
299
333
        if token is not None:
300
334
            raise errors.TokenLockingNotSupported(self)
 
335