~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/store.py

  • Committer: mbp at sourcefrog
  • Date: 2005-03-09 04:08:15 UTC
  • Revision ID: mbp@sourcefrog.net-20050309040815-13242001617e4a06
import from baz patch-364

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Development Ltd
 
1
#! /usr/bin/env python
 
2
# -*- coding: UTF-8 -*-
2
3
 
3
4
# This program is free software; you can redistribute it and/or modify
4
5
# it under the terms of the GNU General Public License as published by
14
15
# along with this program; if not, write to the Free Software
15
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
 
17
 
# TODO: Could remember a bias towards whether a particular store is typically
18
 
# compressed or not.
19
 
 
20
 
"""
21
 
Stores are the main data-storage mechanism for Bazaar-NG.
 
18
"""Stores are the main data-storage mechanism for Bazaar-NG.
22
19
 
23
20
A store is a simple write-once container indexed by a universally
24
 
unique ID.
25
 
"""
26
 
 
27
 
from cStringIO import StringIO
28
 
from stat import ST_MODE, S_ISDIR
29
 
from zlib import adler32
30
 
 
31
 
import bzrlib.errors as errors
32
 
from bzrlib.errors import BzrError, UnlistableStore, TransportNotPossible
33
 
from bzrlib.trace import mutter
34
 
import bzrlib.transport
35
 
from bzrlib.transport.local import LocalTransport
 
21
unique ID, which is typically the SHA-1 of the content."""
 
22
 
 
23
__copyright__ = "Copyright (C) 2005 Canonical Ltd."
 
24
__author__ = "Martin Pool <mbp@canonical.com>"
 
25
 
 
26
import os, tempfile, types, osutils
 
27
from StringIO import StringIO
 
28
from trace import mutter
 
29
 
36
30
 
37
31
######################################################################
38
32
# stores
41
35
    pass
42
36
 
43
37
 
44
 
class Store(object):
45
 
    """This class represents the abstract storage layout for saving information.
46
 
    
 
38
class ImmutableStore:
 
39
    """Store that holds files indexed by unique names.
 
40
 
47
41
    Files can be added, but not modified once they are in.  Typically
48
42
    the hash is used as the name, or something else known to be unique,
49
43
    such as a UUID.
 
44
 
 
45
    >>> st = ImmutableScratchStore()
 
46
 
 
47
    >>> st.add(StringIO('hello'), 'aa')
 
48
    >>> 'aa' in st
 
49
    True
 
50
    >>> 'foo' in st
 
51
    False
 
52
 
 
53
    You are not allowed to add an id that is already present.
 
54
 
 
55
    Entries can be retrieved as files, which may then be read.
 
56
 
 
57
    >>> st.add(StringIO('goodbye'), '123123')
 
58
    >>> st['123123'].read()
 
59
    'goodbye'
 
60
 
 
61
    :todo: Atomic add by writing to a temporary file and renaming.
 
62
 
 
63
    :todo: Perhaps automatically transform to/from XML in a method?
 
64
           Would just need to tell the constructor what class to
 
65
           use...
 
66
 
 
67
    :todo: Even within a simple disk store like this, we could
 
68
           gzip the files.  But since many are less than one disk
 
69
           block, that might not help a lot.
 
70
 
50
71
    """
51
72
 
52
 
    def __len__(self):
53
 
        raise NotImplementedError('Children should define their length')
54
 
 
55
 
    def __getitem__(self, fileid):
56
 
        """Returns a file reading from a particular entry."""
57
 
        raise NotImplementedError
58
 
 
59
 
    def __contains__(self, fileid):
60
 
        """"""
61
 
        raise NotImplementedError
62
 
 
63
 
    def __iter__(self):
64
 
        raise NotImplementedError
 
73
    def __init__(self, basedir):
 
74
        """ImmutableStore constructor."""
 
75
        self._basedir = basedir
 
76
 
 
77
    def _path(self, id):
 
78
        return os.path.join(self._basedir, id)
 
79
 
 
80
    def __repr__(self):
 
81
        return "%s(%r)" % (self.__class__.__name__, self._basedir)
65
82
 
66
83
    def add(self, f, fileid):
67
 
        """Add a file object f to the store accessible from the given fileid"""
68
 
        raise NotImplementedError('Children of Store must define their method of adding entries.')
69
 
 
70
 
    def add_multi(self, entries):
71
 
        """Add a series of file-like or string objects to the store with the given
