1
# Copyright (C) 2005, 2006, 2008 Canonical Ltd
 
 
3
# This program is free software; you can redistribute it and/or modify
 
 
4
# it under the terms of the GNU General Public License as published by
 
 
5
# the Free Software Foundation; either version 2 of the License, or
 
 
6
# (at your option) any later version.
 
 
8
# This program is distributed in the hope that it will be useful,
 
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
11
# GNU General Public License for more details.
 
 
13
# You should have received a copy of the GNU General Public License
 
 
14
# along with this program; if not, write to the Free Software
 
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
17
from cStringIO import StringIO
 
 
20
from warnings import warn
 
 
23
from bzrlib.decorators import (needs_read_lock,
 
 
25
import bzrlib.errors as errors
 
 
26
from bzrlib.errors import BzrError
 
 
27
from bzrlib.osutils import file_iterator, safe_unicode
 
 
28
from bzrlib.symbol_versioning import (
 
 
32
from bzrlib.trace import mutter, note
 
 
33
import bzrlib.transactions as transactions
 
 
34
import bzrlib.urlutils as urlutils
 
 
37
# XXX: The tracking here of lock counts and whether the lock is held is
 
 
38
# somewhat redundant with what's done in LockDir; the main difference is that
 
 
39
# LockableFiles permits reentrancy.
 
 
41
class LockableFiles(object):
 
 
42
    """Object representing a set of related files locked within the same scope.
 
 
44
    These files are used by a WorkingTree, Repository or Branch, and should
 
 
45
    generally only be touched by that object.
 
 
47
    LockableFiles also provides some policy on top of Transport for encoding
 
 
48
    control files as utf-8.
 
 
50
    LockableFiles manage a lock count and can be locked repeatedly by
 
 
51
    a single caller.  (The underlying lock implementation generally does not
 
 
54
    Instances of this class are often called control_files.
 
 
56
    This object builds on top of a Transport, which is used to actually write
 
 
57
    the files to disk, and an OSLock or LockDir, which controls how access to
 
 
58
    the files is controlled.  The particular type of locking used is set when
 
 
59
    the object is constructed.  In older formats OSLocks are used everywhere.
 
 
60
    in newer formats a LockDir is used for Repositories and Branches, and 
 
 
61
    OSLocks for the local filesystem.
 
 
64
    # _lock_mode: None, or 'r' or 'w'
 
 
66
    # _lock_count: If _lock_mode is true, a positive count of the number of
 
 
67
    # times the lock has been taken *by this process*.   
 
 
69
    # If set to False (by a plugin, etc) BzrBranch will not set the
 
 
70
    # mode on created files or directories
 
 
74
    def __init__(self, transport, lock_name, lock_class):
 
 
75
        """Create a LockableFiles group
 
 
77
        :param transport: Transport pointing to the directory holding the 
 
 
78
            control files and lock.
 
 
79
        :param lock_name: Name of the lock guarding these files.
 
 
80
        :param lock_class: Class of lock strategy to use: typically
 
 
81
            either LockDir or TransportLock.
 
 
83
        self._transport = transport
 
 
84
        self.lock_name = lock_name
 
 
85
        self._transaction = None
 
 
86
        self._lock_mode = None
 
 
89
        esc_name = self._escape(lock_name)
 
 
90
        self._lock = lock_class(transport, esc_name,
 
 
91
                                file_modebits=self._file_mode,
 
 
92
                                dir_modebits=self._dir_mode)
 
 
94
    def create_lock(self):
 
 
97
        This should normally be called only when the LockableFiles directory
 
 
98
        is first created on disk.
 
 
100
        self._lock.create(mode=self._dir_mode)
 
 
103
        return '%s(%r)' % (self.__class__.__name__,
 
 
106
        return 'LockableFiles(%s, %s)' % (self.lock_name, self._transport.base)
 
 
110
            # do not automatically unlock; there should have been a
 
 
111
            # try/finally to unlock this.
 
 
112
            warn("%r was gc'd while locked" % self)
 
 
114
    def break_lock(self):
 
 
115
        """Break the lock of this lockable files group if it is held.
 
 
117
        The current ui factory will be used to prompt for user conformation.
 
 
119
        self._lock.break_lock()
 
 
121
    def _escape(self, file_or_path):
 
 
122
        if not isinstance(file_or_path, basestring):
 
 
123
            file_or_path = '/'.join(file_or_path)
 
 
124
        if file_or_path == '':
 
 
126
        return urlutils.escape(safe_unicode(file_or_path))
 
 
128
    def _find_modes(self):
 
 
129
        """Determine the appropriate modes for files and directories."""
 
 
131
            st = self._transport.stat('.')
 
 
132
        except errors.TransportNotPossible:
 
 
133
            self._dir_mode = 0755
 
 
134
            self._file_mode = 0644
 
 
136
            # Check the directory mode, but also make sure the created
 
 
137
            # directories and files are read-write for this user. This is
 
 
138
            # mostly a workaround for filesystems which lie about being able to
 
 
139
            # write to a directory (cygwin & win32)
 
 
140
            self._dir_mode = (st.st_mode & 07777) | 00700
 
 
141
            # Remove the sticky and execute bits for files
 
 
142
            self._file_mode = self._dir_mode & ~07111
 
 
143
        if not self._set_dir_mode:
 
 
144
            self._dir_mode = None
 
 
145
        if not self._set_file_mode:
 
 
146
            self._file_mode = None
 
 
148
    def controlfilename(self, file_or_path):
 
 
149
        """Return location relative to branch."""
 
 
150
        return self._transport.abspath(self._escape(file_or_path))
 
 
153
    def get(self, relpath):
 
 
154
        """Get a file as a bytestream."""
 
 
155
        relpath = self._escape(relpath)
 
 
156
        return self._transport.get(relpath)
 
 
159
    @deprecated_method(deprecated_in((1, 5, 0)))
 
 
160
    def get_utf8(self, relpath):
 
 
161
        """Get a file as a unicode stream."""
 
 
162
        relpath = self._escape(relpath)
 
 
163
        # DO NOT introduce an errors=replace here.
 
 
164
        return codecs.getreader('utf-8')(self._transport.get(relpath))
 
 
167
    def put(self, path, file):
 
 
170
        :param path: The path to put the file, relative to the .bzr control
 
 
172
        :param f: A file-like or string object whose contents should be copied.
 
 
174
        self._transport.put_file(self._escape(path), file, mode=self._file_mode)
 
 
177
    def put_bytes(self, path, a_string):
 
 
178
        """Write a string of bytes.
 
 
180
        :param path: The path to put the bytes, relative to the transport root.
 
 
181
        :param string: A string object, whose exact bytes are to be copied.
 
 
183
        self._transport.put_bytes(self._escape(path), a_string,
 
 
184
                                  mode=self._file_mode)
 
 
187
    def put_utf8(self, path, a_string):
 
 
188
        """Write a string, encoding as utf-8.
 
 
190
        :param path: The path to put the string, relative to the transport root.
 
 
191
        :param string: A string or unicode object whose contents should be copied.
 
 
193
        # IterableFile would not be needed if Transport.put took iterables
 
 
194
        # instead of files.  ADHB 2005-12-25
 
 
195
        # RBC 20060103 surely its not needed anyway, with codecs transcode
 
 
197
        # JAM 20060103 We definitely don't want encode(..., 'replace')
 
 
198
        # these are valuable files which should have exact contents.
 
 
199
        if not isinstance(a_string, basestring):
 
 
200
            raise errors.BzrBadParameterNotString(a_string)
 
 
201
        self.put_bytes(path, a_string.encode('utf-8'))
 
 
203
    def leave_in_place(self):
 
 
204
        """Set this LockableFiles to not clear the physical lock on unlock."""
 
 
205
        self._lock.leave_in_place()
 
 
207
    def dont_leave_in_place(self):
 
 
208
        """Set this LockableFiles to clear the physical lock on unlock."""
 
 
209
        self._lock.dont_leave_in_place()
 
 
211
    def lock_write(self, token=None):
 
 
212
        """Lock this group of files for writing.
 
 
214
        :param token: if this is already locked, then lock_write will fail
 
 
215
            unless the token matches the existing lock.
 
 
216
        :returns: a token if this instance supports tokens, otherwise None.
 
 
217
        :raises TokenLockingNotSupported: when a token is given but this
 
 
218
            instance doesn't support using token locks.
 
 
219
        :raises MismatchedToken: if the specified token doesn't match the token
 
 
220
            of the existing lock.
 
 
222
        A token should be passed in if you know that you have locked the object
 
 
223
        some other way, and need to synchronise this object's state with that
 
 
226
        # mutter("lock write: %s (%s)", self, self._lock_count)
 
 
227
        # TODO: Upgrade locking to support using a Transport,
 
 
228
        # and potentially a remote locking protocol
 
 
230
            if self._lock_mode != 'w' or not self.get_transaction().writeable():
 
 
231
                raise errors.ReadOnlyError(self)
 
 
232
            self._lock.validate_token(token)
 
 
233
            self._lock_count += 1
 
 
234
            return self._token_from_lock
 
 
236
            token_from_lock = self._lock.lock_write(token=token)
 
 
237
            #note('write locking %s', self)
 
 
238
            #traceback.print_stack()
 
 
239
            self._lock_mode = 'w'
 
 
241
            self._set_transaction(transactions.WriteTransaction())
 
 
242
            self._token_from_lock = token_from_lock
 
 
243
            return token_from_lock
 
 
246
        # mutter("lock read: %s (%s)", self, self._lock_count)
 
 
248
            if self._lock_mode not in ('r', 'w'):
 
 
249
                raise ValueError("invalid lock mode %r" % (self._lock_mode,))
 
 
250
            self._lock_count += 1
 
 
252
            self._lock.lock_read()
 
 
253
            #note('read locking %s', self)
 
 
254
            #traceback.print_stack()
 
 
255
            self._lock_mode = 'r'
 
 
257
            self._set_transaction(transactions.ReadOnlyTransaction())
 
 
258
            # 5K may be excessive, but hey, its a knob.
 
 
259
            self.get_transaction().set_cache_size(5000)
 
 
262
        # mutter("unlock: %s (%s)", self, self._lock_count)
 
 
263
        if not self._lock_mode:
 
 
264
            raise errors.LockNotHeld(self)
 
 
265
        if self._lock_count > 1:
 
 
266
            self._lock_count -= 1
 
 
268
            #note('unlocking %s', self)
 
 
269
            #traceback.print_stack()
 
 
270
            self._finish_transaction()
 
 
274
                self._lock_mode = self._lock_count = None
 
 
277
        """Return true if this LockableFiles group is locked"""
 
 
278
        return self._lock_count >= 1
 
 
280
    def get_physical_lock_status(self):
 
 
281
        """Return physical lock status.
 
 
283
        Returns true if a lock is held on the transport. If no lock is held, or
 
 
284
        the underlying locking mechanism does not support querying lock
 
 
285
        status, false is returned.
 
 
288
            return self._lock.peek() is not None
 
 
289
        except NotImplementedError:
 
 
292
    def get_transaction(self):
 
 
293
        """Return the current active transaction.
 
 
295
        If no transaction is active, this returns a passthrough object
 
 
296
        for which all data is immediately flushed and no caching happens.
 
 
298
        if self._transaction is None:
 
 
299
            return transactions.PassThroughTransaction()
 
 
301
            return self._transaction
 
 
303
    def _set_transaction(self, new_transaction):
 
 
304
        """Set a new active transaction."""
 
 
305
        if self._transaction is not None:
 
 
306
            raise errors.LockError('Branch %s is in a transaction already.' %
 
 
308
        self._transaction = new_transaction
 
 
310
    def _finish_transaction(self):
 
 
311
        """Exit the current transaction."""
 
 
312
        if self._transaction is None:
 
 
313
            raise errors.LockError('Branch %s is not in a transaction' %
 
 
315
        transaction = self._transaction
 
 
316
        self._transaction = None
 
 
320
class TransportLock(object):
 
 
321
    """Locking method which uses transport-dependent locks.
 
 
323
    On the local filesystem these transform into OS-managed locks.
 
 
325
    These do not guard against concurrent access via different
 
 
328
    This is suitable for use only in WorkingTrees (which are at present
 
 
331
    def __init__(self, transport, escaped_name, file_modebits, dir_modebits):
 
 
332
        self._transport = transport
 
 
333
        self._escaped_name = escaped_name
 
 
334
        self._file_modebits = file_modebits
 
 
335
        self._dir_modebits = dir_modebits
 
 
337
    def break_lock(self):
 
 
338
        raise NotImplementedError(self.break_lock)
 
 
340
    def leave_in_place(self):
 
 
341
        raise NotImplementedError(self.leave_in_place)
 
 
343
    def dont_leave_in_place(self):
 
 
344
        raise NotImplementedError(self.dont_leave_in_place)
 
 
346
    def lock_write(self, token=None):
 
 
347
        if token is not None:
 
 
348
            raise errors.TokenLockingNotSupported(self)
 
 
349
        self._lock = self._transport.lock_write(self._escaped_name)
 
 
352
        self._lock = self._transport.lock_read(self._escaped_name)
 
 
359
        raise NotImplementedError()
 
 
361
    def create(self, mode=None):
 
 
362
        """Create lock mechanism"""
 
 
363
        # for old-style locks, create the file now
 
 
364
        self._transport.put_bytes(self._escaped_name, '',
 
 
365
                            mode=self._file_modebits)
 
 
367
    def validate_token(self, token):
 
 
368
        if token is not None:
 
 
369
            raise errors.TokenLockingNotSupported(self)