~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lockable_files.py

first cut at merge from integration.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005 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
16
16
 
17
17
from cStringIO import StringIO
18
18
import codecs
19
 
#import traceback
20
19
 
21
20
import bzrlib
22
21
from bzrlib.decorators import *
23
22
import bzrlib.errors as errors
24
 
from bzrlib.errors import BzrError
 
23
from bzrlib.errors import LockError, ReadOnlyError
25
24
from bzrlib.osutils import file_iterator, safe_unicode
26
25
from bzrlib.symbol_versioning import *
27
 
from bzrlib.trace import mutter, note
 
26
from bzrlib.symbol_versioning import deprecated_method, zero_eight
 
27
from bzrlib.trace import mutter
28
28
import bzrlib.transactions as transactions
29
 
import bzrlib.urlutils as urlutils
30
 
 
31
 
 
32
 
# XXX: The tracking here of lock counts and whether the lock is held is
33
 
# somewhat redundant with what's done in LockDir; the main difference is that
34
 
# LockableFiles permits reentrancy.
 
29
 
35
30
 
36
31
class LockableFiles(object):
37
 
    """Object representing a set of related files locked within the same scope.
38
 
 
39
 
    These files are used by a WorkingTree, Repository or Branch, and should
40
 
    generally only be touched by that object.
41
 
 
42
 
    LockableFiles also provides some policy on top of Transport for encoding
43
 
    control files as utf-8.
44
 
 
45
 
    LockableFiles manage a lock count and can be locked repeatedly by
46
 
    a single caller.  (The underlying lock implementation generally does not
47
 
    support this.)
48
 
 
49
 
    Instances of this class are often called control_files.
50
 
    
51
 
    This object builds on top of a Transport, which is used to actually write
52
 
    the files to disk, and an OSLock or LockDir, which controls how access to
53
 
    the files is controlled.  The particular type of locking used is set when
54
 
    the object is constructed.  In older formats OSLocks are used everywhere.
55
 
    in newer formats a LockDir is used for Repositories and Branches, and 
56
 
    OSLocks for the local filesystem.
 
32
    """Object representing a set of files locked within the same scope
 
33
 
 
34
    _lock_mode
 
35
        None, or 'r' or 'w'
 
36
 
 
37
    _lock_count
 
38
        If _lock_mode is true, a positive count of the number of times the
 
39
        lock has been taken *by this process*.  Others may have compatible 
 
40
        read locks.
 
41
 
 
42
    _lock
 
43
        Lock object from bzrlib.lock.
57
44
    """
58
45
 
59
 
    # _lock_mode: None, or 'r' or 'w'
60
 
 
61
 
    # _lock_count: If _lock_mode is true, a positive count of the number of
62
 
    # times the lock has been taken *by this process*.   
63
 
    
 
46
    _lock_mode = None
 
47
    _lock_count = None
 
48
    _lock = None
64
49
    # If set to False (by a plugin, etc) BzrBranch will not set the
65
50
    # mode on created files or directories
66
51
    _set_file_mode = True
67
52
    _set_dir_mode = True
68
53
 
69
 
    def __init__(self, transport, lock_name, lock_class):
70
 
        """Create a LockableFiles group
71
 
 
72
 
        :param transport: Transport pointing to the directory holding the 
73
 
            control files and lock.
74
 
        :param lock_name: Name of the lock guarding these files.
75
 
        :param lock_class: Class of lock strategy to use: typically
76
 
            either LockDir or TransportLock.
77
 
        """
 
54
    def __init__(self, transport, lock_name):
 
55
        object.__init__(self)
78
56
        self._transport = transport
79
57
        self.lock_name = lock_name
80
58
        self._transaction = None
81
 
        self._lock_mode = None
82
 
        self._lock_count = 0
83
59
        self._find_modes()
84
 
        esc_name = self._escape(lock_name)
85
 
        self._lock = lock_class(transport, esc_name,
86
 
                                file_modebits=self._file_mode,
87
 
                                dir_modebits=self._dir_mode)
88
 
 
89
 
    def create_lock(self):
90
 
        """Create the lock.
91
 
 
92
 
        This should normally be called only when the LockableFiles directory
93
 
        is first created on disk.
94
 
        """
95
 
        self._lock.create(mode=self._dir_mode)
96
 
 
97
 
    def __repr__(self):
98
 
        return '%s(%r)' % (self.__class__.__name__,
99
 
                           self._transport)
100
 
    def __str__(self):
101
 
        return 'LockableFiles(%s, %s)' % (self.lock_name, self._transport.base)
102
60
 
103
61
    def __del__(self):
104
 
        if self.is_locked():
 
62
        if self._lock_mode or self._lock:
105
63
            # XXX: This should show something every time, and be suitable for
106
64
            # headless operation and embedding
107
65
            from warnings import warn
108
66
            warn("file group %r was not explicitly unlocked" % self)
109
67
            self._lock.unlock()
110
68
 
111
 
    def break_lock(self):
112
 
        """Break the lock of this lockable files group if it is held.
113
 
 
114
 
        The current ui factory will be used to prompt for user conformation.
115
 
        """
116
 
        self._lock.break_lock()
117
 
 
118
69
    def _escape(self, file_or_path):
119
70
        if not isinstance(file_or_path, basestring):
120
71
            file_or_path = '/'.join(file_or_path)
121
72
        if file_or_path == '':
122
73
            return u''
123
 
        return urlutils.escape(safe_unicode(file_or_path))
 
74
        return bzrlib.transport.urlescape(safe_unicode(file_or_path))
124
75
 
125
76
    def _find_modes(self):
126
77
        """Determine the appropriate modes for files and directories."""
157
108
        """