72
 
        identities.
73
 
        
74
 
        :param entries: A list of tuples of file,id pairs [(file1, id1), (file2, id2), ...]
75
 
                        This could also be a generator yielding (file,id) pairs.
76
 
        """
77
 
        for f, fileid in entries:
78
 
            self.add(f, fileid)
79
 
 
80
 
    def has(self, fileids):
81
 
        """Return True/False for each entry in fileids.
82
 
 
83
 
        :param fileids: A List or generator yielding file ids.
84
 
        :return: A generator or list returning True/False for each entry.
85
 
        """
86
 
        for fileid in fileids:
87
 
            if fileid in self:
88
 
                yield True
89
 
            else:
90
 
                yield False
91
 
 
92
 
    def listable(self):
93
 
        """Return True if this store is able to be listed."""
94
 
        return hasattr(self, "__iter__")
95
 
 
96
 
    def get(self, fileids, permit_failure=False, pb=None):
97
 
        """Return a set of files, one for each requested entry.
98
 
        
99
 
        :param permit_failure: If true, return None for entries which do not 
100
 
                               exist.
101
 
        :return: A list or generator of file-like objects, one for each id.
102
 
        """
103
 
        for fileid in fileids:
104
 
            try:
105
 
                yield self[fileid]
106
 
            except KeyError:
107
 
                if permit_failure:
108
 
                    yield None
109
 
                else:
110
 
                    raise
111
 
 
112
 
    def copy_multi(self, other, ids, pb=None, permit_failure=False):
113
 
        """Copy texts for ids from other into self.
114
 
 
115
 
        If an id is present in self, it is skipped.  A count of copied
116
 
        ids is returned, which may be less than len(ids).
117
 
 
118
 
        :param other: Another Store object
119
 
        :param ids: A list of entry ids to be copied
120
 
        :param pb: A ProgressBar object, if none is given, the default will be created.
121
 
        :param permit_failure: Allow missing entries to be ignored
122
 
        :return: (n_copied, [failed]) The number of entries copied successfully,
123
 
            followed by a list of entries which could not be copied (because they
124
 
            were missing)
125
 
        """
126
 
        if pb is None:
127
 
            pb = bzrlib.ui.ui_factory.progress_bar()
128
 
 
129
 
        # XXX: Is there any reason why we couldn't make this accept a generator
130
 
        # and build a list as it finds things to copy?
131
 
        ids = list(ids) # Make sure we don't have a generator, since we iterate 2 times
132
 
        pb.update('preparing to copy')
133
 
        to_copy = []
134
 
        for file_id, has in zip(ids, self.has(ids)):
135
 
            if not has:
136
 
                to_copy.append(file_id)
137
 
        return self._do_copy(other, to_copy, pb, permit_failure=permit_failure)
138
 
 
139
 
    def _do_copy(self, other, to_copy, pb, permit_failure=False):
140
 
        """This is the standard copying mechanism, just get them one at
141
 
        a time from remote, and store them locally.
142
 
 
143
 
        :param other: Another Store object
144
 
        :param to_copy: A list of entry ids to copy
145
 
        :param pb: A ProgressBar object to display completion status.
146
 
        :param permit_failure: Allow missing entries to be ignored
147
 
        :return: (n_copied, [failed])
148
 
            The number of entries copied, and a list of failed entries.
149
 
        """
150
 
        # This should be updated to use add_multi() rather than
151
 
        # the current methods of buffering requests.
152
 
        # One question, is it faster to queue up 1-10 and then copy 1-10
153
 
        # then queue up 11-20, copy 11-20
154
 
        # or to queue up 1-10, copy 1, queue 11, copy 2, etc?
155
 
        # sort of pipeline versus batch.
156
 
 
157
 
        # We can't use self._transport.copy_to because we don't know
158
 
        # whether the local tree is in the same format as other
159
 
        failed = set()
160
 
        def buffer_requests():
161
 
            count = 0
162
 
            buffered_requests = []
163
 
            for fileid in to_copy:
164
 
                try:
165
 
                    f = other[fileid]
166
 
                except KeyError:
167
 
                    if permit_failure:
168
 
                        failed.add(fileid)
169
 
                        continue
170
 
                    else:
171
 
                        raise
172
 
 
173
 
                buffered_requests.append((f, fileid))
174
 
                if len(buffered_requests) > self._max_buffered_requests:
175
 
                    yield buffered_requests.pop(0)
176
 
                    count += 1
177
 
                    pb.update('copy', count, len(to_copy))
178
 
 
179
 
            for req in buffered_requests:
180
 
                yield req
181
 
                count += 1
182
 
                pb.update('copy', count, len(to_copy))
183
 
 
184
 
            assert count == len(to_copy)
185
 
 
186
 
        self.add_multi(buffer_requests())
187
 
 
188
 
        pb.clear()
189
 
        return len(to_copy), failed
190
 
 
191
 
 
192
 
class TransportStore(Store):
193
 
    """A TransportStore is a Store superclass for Stores that use Transports."""
194
 
 
195
 
    _max_buffered_requests = 10
196
 
 
197
 
    def __getitem__(self, fileid):
198
 
        """Returns a file reading from a particular entry."""
199
 
        fn = self._relpath(fileid)
200
 
        try:
201
 
            return self._transport.get(fn)
202
 
        except errors.NoSuchFile:
203
 
            raise KeyError(fileid)
204
 
 
205
 
    def __init__(self, transport):
206
 
        assert isinstance(transport, bzrlib.transport.Transport)
207
 
        super(TransportStore, self).__init__()
208
 
        self._transport = transport
209
 
 
210
 
    def __repr__(self):
211
 
        if self._transport is None:
212
 
            return "%s(None)" % (self.__class__.__name__)
 
84
        """Add contents of a file into the store.
 
85
 
 
86
        :param f: An open file, or file-like object."""
 
87
        # FIXME: Only works on smallish files
 
88
        # TODO: Can be optimized by copying at the same time as
 
89
        # computing the sum.
 
90
        mutter("add store entry %r" % (fileid))
 
91
        if isinstance(f, types.StringTypes):
 
92
            content = f
213
93
        else:
214
 
            return "%s(%r)" % (self.__class__.__name__, self._transport.base)
215
 
 
216
 
    __str__ = __repr__
217
 
 
218
 
    def _iter_relpaths(self):
219
 
        """Iter the relative paths of files in the transports sub-tree."""
220
 
        transport = self._transport
221
 
        queue = list(transport.list_dir('.'))
222
 
        while queue:
223
 
            relpath = queue.pop(0)
224
 
            st = transport.stat(relpath)
225
 
            if S_ISDIR(st[ST_MODE]):
226
 
                for i, basename in enumerate(transport.list_dir(relpath)):
227
 
                    queue.insert(i, relpath+'/'+basename)
228
 
            else:
229
 
                yield relpath, st
230
 
 
231
 
    def listable(self):
232
 
        """Return True if this store is able to be listed."""
233
 
        return self._transport.listable()
234
 
 
235
 
 
236
 
class ImmutableMemoryStore(Store):
237
 
    """A memory only store."""
 
94
            content = f.read()
 
95
        if fileid not in self:
 
96
            filename = self._path(fileid)
 
97
            f = file(filename, 'wb')
 
98
            f.write(content)
 
99
            f.flush()
 
100
            os.fsync(f.fileno())
 
101
            f.close()
 
102
            osutils.make_readonly(filename)
 
103
 
238
104
 
239
105
    def __contains__(self, fileid):
240
 
        return self._contents.has_key(fileid)
241
 
 
 
106
        """"""
 
107
        return os.access(self._path(fileid), os.R_OK)
 
108
 
 
109
 
 
110
    def __iter__(self):
 
111
        return iter(os.listdir(self._basedir))
 
112
 
 
113
    def __getitem__(self, fileid):
 
114
        """Returns a file reading from a particular entry."""
 
115
        return file(self._path(fileid), 'rb')
 
116
 
 
117
    def delete_all(self):
 
118
        for fileid in self:
 
119
            self.delete(fileid)
 
120
 
 
121
    def delete(self, fileid):
 
122
        """Remove nominated store entry.
 
123
 
 
124
        Most stores will be add-only."""
 
125
        filename = self._path(fileid)
 
126
        ## osutils.make_writable(filename)
 
127
        os.remove(filename)
 
128
 
 
129
    def destroy(self):
 
130
        """Remove store; only allowed if it is empty."""
 
131
        os.rmdir(self._basedir)
 
132
        mutter("%r destroyed" % self)
 
133
 
 
134
 
 
135
 
 
136
class ImmutableScratchStore(ImmutableStore):
 
137
    """Self-destructing test subclass of ImmutableStore.
 