158
109
 
159
110
        relpath = self._escape(file_or_path)
160
 
        # TODO: codecs.open() buffers linewise, so it was overloaded with
 
111
        #TODO: codecs.open() buffers linewise, so it was overloaded with
161
112
        # a much larger buffer, do we need to do the same for getreader/getwriter?
162
113
        if mode == 'rb': 
163
114
            return self.get(relpath)
211
162
        self.put(path, StringIO(a_string.encode('utf-8')))
212
163
 
213
164
    def lock_write(self):
214
 
        # mutter("lock write: %s (%s)", self, self._lock_count)
 
165
        mutter("lock write: %s (%s)", self, self._lock_count)
215
166
        # TODO: Upgrade locking to support using a Transport,
216
167
        # and potentially a remote locking protocol
217
168
        if self._lock_mode:
218
 
            if self._lock_mode != 'w' or not self.get_transaction().writeable():
219
 
                raise errors.ReadOnlyError(self)
 
169
            if self._lock_mode != 'w':
 
170
                raise ReadOnlyError("can't upgrade to a write lock from %r" %
 
171
                                self._lock_mode)
220
172
            self._lock_count += 1
221
173
        else:
222
 
            self._lock.lock_write()
223
 
            #note('write locking %s', self)
224
 
            #traceback.print_stack()
 
174
            self._lock = self._transport.lock_write(
 
175
                    self._escape(self.lock_name))
225
176
            self._lock_mode = 'w'
226
177
            self._lock_count = 1
227
 
            self._set_transaction(transactions.WriteTransaction())
 
178
            self._set_transaction(transactions.PassThroughTransaction())
228
179
 
229
180
    def lock_read(self):
230
 
        # mutter("lock read: %s (%s)", self, self._lock_count)
 
181
        mutter("lock read: %s (%s)", self, self._lock_count)
231
182
        if self._lock_mode:
232
183
            assert self._lock_mode in ('r', 'w'), \
233
184
                   "invalid lock mode %r" % self._lock_mode
234
185
            self._lock_count += 1
235
186
        else:
236
 
            self._lock.lock_read()
237
 
            #note('read locking %s', self)
238
 
            #traceback.print_stack()
 
187
            self._lock = self._transport.lock_read(
 
188
                    self._escape(self.lock_name))
239
189
            self._lock_mode = 'r'
240
190
            self._lock_count = 1
241
191
            self._set_transaction(transactions.ReadOnlyTransaction())
243
193
            self.get_transaction().set_cache_size(5000)
244
194
                        
245
195
    def unlock(self):
246
 
        # mutter("unlock: %s (%s)", self, self._lock_count)
 
196
        mutter("unlock: %s (%s)", self, self._lock_count)
247
197
        if not self._lock_mode:
248
 
            raise errors.LockNotHeld(self)
 
198
            raise LockError('branch %r is not locked' % (self))
 
199
 
249
200
        if self._lock_count > 1:
250
201
            self._lock_count -= 1
251
202
        else:
252
 
            #note('unlocking %s', self)
253
 
            #traceback.print_stack()
254
203
            self._finish_transaction()
255
 
            try:
256
 
                self._lock.unlock()
257
 
            finally:
258
 
                self._lock_mode = self._lock_count = None
259
 
 
260
 
    def is_locked(self):
261
 
        """Return true if this LockableFiles group is locked"""
262
 
        return self._lock_count >= 1
263
 
 
264
 
    def get_physical_lock_status(self):
265
 
        """Return physical lock status.
266
 
        
267
 
        Returns true if a lock is held on the transport. If no lock is held, or
268
 
        the underlying locking mechanism does not support querying lock
269
 
        status, false is returned.
270
 
        """
271
 
        try:
272
 
            return self._lock.peek() is not None
273
 
        except NotImplementedError:
274
 
            return False
 
204
            self._lock.unlock()
 
205
            self._lock = None
 
206
            self._lock_mode = self._lock_count = None
275
207
 
276
208
    def get_transaction(self):
277
209
        """Return the current active transaction.
299
231
        transaction = self._transaction
300
232
        self._transaction = None
301
233
        transaction.finish()
302
 
 
303
 
 
304
 
class TransportLock(object):
305
 
    """Locking method which uses transport-dependent locks.
306
 
 
307
 
    On the local filesystem these transform into OS-managed locks.
308
 
 
309
 
    These do not guard against concurrent access via different
310
 
    transports.
311
 
 
312
 
    This is suitable for use only in WorkingTrees (which are at present
313
 
    always local).
314
 
    """
315
 
    def __init__(self, transport, escaped_name, file_modebits, dir_modebits):
316
 
        self._transport = transport
317
 
        self._escaped_name = escaped_name
318
 
        self._file_modebits = file_modebits
319
 
        self._dir_modebits = dir_modebits
320
 
 
321
 
    def break_lock(self):
322
 
        raise NotImplementedError(self.break_lock)
323
 
 
324
 
    def lock_write(self):
325
 
        self._lock = self._transport.lock_write(self._escaped_name)
326
 
 
327
 
    def lock_read(self):
328
 
        self._lock = self._transport.lock_read(self._escaped_name)
329
 
 
330
 
    def unlock(self):
331
 
        self._lock.unlock()
332
 
        self._lock = None
333
 
 
334
 
    def peek(self):
335
 
        raise NotImplementedError()
336
 
 
337
 
    def create(self, mode=None):
338
 
        """Create lock mechanism"""
339
 
        # for old-style locks, create the file now
340
 
        self._transport.put(self._escaped_name, StringIO(), 
341
 
                            mode=self._file_modebits)