138
 
 
139
    The Store only exists for the lifetime of the Python object.
 
140
    Obviously you should not put anything precious in it.
 
141
    """
242
142
    def __init__(self):
243
 
        super(ImmutableMemoryStore, self).__init__()
244
 
        self._contents = {}
245
 
 
246
 
    def add(self, stream, fileid, compressed=True):
247
 
        if self._contents.has_key(fileid):
248
 
            raise StoreError("fileid %s already in the store" % fileid)
249
 
        self._contents[fileid] = stream.read()
250
 
 
251
 
    def __getitem__(self, fileid):
252
 
        """Returns a file reading from a particular entry."""
253
 
        if not self._contents.has_key(fileid):
254
 
            raise IndexError
255
 
        return StringIO(self._contents[fileid])
256
 
 
257
 
    def _item_size(self, fileid):
258
 
        return len(self._contents[fileid])
259
 
 
260
 
    def __iter__(self):
261
 
        return iter(self._contents.keys())
262
 
 
263
 
    def total_size(self):
264
 
        result = 0
265
 
        count = 0
266
 
        for fileid in self:
267
 
            count += 1
268
 
            result += self._item_size(fileid)
269
 
        return count, result
270
 
        
271
 
 
272
 
class CachedStore(Store):
273
 
    """A store that caches data locally, to avoid repeated downloads.
274
 
    The precacache method should be used to avoid server round-trips for
275
 
    every piece of data.
276
 
    """
277
 
 
278
 
    def __init__(self, store, cache_dir):
279
 
        super(CachedStore, self).__init__()
280
 
        self.source_store = store
281
 
        # This clones the source store type with a locally bound
282
 
        # transport. FIXME: it assumes a constructor is == cloning.
283
 
        # clonable store - it might be nicer to actually have a clone()
284
 
        # or something. RBC 20051003
285
 
        self.cache_store = store.__class__(LocalTransport(cache_dir))
286
 
 
287
 
    def __getitem__(self, id):
288
 
        mutter("Cache add %s" % id)
289
 
        if id not in self.cache_store:
290
 
            self.cache_store.add(self.source_store[id], id)
291
 
        return self.cache_store[id]
292
 
 
293
 
    def __contains__(self, fileid):
294
 
        if fileid in self.cache_store:
295
 
            return True
296
 
        if fileid in self.source_store:
297
 
            # We could copy at this time
298
 
            return True
299
 
        return False
300
 
 
301
 
    def get(self, fileids, permit_failure=False, pb=None):
302
 
        fileids = list(fileids)
303
 
        hasids = self.cache_store.has(fileids)
304
 
        needs = set()
305
 
        for has, fileid in zip(hasids, fileids):
306
 
            if not has:
307
 
                needs.add(fileid)
308
 
        if needs:
309
 
            self.cache_store.copy_multi(self.source_store, needs,
310
 
                    permit_failure=permit_failure)
311
 
        return self.cache_store.get(fileids,
312
 
                permit_failure=permit_failure, pb=pb)
313
 
 
314
 
    def prefetch(self, ids):
315
 
        """Copy a series of ids into the cache, before they are used.
316
 
        For remote stores that support pipelining or async downloads, this can
317
 
        increase speed considerably.
318
 
 
319
 
        Failures while prefetching are ignored.
320
 
        """
321
 
        mutter("Prefetch of ids %s" % ",".join(ids))
322
 
        self.cache_store.copy_multi(self.source_store, ids, 
323
 
                                    permit_failure=True)
324
 
 
325
 
 
326
 
def copy_all(store_from, store_to):
327
 
    """Copy all ids from one store to another."""
328
 
    # TODO: Optional progress indicator
329
 
    if not store_from.listable():
330
 
        raise UnlistableStore(store_from)
331
 
    ids = [f for f in store_from]
332
 
    store_to.copy_multi(store_from, ids)
333
 
 
334
 
def hash_prefix(file_id):
335
 
    return "%02x/" % (adler32(file_id) & 0xff)
336
 
 
 
143
        ImmutableStore.__init__(self, tempfile.mkdtemp())
 
144
 
 
145
    def __del__(self):
 
146
        self.delete_all()
 
147
        self.destroy()