/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
#
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.
7
#
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.
12
#
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
16
17
from bzrlib.lazy_import import lazy_import
18
lazy_import(globals(), """
19
from itertools import izip
20
import math
21
import md5
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
22
import time
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
23
24
from bzrlib import (
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
25
        debug,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
26
        pack,
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
27
        ui,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
28
        )
29
from bzrlib.index import (
30
    GraphIndex,
31
    GraphIndexBuilder,
32
    InMemoryGraphIndex,
33
    CombinedGraphIndex,
34
    GraphIndexPrefixAdapter,
35
    )
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
36
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
37
from bzrlib.osutils import rand_chars
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
38
from bzrlib.pack import ContainerWriter
39
from bzrlib.store import revision
40
""")
41
from bzrlib import (
42
    bzrdir,
43
    deprecated_graph,
44
    errors,
45
    knit,
46
    lockable_files,
47
    lockdir,
48
    osutils,
49
    transactions,
50
    xml5,
51
    xml7,
52
    )
53
54
from bzrlib.decorators import needs_read_lock, needs_write_lock
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
55
from bzrlib.repofmt.knitrepo import KnitRepository
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
56
from bzrlib.repository import (
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
57
    CommitBuilder,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
58
    MetaDirRepository,
59
    MetaDirRepositoryFormat,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
60
    RootCommitBuilder,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
61
    )
62
import bzrlib.revision as _mod_revision
63
from bzrlib.store.revision.knit import KnitRevisionStore
64
from bzrlib.store.versioned import VersionedFileStore
65
from bzrlib.trace import mutter, note, warning
66
67
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
68
class PackCommitBuilder(CommitBuilder):
69
    """A subclass of CommitBuilder to add texts with pack semantics.
70
    
71
    Specifically this uses one knit object rather than one knit object per
72
    added text, reducing memory and object pressure.
73
    """
74
75
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
76
        return self.repository._pack_collection._add_text_to_weave(file_id,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
77
            self._new_revision_id, new_lines, parents, nostore_sha,
78
            self.random_revid)
79
80
81
class PackRootCommitBuilder(RootCommitBuilder):
82
    """A subclass of RootCommitBuilder to add texts with pack semantics.
83
    
84
    Specifically this uses one knit object rather than one knit object per
85
    added text, reducing memory and object pressure.
86
    """
87
88
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
89
        return self.repository._pack_collection._add_text_to_weave(file_id,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
90
            self._new_revision_id, new_lines, parents, nostore_sha,
91
            self.random_revid)
92
93
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
94
class Pack(object):
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
95
    """An in memory proxy for a pack and its indices.
96
97
    This is a base class that is not directly used, instead the classes
98
    ExistingPack and NewPack are used.
99
    """
100
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
101
    def __init__(self, revision_index, inventory_index, text_index,
102
        signature_index):
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
103
        """Create a pack instance.
104
105
        :param revision_index: A GraphIndex for determining what revisions are
106
            present in the Pack and accessing the locations of their texts.
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
107
        :param inventory_index: A GraphIndex for determining what inventories are
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
108
            present in the Pack and accessing the locations of their
109
            texts/deltas.
110
        :param text_index: A GraphIndex for determining what file texts
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
111
            are present in the pack and accessing the locations of their
112
            texts/deltas (via (fileid, revisionid) tuples).
113
        :param revision_index: A GraphIndex for determining what signatures are
114
            present in the Pack and accessing the locations of their texts.
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
115
        """
116
        self.revision_index = revision_index
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
117
        self.inventory_index = inventory_index
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
118
        self.text_index = text_index
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
119
        self.signature_index = signature_index
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
120
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
121
    def access_tuple(self):
122
        """Return a tuple (transport, name) for the pack content."""
123
        return self.pack_transport, self.file_name()
124
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
125
    def file_name(self):
126
        """Get the file name for the pack on disk."""
127
        return self.name + '.pack'
128
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
129
    def get_revision_count(self):
130
        return self.revision_index.key_count()
131
132
    def inventory_index_name(self, name):
133
        """The inv index is the name + .iix."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
134
        return self.index_name('inventory', name)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
135
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
136
    def revision_index_name(self, name):
137
        """The revision index is the name + .rix."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
138
        return self.index_name('revision', name)
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
139
140
    def signature_index_name(self, name):
141
        """The signature index is the name + .six."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
142
        return self.index_name('signature', name)
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
143
144
    def text_index_name(self, name):
145
        """The text index is the name + .tix."""
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
146
        return self.index_name('text', name)
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
147
148
149
class ExistingPack(Pack):
2592.3.222 by Robert Collins
More review feedback.
150
    """An in memory proxy for an existing .pack and its disk indices."""
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
151
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
152
    def __init__(self, pack_transport, name, revision_index, inventory_index,
2592.3.177 by Robert Collins
Make all parameters to Pack objects mandatory.
153
        text_index, signature_index):
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
154
        """Create an ExistingPack object.
155
156
        :param pack_transport: The transport where the pack file resides.
157
        :param name: The name of the pack on disk in the pack_transport.
158
        """
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
159
        Pack.__init__(self, revision_index, inventory_index, text_index,
160
            signature_index)
2592.3.173 by Robert Collins
Basic implementation of all_packs.
161
        self.name = name
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
162
        self.pack_transport = pack_transport
2592.3.177 by Robert Collins
Make all parameters to Pack objects mandatory.
163
        assert None not in (revision_index, inventory_index, text_index,
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
164
            signature_index, name, pack_transport)
2592.3.173 by Robert Collins
Basic implementation of all_packs.
165
166
    def __eq__(self, other):
167
        return self.__dict__ == other.__dict__
168
169
    def __ne__(self, other):
170
        return not self.__eq__(other)
171
172
    def __repr__(self):
173
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
174
            id(self), self.transport, self.name)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
175
176
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
177
class NewPack(Pack):
178
    """An in memory proxy for a pack which is being created."""
179
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
180
    # A map of index 'type' to the file extension and position in the
181
    # index_sizes array.
2592.3.227 by Martin Pool
Rename NewPack.indices to NewPack.index_definitions
182
    index_definitions = {
2592.3.226 by Martin Pool
formatting and docstrings
183
        'revision': ('.rix', 0),
184
        'inventory': ('.iix', 1),
185
        'text': ('.tix', 2),
186
        'signature': ('.six', 3),
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
187
        }
188
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
189
    def __init__(self, upload_transport, index_transport, pack_transport,
190
        upload_suffix=''):
191
        """Create a NewPack instance.
192
193
        :param upload_transport: A writable transport for the pack to be
194
            incrementally uploaded to.
195
        :param index_transport: A writable transport for the pack's indices to
196
            be written to when the pack is finished.
197
        :param pack_transport: A writable transport for the pack to be renamed
2592.3.206 by Robert Collins
Move pack rename-into-place into NewPack.finish and document hash-collision cases somewhat better.
198
            to when the upload is complete. This *must* be the same as
199
            upload_transport.clone('../packs').
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
200
        :param upload_suffix: An optional suffix to be given to any temporary
201
            files created during the pack creation. e.g '.autopack'
202
        """
2592.3.228 by Martin Pool
docstrings and error messages from review
203
        # The relative locations of the packs are constrained, but all are
204
        # passed in because the caller has them, so as to avoid object churn.
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
205
        Pack.__init__(self,
206
            # Revisions: parents list, no text compression.
207
            InMemoryGraphIndex(reference_lists=1),
208
            # Inventory: We want to map compression only, but currently the
209
            # knit code hasn't been updated enough to understand that, so we
210
            # have a regular 2-list index giving parents and compression
211
            # source.
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
212
            InMemoryGraphIndex(reference_lists=2),
213
            # Texts: compression and per file graph, for all fileids - so two
214
            # reference lists and two elements in the key tuple.
215
            InMemoryGraphIndex(reference_lists=2, key_elements=2),
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
216
            # Signatures: Just blobs to store, no compression, no parents
217
            # listing.
218
            InMemoryGraphIndex(reference_lists=0),
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
219
            )
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
220
        # where should the new pack be opened
221
        self.upload_transport = upload_transport
222
        # where are indices written out to
223
        self.index_transport = index_transport
224
        # where is the pack renamed to when it is finished?
225
        self.pack_transport = pack_transport
2592.3.193 by Robert Collins
Move hash tracking of new packs into NewPack.
226
        # tracks the content written to the .pack file.
227
        self._hash = md5.new()
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
228
        # a four-tuple with the length in bytes of the indices, once the pack
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
229
        # is finalised. (rev, inv, text, sigs)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
230
        self.index_sizes = None
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
231
        # How much data to cache when writing packs. Note that this is not
2592.3.222 by Robert Collins
More review feedback.
232
        # synchronised with reads, because it's not in the transport layer, so
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
233
        # is not safe unless the client knows it won't be reading from the pack
234
        # under creation.
235
        self._cache_limit = 0
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
236
        # the temporary pack file name.
237
        self.random_name = rand_chars(20) + upload_suffix
238
        # when was this pack started ?
239
        self.start_time = time.time()
2592.3.202 by Robert Collins
Move write stream management into NewPack.
240
        # open an output stream for the data added to the pack.
241
        self.write_stream = self.upload_transport.open_write_stream(
242
            self.random_name)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
243
        if 'pack' in debug.debug_flags:
2592.3.202 by Robert Collins
Move write stream management into NewPack.
244
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
245
                time.ctime(), self.upload_transport.base, self.random_name,
246
                time.time() - self.start_time)
2592.3.233 by Martin Pool
Review cleanups
247
        # A list of byte sequences to be written to the new pack, and the 
248
        # aggregate size of them.  Stored as a list rather than separate 
249
        # variables so that the _write_data closure below can update them.
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
250
        self._buffer = [[], 0]
2592.3.233 by Martin Pool
Review cleanups
251
        # create a callable for adding data 
252
        #
253
        # robertc says- this is a closure rather than a method on the object
254
        # so that the variables are locals, and faster than accessing object
255
        # members.
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
256
        def _write_data(bytes, flush=False, _buffer=self._buffer,
257
            _write=self.write_stream.write, _update=self._hash.update):
258
            _buffer[0].append(bytes)
259
            _buffer[1] += len(bytes)
2592.3.222 by Robert Collins
More review feedback.
260
            # buffer cap
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
261
            if _buffer[1] > self._cache_limit or flush:
262
                bytes = ''.join(_buffer[0])
263
                _write(bytes)
264
                _update(bytes)
265
                _buffer[:] = [[], 0]
2592.3.202 by Robert Collins
Move write stream management into NewPack.
266
        # expose this on self, for the occasion when clients want to add data.
267
        self._write_data = _write_data
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
268
        # a pack writer object to serialise pack records.
269
        self._writer = pack.ContainerWriter(self._write_data)
270
        self._writer.begin()
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
271
        # what state is the pack in? (open, finished, aborted)
272
        self._state = 'open'
2592.3.202 by Robert Collins
Move write stream management into NewPack.
273
274
    def abort(self):
275
        """Cancel creating this pack."""
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
276
        self._state = 'aborted'
2592.3.202 by Robert Collins
Move write stream management into NewPack.
277
        # Remove the temporary pack file.
278
        self.upload_transport.delete(self.random_name)
279
        # The indices have no state on disk.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
280
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
281
    def access_tuple(self):
282
        """Return a tuple (transport, name) for the pack content."""
283
        assert self._state in ('open', 'finished')
284
        if self._state == 'finished':
285
            return Pack.access_tuple(self)
286
        else:
287
            return self.upload_transport, self.random_name
288
2592.3.198 by Robert Collins
Factor out data_inserted to reduce code duplication in detecting empty packs.
289
    def data_inserted(self):
290
        """True if data has been added to this pack."""
2592.3.233 by Martin Pool
Review cleanups
291
        return bool(self.get_revision_count() or
292
            self.inventory_index.key_count() or
293
            self.text_index.key_count() or
294
            self.signature_index.key_count())
2592.3.198 by Robert Collins
Factor out data_inserted to reduce code duplication in detecting empty packs.
295
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
296
    def finish(self):
297
        """Finish the new pack.
298
299
        This:
300
         - finalises the content
301
         - assigns a name (the md5 of the content, currently)
302
         - writes out the associated indices
303
         - renames the pack into place.
304
         - stores the index size tuple for the pack in the index_sizes
305
           attribute.
306
        """
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
307
        self._writer.end()
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
308
        if self._buffer[1]:
309
            self._write_data('', flush=True)
2592.3.199 by Robert Collins
Store the name of a NewPack in the object upon finish().
310
        self.name = self._hash.hexdigest()
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
311
        # write indices
2592.3.233 by Martin Pool
Review cleanups
312
        # XXX: It'd be better to write them all to temporary names, then
313
        # rename them all into place, so that the window when only some are
314
        # visible is smaller.  On the other hand none will be seen until
315
        # they're in the names list.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
316
        self.index_sizes = [None, None, None, None]
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
317
        self._write_index('revision', self.revision_index, 'revision')
318
        self._write_index('inventory', self.inventory_index, 'inventory')
319
        self._write_index('text', self.text_index, 'file texts')
320
        self._write_index('signature', self.signature_index,
321
            'revision signatures')
2592.3.202 by Robert Collins
Move write stream management into NewPack.
322
        self.write_stream.close()
2592.3.206 by Robert Collins
Move pack rename-into-place into NewPack.finish and document hash-collision cases somewhat better.
323
        # Note that this will clobber an existing pack with the same name,
324
        # without checking for hash collisions. While this is undesirable this
325
        # is something that can be rectified in a subsequent release. One way
326
        # to rectify it may be to leave the pack at the original name, writing
327
        # its pack-names entry as something like 'HASH: index-sizes
328
        # temporary-name'. Allocate that and check for collisions, if it is
329
        # collision free then rename it into place. If clients know this scheme
330
        # they can handle missing-file errors by:
331
        #  - try for HASH.pack
332
        #  - try for temporary-name
333
        #  - refresh the pack-list to see if the pack is now absent
334
        self.upload_transport.rename(self.random_name,
335
                '../packs/' + self.name + '.pack')
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
336
        self._state = 'finished'
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
337
        if 'pack' in debug.debug_flags:
2592.3.219 by Robert Collins
Review feedback.
338
            # XXX: size might be interesting?
339
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
340
                time.ctime(), self.upload_transport.base, self.random_name,
341
                self.pack_transport, self.name,
342
                time.time() - self.start_time)
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
343
344
    def index_name(self, index_type, name):
345
        """Get the disk name of an index type for pack name 'name'."""
2592.3.227 by Martin Pool
Rename NewPack.indices to NewPack.index_definitions
346
        return name + NewPack.index_definitions[index_type][0]
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
347
348
    def index_offset(self, index_type):
349
        """Get the position in a index_size array for a given index type."""
2592.3.227 by Martin Pool
Rename NewPack.indices to NewPack.index_definitions
350
        return NewPack.index_definitions[index_type][1]
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
351
2592.3.233 by Martin Pool
Review cleanups
352
    def _replace_index_with_readonly(self, index_type):
353
        setattr(self, index_type + '_index',
354
            GraphIndex(self.index_transport,
355
                self.index_name(index_type, self.name),
356
                self.index_sizes[self.index_offset(index_type)]))
357
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
358
    def set_write_cache_size(self, size):
359
        self._cache_limit = size
360
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
361
    def _write_index(self, index_type, index, label):
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
362
        """Write out an index.
363
2592.3.222 by Robert Collins
More review feedback.
364
        :param index_type: The type of index to write - e.g. 'revision'.
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
365
        :param index: The index object to serialise.
366
        :param label: What label to give the index e.g. 'revision'.
367
        """
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
368
        index_name = self.index_name(index_type, self.name)
369
        self.index_sizes[self.index_offset(index_type)] = \
370
            self.index_transport.put_file(index_name, index.finish())
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
371
        if 'pack' in debug.debug_flags:
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
372
            # XXX: size might be interesting?
373
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
374
                time.ctime(), label, self.upload_transport.base,
375
                self.random_name, time.time() - self.start_time)
2592.3.233 by Martin Pool
Review cleanups
376
        # Replace the writable index on this object with a readonly, 
377
        # presently unloaded index. We should alter
378
        # the index layer to make its finish() error if add_node is
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
379
        # subsequently used. RBC
2592.3.233 by Martin Pool
Review cleanups
380
        self._replace_index_with_readonly(index_type)
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
381
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
382
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
383
class AggregateIndex(object):
384
    """An aggregated index for the RepositoryPackCollection.
385
386
    AggregateIndex is reponsible for managing the PackAccess object,
387
    Index-To-Pack mapping, and all indices list for a specific type of index
388
    such as 'revision index'.
2592.3.228 by Martin Pool
docstrings and error messages from review
389
390
    A CombinedIndex provides an index on a single key space built up
391
    from several on-disk indices.  The AggregateIndex builds on this 
392
    to provide a knit access layer, and allows having up to one writable
393
    index within the collection.
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
394
    """
2592.3.235 by Martin Pool
Review cleanups
395
    # XXX: Probably 'can be written to' could/should be separated from 'acts
396
    # like a knit index' -- mbp 20071024
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
397
398
    def __init__(self):
399
        """Create an AggregateIndex."""
400
        self.index_to_pack = {}
401
        self.combined_index = CombinedGraphIndex([])
402
        self.knit_access = _PackAccess(self.index_to_pack)
403
404
    def replace_indices(self, index_to_pack, indices):
405
        """Replace the current mappings with fresh ones.
406
407
        This should probably not be used eventually, rather incremental add and
408
        removal of indices. It has been added during refactoring of existing
409
        code.
410
411
        :param index_to_pack: A mapping from index objects to
412
            (transport, name) tuples for the pack file data.
413
        :param indices: A list of indices.
414
        """
415
        # refresh the revision pack map dict without replacing the instance.
416
        self.index_to_pack.clear()
417
        self.index_to_pack.update(index_to_pack)
418
        # XXX: API break - clearly a 'replace' method would be good?
419
        self.combined_index._indices[:] = indices
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
420
        # the current add nodes callback for the current writable index if
421
        # there is one.
422
        self.add_callback = None
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
423
424
    def add_index(self, index, pack):
425
        """Add index to the aggregate, which is an index for Pack pack.
2592.3.226 by Martin Pool
formatting and docstrings
426
427
        Future searches on the aggregate index will seach this new index
428
        before all previously inserted indices.
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
429
        
2592.3.226 by Martin Pool
formatting and docstrings
430
        :param index: An Index for the pack.
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
431
        :param pack: A Pack instance.
432
        """
433
        # expose it to the index map
434
        self.index_to_pack[index] = pack.access_tuple()
435
        # put it at the front of the linear index list
436
        self.combined_index.insert_index(0, index)
437
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
438
    def add_writable_index(self, index, pack):
439
        """Add an index which is able to have data added to it.
2592.3.235 by Martin Pool
Review cleanups
440
441
        There can be at most one writable index at any time.  Any
442
        modifications made to the knit are put into this index.
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
443
        
444
        :param index: An index from the pack parameter.
445
        :param pack: A Pack instance.
446
        """
2592.3.228 by Martin Pool
docstrings and error messages from review
447
        assert self.add_callback is None, \
448
            "%s already has a writable index through %s" % \
449
            (self, self.add_callback)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
450
        # allow writing: queue writes to a new index
451
        self.add_index(index, pack)
452
        # Updates the index to packs mapping as a side effect,
453
        self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
454
        self.add_callback = index.add_nodes
455
456
    def clear(self):
457
        """Reset all the aggregate data to nothing."""
458
        self.knit_access.set_writer(None, None, (None, None))
459
        self.index_to_pack.clear()
460
        del self.combined_index._indices[:]
461
        self.add_callback = None
462
463
    def remove_index(self, index, pack):
464
        """Remove index from the indices used to answer queries.
465
        
466
        :param index: An index from the pack parameter.
467
        :param pack: A Pack instance.
468
        """
469
        del self.index_to_pack[index]
470
        self.combined_index._indices.remove(index)
471
        if (self.add_callback is not None and
472
            getattr(index, 'add_nodes', None) == self.add_callback):
473
            self.add_callback = None
474
            self.knit_access.set_writer(None, None, (None, None))
475
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
476
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
477
class RepositoryPackCollection(object):
2592.5.2 by Martin Pool
Add docstring
478
    """Management of packs within a repository."""
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
479
2592.5.12 by Martin Pool
Move pack_transport and pack_name onto RepositoryPackCollection
480
    def __init__(self, repo, transport, index_transport, upload_transport,
481
                 pack_transport):
2592.5.5 by Martin Pool
Make RepositoryPackCollection remember the index transport, and responsible for getting a map of indexes
482
        """Create a new RepositoryPackCollection.
483
484
        :param transport: Addresses the repository base directory 
485
            (typically .bzr/repository/).
2592.3.226 by Martin Pool
formatting and docstrings
486
        :param index_transport: Addresses the directory containing indices.
2592.5.11 by Martin Pool
Move upload_transport from pack repositories to the pack collection
487
        :param upload_transport: Addresses the directory into which packs are written
488
            while they're being created.
2592.5.12 by Martin Pool
Move pack_transport and pack_name onto RepositoryPackCollection
489
        :param pack_transport: Addresses the directory of existing complete packs.
2592.5.5 by Martin Pool
Make RepositoryPackCollection remember the index transport, and responsible for getting a map of indexes
490
        """
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
491
        self.repo = repo
492
        self.transport = transport
2592.5.5 by Martin Pool
Make RepositoryPackCollection remember the index transport, and responsible for getting a map of indexes
493
        self._index_transport = index_transport
2592.5.11 by Martin Pool
Move upload_transport from pack repositories to the pack collection
494
        self._upload_transport = upload_transport
2592.5.12 by Martin Pool
Move pack_transport and pack_name onto RepositoryPackCollection
495
        self._pack_transport = pack_transport
2592.3.226 by Martin Pool
formatting and docstrings
496
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
497
        self.packs = []
2592.3.176 by Robert Collins
Various pack refactorings.
498
        # name:Pack mapping
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
499
        self._packs_by_name = {}
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
500
        # the previous pack-names content
501
        self._packs_at_load = None
2592.3.193 by Robert Collins
Move hash tracking of new packs into NewPack.
502
        # when a pack is being created by this object, the state of that pack.
503
        self._new_pack = None
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
504
        # aggregated revision index data
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
505
        self.revision_index = AggregateIndex()
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
506
        self.inventory_index = AggregateIndex()
2592.3.212 by Robert Collins
Cleanup text index management in packs.
507
        self.text_index = AggregateIndex()
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
508
        self.signature_index = AggregateIndex()
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
509
510
    def add_pack_to_memory(self, pack):
511
        """Make a Pack object available to the repository to satisfy queries.
512
        
513
        :param pack: A Pack object.
514
        """
2592.3.235 by Martin Pool
Review cleanups
515
        assert pack.name not in self._packs_by_name
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
516
        self.packs.append(pack)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
517
        self._packs_by_name[pack.name] = pack
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
518
        self.revision_index.add_index(pack.revision_index, pack)
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
519
        self.inventory_index.add_index(pack.inventory_index, pack)
2592.3.212 by Robert Collins
Cleanup text index management in packs.
520
        self.text_index.add_index(pack.text_index, pack)
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
521
        self.signature_index.add_index(pack.signature_index, pack)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
522
        
523
    def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
524
        nostore_sha, random_revid):
525
        file_id_index = GraphIndexPrefixAdapter(
2592.3.212 by Robert Collins
Cleanup text index management in packs.
526
            self.text_index.combined_index,
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
527
            (file_id, ), 1,
2592.3.212 by Robert Collins
Cleanup text index management in packs.
528
            add_nodes_callback=self.text_index.add_callback)
2592.3.135 by Robert Collins
Do not create many transient knit objects, saving 4% on commit.
529
        self.repo._text_knit._index._graph_index = file_id_index
530
        self.repo._text_knit._index._add_callback = file_id_index.add_nodes
531
        return self.repo._text_knit.add_lines_with_ghosts(
532
            revision_id, parents, new_lines, nostore_sha=nostore_sha,
2592.3.137 by Robert Collins
Enable check_content=False for pack commits.
533
            random_id=random_revid, check_content=False)[0:2]
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
534
2592.3.173 by Robert Collins
Basic implementation of all_packs.
535
    def all_packs(self):
536
        """Return a list of all the Pack objects this repository has.
537
2592.3.174 by Robert Collins
Docs for all_packs.
538
        Note that an in-progress pack being created is not returned.
539
2592.3.173 by Robert Collins
Basic implementation of all_packs.
540
        :return: A list of Pack objects for all the packs in the repository.
541
        """
542
        result = []
543
        for name in self.names():
2592.3.176 by Robert Collins
Various pack refactorings.
544
            result.append(self.get_pack_by_name(name))
2592.3.173 by Robert Collins
Basic implementation of all_packs.
545
        return result
546
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
547
    def autopack(self):
548
        """Pack the pack collection incrementally.
549
        
550
        This will not attempt global reorganisation or recompression,
551
        rather it will just ensure that the total number of packs does
552
        not grow without bound. It uses the _max_pack_count method to
553
        determine if autopacking is needed, and the pack_distribution
554
        method to determine the number of revisions in each pack.
555
556
        If autopacking takes place then the packs name collection will have
557
        been flushed to disk - packing requires updating the name collection
558
        in synchronisation with certain steps. Otherwise the names collection
559
        is not flushed.
560
561
        :return: True if packing took place.
562
        """
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
563
        # XXX: Should not be needed when the management of indices is sane.
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
564
        total_revisions = self.revision_index.combined_index.key_count()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
565
        total_packs = len(self._names)
566
        if self._max_pack_count(total_revisions) >= total_packs:
567
            return False
568
        # XXX: the following may want to be a class, to pack with a given
569
        # policy.
570
        mutter('Auto-packing repository %s, which has %d pack files, '
571
            'containing %d revisions into %d packs.', self, total_packs,
572
            total_revisions, self._max_pack_count(total_revisions))
573
        # determine which packs need changing
574
        pack_distribution = self.pack_distribution(total_revisions)
575
        existing_packs = []
2592.3.178 by Robert Collins
Add pack objects to the api for PackCollection.create_pack_from_packs.
576
        for pack in self.all_packs():
577
            revision_count = pack.get_revision_count()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
578
            if revision_count == 0:
579
                # revision less packs are not generated by normal operation,
580
                # only by operations like sign-my-commits, and thus will not
581
                # tend to grow rapdily or without bound like commit containing
582
                # packs do - leave them alone as packing them really should
583
                # group their data with the relevant commit, and that may
584
                # involve rewriting ancient history - which autopack tries to
585
                # avoid. Alternatively we could not group the data but treat
586
                # each of these as having a single revision, and thus add 
587
                # one revision for each to the total revision count, to get
588
                # a matching distribution.
589
                continue
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
590
            existing_packs.append((revision_count, pack))
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
591
        pack_operations = self.plan_autopack_combinations(
592
            existing_packs, pack_distribution)
593
        self._execute_pack_operations(pack_operations)
594
        return True
595
2592.3.182 by Robert Collins
Eliminate the need to use a transport,name tuple to represent a pack during fetch.
596
    def create_pack_from_packs(self, packs, suffix, revision_ids=None):
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
597
        """Create a new pack by reading data from other packs.
598
599
        This does little more than a bulk copy of data. One key difference
600
        is that data with the same item key across multiple packs is elided
601
        from the output. The new pack is written into the current pack store
602
        along with its indices, and the name added to the pack names. The 
2592.3.182 by Robert Collins
Eliminate the need to use a transport,name tuple to represent a pack during fetch.
603
        source packs are not altered and are not required to be in the current
604
        pack collection.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
605
2592.3.178 by Robert Collins
Add pack objects to the api for PackCollection.create_pack_from_packs.
606
        :param packs: An iterable of Packs to combine.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
607
        :param revision_ids: Either None, to copy all data, or a list
608
            of revision_ids to limit the copied data to the data they
609
            introduced.
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
610
        :return: A Pack object, or None if nothing was copied.
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
611
        """
612
        # open a pack - using the same name as the last temporary file
613
        # - which has already been flushed, so its safe.
614
        # XXX: - duplicate code warning with start_write_group; fix before
615
        #      considering 'done'.
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
616
        if self._new_pack is not None:
617
            raise errors.BzrError('call to create_pack_from_packs while '
618
                'another pack is being written.')
2592.3.112 by Robert Collins
Various fixups found dogfooding.
619
        if revision_ids is not None and len(revision_ids) == 0:
620
            # silly fetch request.
621
            return None
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
622
        new_pack = NewPack(self._upload_transport, self._index_transport,
623
            self._pack_transport, upload_suffix=suffix)
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
624
        # buffer data - we won't be reading-back during the pack creation and
625
        # this makes a significant difference on sftp pushes.
626
        new_pack.set_write_cache_size(1024*1024)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
627
        if 'pack' in debug.debug_flags:
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
628
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
2592.3.179 by Robert Collins
Generate the revision_index_map for packing during the core operation, from the pack objects.
629
                for a_pack in packs]
2592.3.112 by Robert Collins
Various fixups found dogfooding.
630
            if revision_ids is not None:
631
                rev_count = len(revision_ids)
632
            else:
633
                rev_count = 'all'
634
            mutter('%s: create_pack: creating pack from source packs: '
635
                '%s%s %s revisions wanted %s t=0',
2592.3.204 by Robert Collins
Remove random_name temporary variables.
636
                time.ctime(), self._upload_transport.base, new_pack.random_name,
2592.3.112 by Robert Collins
Various fixups found dogfooding.
637
                plain_pack_list, rev_count)
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
638
        # select revisions
639
        if revision_ids:
640
            revision_keys = [(revision_id,) for revision_id in revision_ids]
641
        else:
642
            revision_keys = None
2592.3.179 by Robert Collins
Generate the revision_index_map for packing during the core operation, from the pack objects.
643
644
        # select revision keys
645
        revision_index_map = self._packs_list_to_pack_map_and_index_list(
646
            packs, 'revision_index')[0]
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
647
        revision_nodes = self._index_contents(revision_index_map, revision_keys)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
648
        # copy revision keys and adjust values
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
649
        list(self._copy_nodes_graph(revision_nodes, revision_index_map,
650
            new_pack._writer, new_pack.revision_index))
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
651
        if 'pack' in debug.debug_flags:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
652
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
2592.3.204 by Robert Collins
Remove random_name temporary variables.
653
                time.ctime(), self._upload_transport.base, new_pack.random_name,
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
654
                new_pack.revision_index.key_count(),
655
                time.time() - new_pack.start_time)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
656
        # select inventory keys
2592.3.145 by Robert Collins
Fix test_fetch_missing_text_other_location_fails for pack repositories.
657
        inv_keys = revision_keys # currently the same keyspace, and note that
658
        # querying for keys here could introduce a bug where an inventory item
659
        # is missed, so do not change it to query separately without cross
660
        # checking like the text key check below.
2592.3.180 by Robert Collins
Generate the inventory_index_map for packing during the core operation, from the pack objects.
661
        inventory_index_map = self._packs_list_to_pack_map_and_index_list(
662
            packs, 'inventory_index')[0]
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
663
        inv_nodes = self._index_contents(inventory_index_map, inv_keys)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
664
        # copy inventory keys and adjust values
2592.3.104 by Robert Collins
hackish fix, but all tests passing again.
665
        # XXX: Should be a helper function to allow different inv representation
666
        # at this point.
667
        inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
668
            new_pack._writer, new_pack.inventory_index, output_lines=True)
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
669
        if revision_ids:
670
            fileid_revisions = self.repo._find_file_ids_from_xml_inventory_lines(
671
                inv_lines, revision_ids)
672
            text_filter = []
673
            for fileid, file_revids in fileid_revisions.iteritems():
674
                text_filter.extend(
675
                    [(fileid, file_revid) for file_revid in file_revids])
676
        else:
2592.3.145 by Robert Collins
Fix test_fetch_missing_text_other_location_fails for pack repositories.
677
            # eat the iterator to cause it to execute.
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
678
            list(inv_lines)
679
            text_filter = None
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
680
        if 'pack' in debug.debug_flags:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
681
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
2592.3.204 by Robert Collins
Remove random_name temporary variables.
682
                time.ctime(), self._upload_transport.base, new_pack.random_name,
2592.3.195 by Robert Collins
Move some inventory index logic to NewPack.
683
                new_pack.inventory_index.key_count(),
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
684
                time.time() - new_pack.start_time)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
685
        # select text keys
2592.3.181 by Robert Collins
Generate the text_index_map for packing during the core operation, from the pack objects.
686
        text_index_map = self._packs_list_to_pack_map_and_index_list(
687
            packs, 'text_index')[0]
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
688
        text_nodes = self._index_contents(text_index_map, text_filter)
2592.3.149 by Robert Collins
Unbreak pack to pack fetching properly, with missing-text detection really working.
689
        if text_filter is not None:
690
            # We could return the keys copied as part of the return value from
691
            # _copy_nodes_graph but this doesn't work all that well with the
692
            # need to get line output too, so we check separately, and as we're
693
            # going to buffer everything anyway, we check beforehand, which
694
            # saves reading knit data over the wire when we know there are
695
            # mising records.
696
            text_nodes = set(text_nodes)
697
            present_text_keys = set(_node[1] for _node in text_nodes)
698
            missing_text_keys = set(text_filter) - present_text_keys
699
            if missing_text_keys:
700
                # TODO: raise a specific error that can handle many missing
701
                # keys.
702
                a_missing_key = missing_text_keys.pop()
703
                raise errors.RevisionNotPresent(a_missing_key[1],
704
                    a_missing_key[0])
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
705
        # copy text keys and adjust values
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
706
        list(self._copy_nodes_graph(text_nodes, text_index_map,
707
            new_pack._writer, new_pack.text_index))
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
708
        if 'pack' in debug.debug_flags:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
709
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
2592.3.204 by Robert Collins
Remove random_name temporary variables.
710
                time.ctime(), self._upload_transport.base, new_pack.random_name,
2592.3.196 by Robert Collins
Move some text index logic to NewPack.
711
                new_pack.text_index.key_count(),
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
712
                time.time() - new_pack.start_time)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
713
        # select signature keys
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
714
        signature_filter = revision_keys # same keyspace
2592.3.182 by Robert Collins
Eliminate the need to use a transport,name tuple to represent a pack during fetch.
715
        signature_index_map = self._packs_list_to_pack_map_and_index_list(
716
            packs, 'signature_index')[0]
2592.3.110 by Robert Collins
Filter out texts and signatures not referenced by the revisions being copied during pack to pack fetching.
717
        signature_nodes = self._index_contents(signature_index_map,
718
            signature_filter)
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
719
        # copy signature keys and adjust values
2592.3.205 by Robert Collins
Move the pack ContainerWriter instance into NewPack.
720
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
721
            new_pack.signature_index)
2592.3.234 by Martin Pool
Use -Dpack not -Dfetch for pack traces
722
        if 'pack' in debug.debug_flags:
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
723
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
2592.3.204 by Robert Collins
Remove random_name temporary variables.
724
                time.ctime(), self._upload_transport.base, new_pack.random_name,
2592.3.197 by Robert Collins
Hand over signature index creation to NewPack.
725
                new_pack.signature_index.key_count(),
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
726
                time.time() - new_pack.start_time)
2592.3.203 by Robert Collins
Teach NewPack how to buffer for pack operations.
727
        if not new_pack.data_inserted():
728
            new_pack.abort()
729
            return None
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
730
        new_pack.finish()
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
731
        self.allocate(new_pack)
2592.3.206 by Robert Collins
Move pack rename-into-place into NewPack.finish and document hash-collision cases somewhat better.
732
        return new_pack
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
733
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
734
    def _execute_pack_operations(self, pack_operations):
735
        """Execute a series of pack operations.
736
737
        :param pack_operations: A list of [revision_count, packs_to_combine].
738
        :return: None.
739
        """
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
740
        for revision_count, packs in pack_operations:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
741
            # we may have no-ops from the setup logic
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
742
            if len(packs) == 0:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
743
                continue
744
            # have a progress bar?
2592.3.182 by Robert Collins
Eliminate the need to use a transport,name tuple to represent a pack during fetch.
745
            self.create_pack_from_packs(packs, '.autopack')
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
746
            for pack in packs:
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
747
                self._remove_pack_from_memory(pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
748
        # record the newly available packs and stop advertising the old
749
        # packs
2592.5.10 by Martin Pool
Rename RepositoryPackCollection.save to _save_pack_names
750
        self._save_pack_names()
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
751
        # Move the old packs out of the way now they are no longer referenced.
752
        for revision_count, packs in pack_operations:
753
            self._obsolete_packs(packs)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
754
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
755
    def lock_names(self):
756
        """Acquire the mutex around the pack-names index.
757
        
758
        This cannot be used in the middle of a read-only transaction on the
759
        repository.
760
        """
761
        self.repo.control_files.lock_write()
762
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
763
    def pack(self):
764
        """Pack the pack collection totally."""
765
        self.ensure_loaded()
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
766
        total_packs = len(self._names)
767
        if total_packs < 2:
768
            return
769
        total_revisions = self.revision_index.combined_index.key_count()
770
        # XXX: the following may want to be a class, to pack with a given
771
        # policy.
772
        mutter('Packing repository %s, which has %d pack files, '
773
            'containing %d revisions into 1 packs.', self, total_packs,
774
            total_revisions)
775
        # determine which packs need changing
776
        pack_distribution = [1]
777
        pack_operations = [[0, []]]
778
        for pack in self.all_packs():
779
            revision_count = pack.get_revision_count()
780
            pack_operations[-1][0] += revision_count
781
            pack_operations[-1][1].append(pack)
782
        self._execute_pack_operations(pack_operations)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
783
784
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
2592.3.176 by Robert Collins
Various pack refactorings.
785
        """Plan a pack operation.
786
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
787
        :param existing_packs: The packs to pack. (A list of (revcount, Pack)
788
            tuples).
2592.3.235 by Martin Pool
Review cleanups
789
        :param pack_distribution: A list with the number of revisions desired
2592.3.176 by Robert Collins
Various pack refactorings.
790
            in each pack.
791
        """
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
792
        if len(existing_packs) <= len(pack_distribution):
793
            return []
794
        existing_packs.sort(reverse=True)
795
        pack_operations = [[0, []]]
796
        # plan out what packs to keep, and what to reorganise
797
        while len(existing_packs):
798
            # take the largest pack, and if its less than the head of the
799
            # distribution chart we will include its contents in the new pack for
800
            # that position. If its larger, we remove its size from the
801
            # distribution chart
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
802
            next_pack_rev_count, next_pack = existing_packs.pop(0)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
803
            if next_pack_rev_count >= pack_distribution[0]:
804
                # this is already packed 'better' than this, so we can
805
                # not waste time packing it.
806
                while next_pack_rev_count > 0:
807
                    next_pack_rev_count -= pack_distribution[0]
808
                    if next_pack_rev_count >= 0:
809
                        # more to go
810
                        del pack_distribution[0]
811
                    else:
812
                        # didn't use that entire bucket up
813
                        pack_distribution[0] = -next_pack_rev_count
814
            else:
815
                # add the revisions we're going to add to the next output pack
816
                pack_operations[-1][0] += next_pack_rev_count
817
                # allocate this pack to the next pack sub operation
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
818
                pack_operations[-1][1].append(next_pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
819
                if pack_operations[-1][0] >= pack_distribution[0]:
820
                    # this pack is used up, shift left.
821
                    del pack_distribution[0]
822
                    pack_operations.append([0, []])
823
        
824
        return pack_operations
825
826
    def _copy_nodes(self, nodes, index_map, writer, write_index):
827
        # plan a readv on each source pack:
828
        # group by pack
829
        nodes = sorted(nodes)
830
        # how to map this into knit.py - or knit.py into this?
831
        # we don't want the typical knit logic, we want grouping by pack
832
        # at this point - perhaps a helper library for the following code 
833
        # duplication points?
834
        request_groups = {}
835
        for index, key, value in nodes:
836
            if index not in request_groups:
837
                request_groups[index] = []
838
            request_groups[index].append((key, value))
839
        for index, items in request_groups.iteritems():
840
            pack_readv_requests = []
841
            for key, value in items:
842
                # ---- KnitGraphIndex.get_position
843
                bits = value[1:].split(' ')
844
                offset, length = int(bits[0]), int(bits[1])
845
                pack_readv_requests.append((offset, length, (key, value[0])))
846
            # linear scan up the pack
847
            pack_readv_requests.sort()
848
            # copy the data
849
            transport, path = index_map[index]
850
            reader = pack.make_readv_reader(transport, path,
851
                [offset[0:2] for offset in pack_readv_requests])
852
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
853
                izip(reader.iter_records(), pack_readv_requests):
854
                raw_data = read_func(None)
855
                pos, size = writer.add_bytes_record(raw_data, names)
856
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
857
2592.3.104 by Robert Collins
hackish fix, but all tests passing again.
858
    def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
859
        output_lines=False):
860
        """Copy knit nodes between packs.
861
862
        :param output_lines: Return lines present in the copied data as
863
            an iterator.
864
        """
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
865
        # for record verification
866
        knit_data = _KnitData(None)
2592.3.104 by Robert Collins
hackish fix, but all tests passing again.
867
        # for line extraction when requested (inventories only)
868
        if output_lines:
869
            factory = knit.KnitPlainFactory()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
870
        # plan a readv on each source pack:
871
        # group by pack
872
        nodes = sorted(nodes)
873
        # how to map this into knit.py - or knit.py into this?
874
        # we don't want the typical knit logic, we want grouping by pack
875
        # at this point - perhaps a helper library for the following code 
876
        # duplication points?
877
        request_groups = {}
878
        for index, key, value, references in nodes:
879
            if index not in request_groups:
880
                request_groups[index] = []
881
            request_groups[index].append((key, value, references))
882
        for index, items in request_groups.iteritems():
883
            pack_readv_requests = []
884
            for key, value, references in items:
885
                # ---- KnitGraphIndex.get_position
886
                bits = value[1:].split(' ')
887
                offset, length = int(bits[0]), int(bits[1])
888
                pack_readv_requests.append((offset, length, (key, value[0], references)))
889
            # linear scan up the pack
890
            pack_readv_requests.sort()
891
            # copy the data
892
            transport, path = index_map[index]
893
            reader = pack.make_readv_reader(transport, path,
894
                [offset[0:2] for offset in pack_readv_requests])
895
            for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
896
                izip(reader.iter_records(), pack_readv_requests):
897
                raw_data = read_func(None)
2592.3.104 by Robert Collins
hackish fix, but all tests passing again.
898
                if output_lines:
899
                    # read the entire thing
900
                    content, _ = knit_data._parse_record(key[-1], raw_data)
901
                    if len(references[-1]) == 0:
902
                        line_iterator = factory.get_fulltext_content(content)
903
                    else:
904
                        line_iterator = factory.get_linedelta_content(content)
905
                    for line in line_iterator:
906
                        yield line
907
                else:
908
                    # check the header only
909
                    df, _ = knit_data._parse_record_header(key[-1], raw_data)
910
                    df.close()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
911
                pos, size = writer.add_bytes_record(raw_data, names)
912
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
913
914
    def ensure_loaded(self):
2592.3.214 by Robert Collins
Merge bzr.dev.
915
        # NB: if you see an assertion error here, its probably access against
916
        # an unlocked repo. Naughty.
917
        assert self.repo.is_locked()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
918
        if self._names is None:
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
919
            self._names = {}
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
920
            self._packs_at_load = set()
921
            for index, key, value in self._iter_disk_pack_index():
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
922
                name = key[0]
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
923
                self._names[name] = self._parse_index_sizes(value)
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
924
                self._packs_at_load.add((key, value))
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
925
        # populate all the metadata.
926
        self.all_packs()
927
928
    def _parse_index_sizes(self, value):
929
        """Parse a string of index sizes."""
930
        return tuple([int(digits) for digits in value.split(' ')])
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
931
2592.3.176 by Robert Collins
Various pack refactorings.
932
    def get_pack_by_name(self, name):
933
        """Get a Pack object by name.
934
935
        :param name: The name of the pack - e.g. '123456'
936
        :return: A Pack object.
937
        """
938
        try:
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
939
            return self._packs_by_name[name]
2592.3.176 by Robert Collins
Various pack refactorings.
940
        except KeyError:
941
            rev_index = self._make_index(name, '.rix')
942
            inv_index = self._make_index(name, '.iix')
943
            txt_index = self._make_index(name, '.tix')
944
            sig_index = self._make_index(name, '.six')
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
945
            result = ExistingPack(self._pack_transport, name, rev_index,
946
                inv_index, txt_index, sig_index)
2592.3.178 by Robert Collins
Add pack objects to the api for PackCollection.create_pack_from_packs.
947
            self.add_pack_to_memory(result)
2592.3.176 by Robert Collins
Various pack refactorings.
948
            return result
949
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
950
    def allocate(self, a_new_pack):
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
951
        """Allocate name in the list of packs.
952
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
953
        :param a_new_pack: A NewPack instance to be added to the collection of
954
            packs for this repository.
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
955
        """
2592.3.91 by Robert Collins
Incrementally closing in on a correct fetch for packs.
956
        self.ensure_loaded()
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
957
        if a_new_pack.name in self._names:
2592.3.206 by Robert Collins
Move pack rename-into-place into NewPack.finish and document hash-collision cases somewhat better.
958
            # a collision with the packs we know about (not the only possible
959
            # collision, see NewPack.finish() for some discussion). Remove our
960
            # prior reference to it.
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
961
            self._remove_pack_from_memory(a_new_pack)
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
962
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
963
        self.add_pack_to_memory(a_new_pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
964
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
965
    def _iter_disk_pack_index(self):
966
        """Iterate over the contents of the pack-names index.
967
        
968
        This is used when loading the list from disk, and before writing to
969
        detect updates from others during our write operation.
970
        :return: An iterator of the index contents.
971
        """
972
        return GraphIndex(self.transport, 'pack-names', None
973
                ).iter_all_entries()
974
2592.3.176 by Robert Collins
Various pack refactorings.
975
    def _make_index(self, name, suffix):
976
        size_offset = self._suffix_offsets[suffix]
977
        index_name = name + suffix
978
        index_size = self._names[name][size_offset]
979
        return GraphIndex(
980
            self._index_transport, index_name, index_size)
2592.5.5 by Martin Pool
Make RepositoryPackCollection remember the index transport, and responsible for getting a map of indexes
981
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
982
    def _max_pack_count(self, total_revisions):
983
        """Return the maximum number of packs to use for total revisions.
984
        
985
        :param total_revisions: The total number of revisions in the
986
            repository.
987
        """
988
        if not total_revisions:
989
            return 1
990
        digits = str(total_revisions)
991
        result = 0
992
        for digit in digits:
993
            result += int(digit)
994
        return result
995
996
    def names(self):
997
        """Provide an order to the underlying names."""
2592.3.118 by Robert Collins
Record the size of the index files in the pack-names index.
998
        return sorted(self._names.keys())
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
999
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1000
    def _obsolete_packs(self, packs):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1001
        """Move a number of packs which have been obsoleted out of the way.
1002
1003
        Each pack and its associated indices are moved out of the way.
1004
1005
        Note: for correctness this function should only be called after a new
1006
        pack names index has been written without these pack names, and with
1007
        the names of packs that contain the data previously available via these
1008
        packs.
1009
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1010
        :param packs: The packs to obsolete.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1011
        :param return: None.
1012
        """
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1013
        for pack in packs:
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
1014
            pack.pack_transport.rename(pack.file_name(),
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1015
                '../obsolete_packs/' + pack.file_name())
2592.3.226 by Martin Pool
formatting and docstrings
1016
            # TODO: Probably needs to know all possible indices for this pack
1017
            # - or maybe list the directory and move all indices matching this
2592.5.13 by Martin Pool
Clean up duplicate index_transport variables
1018
            # name whether we recognize it or not?
2592.3.187 by Robert Collins
Finish cleaning up the packing logic to take Pack objects - all tests pass.
1019
            for suffix in ('.iix', '.six', '.tix', '.rix'):
1020
                self._index_transport.rename(pack.name + suffix,
1021
                    '../obsolete_packs/' + pack.name + suffix)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1022
1023
    def pack_distribution(self, total_revisions):
1024
        """Generate a list of the number of revisions to put in each pack.
1025
1026
        :param total_revisions: The total number of revisions in the
1027
            repository.
1028
        """
1029
        if total_revisions == 0:
1030
            return [0]
1031
        digits = reversed(str(total_revisions))
1032
        result = []
1033
        for exponent, count in enumerate(digits):
1034
            size = 10 ** exponent
1035
            for pos in range(int(count)):
1036
                result.append(size)
1037
        return list(reversed(result))
1038
2592.5.12 by Martin Pool
Move pack_transport and pack_name onto RepositoryPackCollection
1039
    def _pack_tuple(self, name):
1040
        """Return a tuple with the transport and file name for a pack name."""
1041
        return self._pack_transport, name + '.pack'
1042
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1043
    def _remove_pack_from_memory(self, pack):
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1044
        """Remove pack from the packs accessed by this repository.
1045
        
1046
        Only affects memory state, until self._save_pack_names() is invoked.
1047
        """
1048
        self._names.pop(pack.name)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1049
        self._packs_by_name.pop(pack.name)
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1050
        self._remove_pack_indices(pack)
1051
1052
    def _remove_pack_indices(self, pack):
1053
        """Remove the indices for pack from the aggregated indices."""
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1054
        self.revision_index.remove_index(pack.revision_index, pack)
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1055
        self.inventory_index.remove_index(pack.inventory_index, pack)
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1056
        self.text_index.remove_index(pack.text_index, pack)
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
1057
        self.signature_index.remove_index(pack.signature_index, pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1058
1059
    def reset(self):
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1060
        """Clear all cached data."""
1061
        # cached revision data
1062
        self.repo._revision_knit = None
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1063
        self.revision_index.clear()
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1064
        # cached signature data
1065
        self.repo._signature_knit = None
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
1066
        self.signature_index.clear()
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1067
        # cached file text data
1068
        self.text_index.clear()
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1069
        self.repo._text_knit = None
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1070
        # cached inventory data
1071
        self.inventory_index.clear()
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
1072
        # remove the open pack
1073
        self._new_pack = None
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1074
        # information about packs.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1075
        self._names = None
2592.3.90 by Robert Collins
Slightly broken, but branch and fetch performance is now roughly on par (for bzr.dev) with knits - should be much faster for large repos.
1076
        self.packs = []
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1077
        self._packs_by_name = {}
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1078
        self._packs_at_load = None
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1079
2592.3.207 by Robert Collins
Start removing the dependency on RepositoryPackCollection._make_index_map.
1080
    def _make_index_map(self, index_suffix):
2592.3.226 by Martin Pool
formatting and docstrings
1081
        """Return information on existing indices.
2592.3.207 by Robert Collins
Start removing the dependency on RepositoryPackCollection._make_index_map.
1082
1083
        :param suffix: Index suffix added to pack name.
1084
1085
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
1086
        objects, and pack_map is a mapping from those objects to the 
1087
        pack tuple they describe.
1088
        """
1089
        # TODO: stop using this; it creates new indices unnecessarily.
2592.3.176 by Robert Collins
Various pack refactorings.
1090
        self.ensure_loaded()
2592.3.226 by Martin Pool
formatting and docstrings
1091
        suffix_map = {'.rix': 'revision_index',
1092
            '.six': 'signature_index',
1093
            '.iix': 'inventory_index',
1094
            '.tix': 'text_index',
2592.3.207 by Robert Collins
Start removing the dependency on RepositoryPackCollection._make_index_map.
1095
        }
1096
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1097
            suffix_map[index_suffix])
2592.5.15 by Martin Pool
Split out common code for making index maps
1098
2592.3.179 by Robert Collins
Generate the revision_index_map for packing during the core operation, from the pack objects.
1099
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1100
        """Convert a list of packs to an index pack map and index list.
1101
1102
        :param packs: The packs list to process.
1103
        :param index_attribute: The attribute that the desired index is found
1104
            on.
1105
        :return: A tuple (map, list) where map contains the dict from
1106
            index:pack_tuple, and lsit contains the indices in the same order
1107
            as the packs list.
1108
        """
1109
        indices = []
1110
        pack_map = {}
1111
        for pack in packs:
1112
            index = getattr(pack, index_attribute)
1113
            indices.append(index)
2592.3.200 by Robert Collins
Make NewPack reopen the index files, separating out the task of refreshing the index maps in the repository and managing the completion of writing a single pack to disk.
1114
            pack_map[index] = (pack.pack_transport, pack.file_name())
2592.3.179 by Robert Collins
Generate the revision_index_map for packing during the core operation, from the pack objects.
1115
        return pack_map, indices
1116
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
1117
    def _index_contents(self, pack_map, key_filter=None):
1118
        """Get an iterable of the index contents from a pack_map.
1119
1120
        :param pack_map: A map from indices to pack details.
1121
        :param key_filter: An optional filter to limit the
1122
            keys returned.
1123
        """
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1124
        indices = [index for index in pack_map.iterkeys()]
1125
        all_index = CombinedGraphIndex(indices)
2592.3.93 by Robert Collins
Steps toward filtering revisions/inventories/texts during fetch.
1126
        if key_filter is None:
1127
            return all_index.iter_all_entries()
1128
        else:
1129
            return all_index.iter_entries(key_filter)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1130
2592.3.237 by Martin Pool
Rename RepositoryPackCollection.release_names to _unlock_names
1131
    def _unlock_names(self):
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1132
        """Release the mutex around the pack-names index."""
1133
        self.repo.control_files.unlock()
1134
2592.5.10 by Martin Pool
Rename RepositoryPackCollection.save to _save_pack_names
1135
    def _save_pack_names(self):
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1136
        """Save the list of packs.
1137
1138
        This will take out the mutex around the pack names list for the
1139
        duration of the method call. If concurrent updates have been made, a
1140
        three-way merge between the current list and the current in memory list
1141
        is performed.
1142
        """
1143
        self.lock_names()
1144
        try:
1145
            builder = GraphIndexBuilder()
1146
            # load the disk nodes across
1147
            disk_nodes = set()
1148
            for index, key, value in self._iter_disk_pack_index():
1149
                disk_nodes.add((key, value))
1150
            # do a two-way diff against our original content
1151
            current_nodes = set()
1152
            for name, sizes in self._names.iteritems():
1153
                current_nodes.add(
1154
                    ((name, ), ' '.join(str(size) for size in sizes)))
1155
            deleted_nodes = self._packs_at_load - current_nodes
1156
            new_nodes = current_nodes - self._packs_at_load
1157
            disk_nodes.difference_update(deleted_nodes)
1158
            disk_nodes.update(new_nodes)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1159
            # TODO: handle same-name, index-size-changes here - 
1160
            # e.g. use the value from disk, not ours, *unless* we're the one
1161
            # changing it.
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1162
            for key, value in disk_nodes:
1163
                builder.add_node(key, value)
1164
            self.transport.put_file('pack-names', builder.finish())
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1165
            # move the baseline forward
1166
            self._packs_at_load = disk_nodes
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1167
        finally:
2592.3.237 by Martin Pool
Rename RepositoryPackCollection.release_names to _unlock_names
1168
            self._unlock_names()
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1169
        # synchronise the memory packs list with what we just wrote:
1170
        new_names = dict(disk_nodes)
1171
        # drop no longer present nodes
1172
        for pack in self.all_packs():
1173
            if (pack.name,) not in new_names:
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1174
                self._remove_pack_from_memory(pack)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1175
        # add new nodes/refresh existing ones
1176
        for key, value in disk_nodes:
1177
            name = key[0]
1178
            sizes = self._parse_index_sizes(value)
1179
            if name in self._names:
1180
                # existing
1181
                if sizes != self._names[name]:
1182
                    # the pack for name has had its indices replaced - rare but
1183
                    # important to handle. XXX: probably can never happen today
1184
                    # because the three-way merge code above does not handle it
1185
                    # - you may end up adding the same key twice to the new
1186
                    # disk index because the set values are the same, unless
1187
                    # the only index shows up as deleted by the set difference
1188
                    # - which it may. Until there is a specific test for this,
1189
                    # assume its broken. RBC 20071017.
2592.3.236 by Martin Pool
Make RepositoryPackCollection.remove_pack_from_memory private
1190
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1191
                    self._names[name] = sizes
1192
                    self.get_pack_by_name(name)
1193
            else:
1194
                # new
1195
                self._names[name] = sizes
1196
                self.get_pack_by_name(name)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1197
2592.3.202 by Robert Collins
Move write stream management into NewPack.
1198
    def _start_write_group(self):
2592.3.190 by Robert Collins
Move flush and reset operations to the pack collection rather than the thunk layers.
1199
        # Do not permit preparation for writing if we're not in a 'write lock'.
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1200
        if not self.repo.is_write_locked():
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1201
            raise errors.NotWriteLocked(self)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1202
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
1203
            self._pack_transport, upload_suffix='.pack')
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1204
        # allow writing: queue writes to a new index
1205
        self.revision_index.add_writable_index(self._new_pack.revision_index,
1206
            self._new_pack)
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1207
        self.inventory_index.add_writable_index(self._new_pack.inventory_index,
1208
            self._new_pack)
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1209
        self.text_index.add_writable_index(self._new_pack.text_index,
1210
            self._new_pack)
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
1211
        self.signature_index.add_writable_index(self._new_pack.signature_index,
1212
            self._new_pack)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1213
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1214
        # reused revision and signature knits may need updating
2592.3.238 by Martin Pool
Pack doc updates
1215
        #
1216
        # "Hysterical raisins. client code in bzrlib grabs those knits outside
1217
        # of write groups and then mutates it inside the write group."
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1218
        if self.repo._revision_knit is not None:
1219
            self.repo._revision_knit._index._add_callback = \
1220
                self.revision_index.add_callback
1221
        if self.repo._signature_knit is not None:
1222
            self.repo._signature_knit._index._add_callback = \
1223
                self.signature_index.add_callback
1224
        # create a reused knit object for text addition in commit.
1225
        self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1226
            'all-texts', None)
2592.5.9 by Martin Pool
Move some more bits that seem to belong in RepositoryPackCollection into there
1227
2592.5.8 by Martin Pool
Delegate abort_write_group to RepositoryPackCollection
1228
    def _abort_write_group(self):
1229
        # FIXME: just drop the transient index.
1230
        # forget what names there are
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1231
        self._new_pack.abort()
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1232
        self._remove_pack_indices(self._new_pack)
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1233
        self._new_pack = None
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1234
        self.repo._text_knit = None
2592.5.6 by Martin Pool
Move pack repository start_write_group to pack collection object
1235
2592.5.7 by Martin Pool
move commit_write_group to RepositoryPackCollection
1236
    def _commit_write_group(self):
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1237
        self._remove_pack_indices(self._new_pack)
2592.3.198 by Robert Collins
Factor out data_inserted to reduce code duplication in detecting empty packs.
1238
        if self._new_pack.data_inserted():
2592.3.209 by Robert Collins
Revision index management looking sane for packs.
1239
            # get all the data to disk and read to use
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1240
            self._new_pack.finish()
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
1241
            self.allocate(self._new_pack)
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1242
            self._new_pack = None
2592.5.7 by Martin Pool
move commit_write_group to RepositoryPackCollection
1243
            if not self.autopack():
2592.3.201 by Robert Collins
Cleanup RepositoryPackCollection.allocate.
1244
                # when autopack takes no steps, the names list is still
1245
                # unsaved.
2592.5.10 by Martin Pool
Rename RepositoryPackCollection.save to _save_pack_names
1246
                self._save_pack_names()
2592.5.7 by Martin Pool
move commit_write_group to RepositoryPackCollection
1247
        else:
2592.3.202 by Robert Collins
Move write stream management into NewPack.
1248
            self._new_pack.abort()
2592.3.213 by Robert Collins
Retain packs and indices in memory within a lock, even when write groups are entered and exited.
1249
        self.repo._text_knit = None
2592.5.8 by Martin Pool
Delegate abort_write_group to RepositoryPackCollection
1250
1251
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1252
class KnitPackRevisionStore(KnitRevisionStore):
1253
    """An object to adapt access from RevisionStore's to use KnitPacks.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1254
1255
    This class works by replacing the original RevisionStore.
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1256
    We need to do this because the KnitPackRevisionStore is less
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1257
    isolated in its layering - it uses services from the repo.
1258
    """
1259
1260
    def __init__(self, repo, transport, revisionstore):
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1261
        """Create a KnitPackRevisionStore on repo with revisionstore.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1262
1263
        This will store its state in the Repository, use the
2592.3.238 by Martin Pool
Pack doc updates
1264
        indices to provide a KnitGraphIndex,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1265
        and at the end of transactions write new indices.
1266
        """
1267
        KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1268
        self.repo = repo
1269
        self._serializer = revisionstore._serializer
1270
        self.transport = transport
1271
1272
    def get_revision_file(self, transaction):
1273
        """Get the revision versioned file object."""
1274
        if getattr(self.repo, '_revision_knit', None) is not None:
1275
            return self.repo._revision_knit
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1276
        self.repo._pack_collection.ensure_loaded()
1277
        add_callback = self.repo._pack_collection.revision_index.add_callback
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
1278
        # setup knit specific objects
1279
        knit_index = KnitGraphIndex(
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1280
            self.repo._pack_collection.revision_index.combined_index,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1281
            add_callback=add_callback)
1282
        self.repo._revision_knit = knit.KnitVersionedFile(
1283
            'revisions', self.transport.clone('..'),
1284
            self.repo.control_files._file_mode,
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1285
            create=False, access_mode=self.repo._access_mode(),
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1286
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1287
            access_method=self.repo._pack_collection.revision_index.knit_access)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1288
        return self.repo._revision_knit
1289
1290
    def get_signature_file(self, transaction):
1291
        """Get the signature versioned file object."""
1292
        if getattr(self.repo, '_signature_knit', None) is not None:
1293
            return self.repo._signature_knit
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1294
        self.repo._pack_collection.ensure_loaded()
1295
        add_callback = self.repo._pack_collection.signature_index.add_callback
2592.3.210 by Robert Collins
Signature index management looking sane for packs.
1296
        # setup knit specific objects
1297
        knit_index = KnitGraphIndex(
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1298
            self.repo._pack_collection.signature_index.combined_index,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1299
            add_callback=add_callback, parents=False)
1300
        self.repo._signature_knit = knit.KnitVersionedFile(
1301
            'signatures', self.transport.clone('..'),
1302
            self.repo.control_files._file_mode,
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1303
            create=False, access_mode=self.repo._access_mode(),
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1304
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1305
            access_method=self.repo._pack_collection.signature_index.knit_access)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1306
        return self.repo._signature_knit
1307
1308
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1309
class KnitPackTextStore(VersionedFileStore):
2592.3.238 by Martin Pool
Pack doc updates
1310
    """Presents a TextStore abstraction on top of packs.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1311
1312
    This class works by replacing the original VersionedFileStore.
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1313
    We need to do this because the KnitPackRevisionStore is less
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1314
    isolated in its layering - it uses services from the repo and shares them
1315
    with all the data written in a single write group.
1316
    """
1317
1318
    def __init__(self, repo, transport, weavestore):
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1319
        """Create a KnitPackTextStore on repo with weavestore.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1320
1321
        This will store its state in the Repository, use the
1322
        indices FileNames to provide a KnitGraphIndex,
1323
        and at the end of transactions write new indices.
1324
        """
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1325
        # don't call base class constructor - it's not suitable.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1326
        # no transient data stored in the transaction
1327
        # cache.
1328
        self._precious = False
1329
        self.repo = repo
1330
        self.transport = transport
1331
        self.weavestore = weavestore
1332
        # XXX for check() which isn't updated yet
1333
        self._transport = weavestore._transport
1334
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1335
    def get_weave_or_empty(self, file_id, transaction):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1336
        """Get a 'Knit' backed by the .tix indices.
1337
1338
        The transaction parameter is ignored.
1339
        """
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1340
        self.repo._pack_collection.ensure_loaded()
1341
        add_callback = self.repo._pack_collection.text_index.add_callback
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1342
        # setup knit specific objects
1343
        file_id_index = GraphIndexPrefixAdapter(
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1344
            self.repo._pack_collection.text_index.combined_index,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1345
            (file_id, ), 1, add_nodes_callback=add_callback)
1346
        knit_index = KnitGraphIndex(file_id_index,
1347
            add_callback=file_id_index.add_nodes,
1348
            deltas=True, parents=True)
2592.3.159 by Robert Collins
Provide a transport for KnitVersionedFile's __repr__ in pack repositories.
1349
        return knit.KnitVersionedFile('text:' + file_id,
1350
            self.transport.clone('..'),
2592.3.130 by Robert Collins
Reduce object creation volume during commit.
1351
            None,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1352
            index=knit_index,
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1353
            access_method=self.repo._pack_collection.text_index.knit_access,
2592.3.160 by Robert Collins
Change the packs format to be unannotated.
1354
            factory=knit.KnitPlainFactory())
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1355
1356
    get_weave = get_weave_or_empty
1357
1358
    def __iter__(self):
1359
        """Generate a list of the fileids inserted, for use by check."""
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1360
        self.repo._pack_collection.ensure_loaded()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1361
        ids = set()
2592.3.212 by Robert Collins
Cleanup text index management in packs.
1362
        for index, key, value, refs in \
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1363
            self.repo._pack_collection.text_index.combined_index.iter_all_entries():
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1364
            ids.add(key[0])
1365
        return iter(ids)
1366
1367
1368
class InventoryKnitThunk(object):
1369
    """An object to manage thunking get_inventory_weave to pack based knits."""
1370
1371
    def __init__(self, repo, transport):
1372
        """Create an InventoryKnitThunk for repo at transport.
1373
1374
        This will store its state in the Repository, use the
1375
        indices FileNames to provide a KnitGraphIndex,
1376
        and at the end of transactions write a new index..
1377
        """
1378
        self.repo = repo
1379
        self.transport = transport
1380
1381
    def get_weave(self):
1382
        """Get a 'Knit' that contains inventory data."""
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1383
        self.repo._pack_collection.ensure_loaded()
1384
        add_callback = self.repo._pack_collection.inventory_index.add_callback
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1385
        # setup knit specific objects
1386
        knit_index = KnitGraphIndex(
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1387
            self.repo._pack_collection.inventory_index.combined_index,
2592.3.211 by Robert Collins
Pack inventory index management cleaned up.
1388
            add_callback=add_callback, deltas=True, parents=True)
1389
        return knit.KnitVersionedFile(
1390
            'inventory', self.transport.clone('..'),
1391
            self.repo.control_files._file_mode,
1392
            create=False, access_mode=self.repo._access_mode(),
1393
            index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1394
            access_method=self.repo._pack_collection.inventory_index.knit_access)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1395
1396
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1397
class KnitPackRepository(KnitRepository):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1398
    """Experimental graph-knit using repository."""
1399
1400
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1401
        control_store, text_store, _commit_builder_class, _serializer):
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1402
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1403
            _revision_store, control_store, text_store, _commit_builder_class,
1404
            _serializer)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1405
        index_transport = control_files._transport.clone('indices')
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1406
        self._pack_collection = RepositoryPackCollection(self, control_files._transport,
2592.5.11 by Martin Pool
Move upload_transport from pack repositories to the pack collection
1407
            index_transport,
2592.5.12 by Martin Pool
Move pack_transport and pack_name onto RepositoryPackCollection
1408
            control_files._transport.clone('upload'),
1409
            control_files._transport.clone('packs'))
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1410
        self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1411
        self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1412
        self._inv_thunk = InventoryKnitThunk(self, index_transport)
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1413
        # True when the repository object is 'write locked' (as opposed to the
1414
        # physical lock only taken out around changes to the pack-names list.) 
1415
        # Another way to represent this would be a decorator around the control
1416
        # files object that presents logical locks as physical ones - if this
1417
        # gets ugly consider that alternative design. RBC 20071011
1418
        self._write_lock_count = 0
1419
        self._transaction = None
2592.3.96 by Robert Collins
Merge index improvements (includes bzr.dev).
1420
        # for tests
1421
        self._reconcile_does_inventory_gc = False
2592.3.214 by Robert Collins
Merge bzr.dev.
1422
        self._reconcile_fixes_text_parents = False
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1423
1424
    def _abort_write_group(self):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1425
        self._pack_collection._abort_write_group()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1426
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1427
    def _access_mode(self):
1428
        """Return 'w' or 'r' for depending on whether a write lock is active.
1429
        
1430
        This method is a helper for the Knit-thunking support objects.
1431
        """
1432
        if self.is_write_locked():
1433
            return 'w'
1434
        return 'r'
1435
2592.3.216 by Robert Collins
Implement get_parents and _make_parents_provider for Pack repositories.
1436
    def get_parents(self, revision_ids):
1437
        """See StackedParentsProvider.get_parents.
1438
        
1439
        This implementation accesses the combined revision index to provide
1440
        answers.
1441
        """
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1442
        index = self._pack_collection.revision_index.combined_index
2592.3.216 by Robert Collins
Implement get_parents and _make_parents_provider for Pack repositories.
1443
        search_keys = set()
1444
        for revision_id in revision_ids:
1445
            if revision_id != _mod_revision.NULL_REVISION:
1446
                search_keys.add((revision_id,))
1447
        found_parents = {_mod_revision.NULL_REVISION:[]}
1448
        for index, key, value, refs in index.iter_entries(search_keys):
1449
            parents = refs[0]
1450
            if not parents:
1451
                parents = (_mod_revision.NULL_REVISION,)
1452
            else:
1453
                parents = tuple(parent[0] for parent in parents)
1454
            found_parents[key[0]] = parents
1455
        result = []
1456
        for revision_id in revision_ids:
1457
            try:
1458
                result.append(found_parents[revision_id])
1459
            except KeyError:
1460
                result.append(None)
1461
        return result
1462
1463
    def _make_parents_provider(self):
1464
        return self
1465
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1466
    def _refresh_data(self):
2592.3.225 by Martin Pool
formatting
1467
        if self._write_lock_count == 1 or self.control_files._lock_count == 1:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1468
            # forget what names there are
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1469
            self._pack_collection.reset()
2592.3.219 by Robert Collins
Review feedback.
1470
            # XXX: Better to do an in-memory merge when acquiring a new lock -
1471
            # factor out code from _save_pack_names.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1472
1473
    def _start_write_group(self):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1474
        self._pack_collection._start_write_group()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1475
1476
    def _commit_write_group(self):
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1477
        return self._pack_collection._commit_write_group()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1478
1479
    def get_inventory_weave(self):
1480
        return self._inv_thunk.get_weave()
1481
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1482
    def get_transaction(self):
1483
        if self._write_lock_count:
1484
            return self._transaction
1485
        else:
1486
            return self.control_files.get_transaction()
1487
1488
    def is_locked(self):
1489
        return self._write_lock_count or self.control_files.is_locked()
1490
1491
    def is_write_locked(self):
1492
        return self._write_lock_count
1493
1494
    def lock_write(self, token=None):
1495
        if not self._write_lock_count and self.is_locked():
1496
            raise errors.ReadOnlyError(self)
1497
        self._write_lock_count += 1
1498
        if self._write_lock_count == 1:
1499
            from bzrlib import transactions
1500
            self._transaction = transactions.WriteTransaction()
1501
        self._refresh_data()
1502
1503
    def lock_read(self):
1504
        if self._write_lock_count:
1505
            self._write_lock_count += 1
1506
        else:
1507
            self.control_files.lock_read()
1508
        self._refresh_data()
1509
1510
    def leave_lock_in_place(self):
1511
        # not supported - raise an error
1512
        raise NotImplementedError(self.leave_lock_in_place)
1513
1514
    def dont_leave_lock_in_place(self):
1515
        # not supported - raise an error
1516
        raise NotImplementedError(self.dont_leave_lock_in_place)
1517
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1518
    @needs_write_lock
1519
    def pack(self):
1520
        """Compress the data within the repository.
1521
1522
        This will pack all the data to a single pack. In future it may
1523
        recompress deltas or do other such expensive operations.
1524
        """
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1525
        self._pack_collection.pack()
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1526
1527
    @needs_write_lock
1528
    def reconcile(self, other=None, thorough=False):
1529
        """Reconcile this repository."""
1530
        from bzrlib.reconcile import PackReconciler
1531
        reconciler = PackReconciler(self, thorough=thorough)
1532
        reconciler.reconcile()
1533
        return reconciler
1534
2592.3.188 by Robert Collins
Allow pack repositories to have multiple writers active at one time, for greater concurrency.
1535
    def unlock(self):
1536
        if self._write_lock_count == 1 and self._write_group is not None:
1537
            raise errors.BzrError(
1538
                'Must end write groups before releasing write locks.')
1539
        if self._write_lock_count:
1540
            self._write_lock_count -= 1
1541
            if not self._write_lock_count:
1542
                transaction = self._transaction
1543
                self._transaction = None
1544
                transaction.finish()
1545
        else:
1546
            self.control_files.unlock()
1547
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1548
1549
class RepositoryFormatPack(MetaDirRepositoryFormat):
1550
    """Format logic for pack structured repositories.
1551
1552
    This repository format has:
1553
     - a list of packs in pack-names
1554
     - packs in packs/NAME.pack
1555
     - indices in indices/NAME.{iix,six,tix,rix}
1556
     - knit deltas in the packs, knit indices mapped to the indices.
1557
     - thunk objects to support the knits programming API.
1558
     - a format marker of its own
1559
     - an optional 'shared-storage' flag
1560
     - an optional 'no-working-trees' flag
1561
     - a LockDir lock
1562
    """
1563
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1564
    # Set this attribute in derived classes to control the repository class
1565
    # created by open and initialize.
1566
    repository_class = None
1567
    # Set this attribute in derived classes to control the
1568
    # _commit_builder_class that the repository objects will have passed to
1569
    # their constructor.
1570
    _commit_builder_class = None
1571
    # Set this attribute in derived clases to control the _serializer that the
1572
    # repository objects will have passed to their constructor.
1573
    _serializer = None
1574
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1575
    def _get_control_store(self, repo_transport, control_files):
1576
        """Return the control store for this repository."""
1577
        return VersionedFileStore(
1578
            repo_transport,
1579
            prefixed=False,
1580
            file_mode=control_files._file_mode,
1581
            versionedfile_class=knit.KnitVersionedFile,
2592.3.226 by Martin Pool
formatting and docstrings
1582
            versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1583
            )
1584
1585
    def _get_revision_store(self, repo_transport, control_files):
1586
        """See RepositoryFormat._get_revision_store()."""
1587
        versioned_file_store = VersionedFileStore(
1588
            repo_transport,
1589
            file_mode=control_files._file_mode,
1590
            prefixed=False,
1591
            precious=True,
1592
            versionedfile_class=knit.KnitVersionedFile,
2592.3.226 by Martin Pool
formatting and docstrings
1593
            versionedfile_kwargs={'delta': False,
1594
                                  'factory': knit.KnitPlainFactory(),
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1595
                                 },
1596
            escaped=True,
1597
            )
1598
        return KnitRevisionStore(versioned_file_store)
1599
1600
    def _get_text_store(self, transport, control_files):
1601
        """See RepositoryFormat._get_text_store()."""
1602
        return self._get_versioned_file_store('knits',
1603
                                  transport,
1604
                                  control_files,
1605
                                  versionedfile_class=knit.KnitVersionedFile,
1606
                                  versionedfile_kwargs={
2592.3.226 by Martin Pool
formatting and docstrings
1607
                                      'create_parent_dir': True,
1608
                                      'delay_create': True,
1609
                                      'dir_mode': control_files._dir_mode,
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1610
                                  },
1611
                                  escaped=True)
1612
1613
    def initialize(self, a_bzrdir, shared=False):
1614
        """Create a pack based repository.
1615
1616
        :param a_bzrdir: bzrdir to contain the new repository; must already
1617
            be initialized.
1618
        :param shared: If true the repository will be initialized as a shared
1619
                       repository.
1620
        """
1621
        mutter('creating repository in %s.', a_bzrdir.transport.base)
1622
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1623
        builder = GraphIndexBuilder()
1624
        files = [('pack-names', builder.finish())]
1625
        utf8_files = [('format', self.get_format_string())]
1626
        
1627
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1628
        return self.open(a_bzrdir=a_bzrdir, _found=True)
1629
1630
    def open(self, a_bzrdir, _found=False, _override_transport=None):
1631
        """See RepositoryFormat.open().
1632
        
1633
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
1634
                                    repository at a slightly different url
1635
                                    than normal. I.e. during 'upgrade'.
1636
        """
1637
        if not _found:
1638
            format = RepositoryFormat.find_format(a_bzrdir)
1639
            assert format.__class__ ==  self.__class__
1640
        if _override_transport is not None:
1641
            repo_transport = _override_transport
1642
        else:
1643
            repo_transport = a_bzrdir.get_repository_transport(None)
1644
        control_files = lockable_files.LockableFiles(repo_transport,
1645
                                'lock', lockdir.LockDir)
1646
        text_store = self._get_text_store(repo_transport, control_files)
1647
        control_store = self._get_control_store(repo_transport, control_files)
1648
        _revision_store = self._get_revision_store(repo_transport, control_files)
1649
        return self.repository_class(_format=self,
1650
                              a_bzrdir=a_bzrdir,
1651
                              control_files=control_files,
1652
                              _revision_store=_revision_store,
1653
                              control_store=control_store,
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1654
                              text_store=text_store,
1655
                              _commit_builder_class=self._commit_builder_class,
1656
                              _serializer=self._serializer)
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1657
1658
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1659
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2592.3.215 by Robert Collins
Review feedback.
1660
    """A no-subtrees parameterised Pack repository.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1661
1662
    This format was introduced in bzr.dev.
1663
    """
1664
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1665
    repository_class = KnitPackRepository
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1666
    _commit_builder_class = PackCommitBuilder
1667
    _serializer = xml5.serializer_v5
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1668
1669
    def _get_matching_bzrdir(self):
1670
        return bzrdir.format_registry.make_bzrdir('experimental')
1671
1672
    def _ignore_setting_bzrdir(self, format):
1673
        pass
1674
1675
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1676
1677
    def get_format_string(self):
1678
        """See RepositoryFormat.get_format_string()."""
1679
        return "Bazaar Experimental no-subtrees\n"
1680
1681
    def get_format_description(self):
1682
        """See RepositoryFormat.get_format_description()."""
1683
        return "Experimental no-subtrees"
1684
1685
    def check_conversion_target(self, target_format):
1686
        pass
1687
1688
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1689
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2592.3.215 by Robert Collins
Review feedback.
1690
    """A subtrees parameterised Pack repository.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1691
2592.3.215 by Robert Collins
Review feedback.
1692
    This repository format uses the xml7 serializer to get:
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1693
     - support for recording full info about the tree root
1694
     - support for recording tree-references
2592.3.215 by Robert Collins
Review feedback.
1695
1696
    This format was introduced in bzr.dev.
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1697
    """
1698
2592.3.224 by Martin Pool
Rename GraphKnitRepository etc to KnitPackRepository
1699
    repository_class = KnitPackRepository
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1700
    _commit_builder_class = PackRootCommitBuilder
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1701
    rich_root_data = True
1702
    supports_tree_reference = True
2592.3.166 by Robert Collins
Merge KnitRepository3 removal branch.
1703
    _serializer = xml7.serializer_v7
2592.3.88 by Robert Collins
Move Pack repository logic to bzrlib.repofmt.pack_repo.
1704
1705
    def _get_matching_bzrdir(self):
1706
        return bzrdir.format_registry.make_bzrdir('experimental-subtree')
1707
1708
    def _ignore_setting_bzrdir(self, format):
1709
        pass
1710
1711
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1712
1713
    def check_conversion_target(self, target_format):
1714
        if not target_format.rich_root_data:
1715
            raise errors.BadConversionTarget(
1716
                'Does not support rich root data.', target_format)
1717
        if not getattr(target_format, 'supports_tree_reference', False):
1718
            raise errors.BadConversionTarget(
1719
                'Does not support nested trees', target_format)
1720
            
1721
    def get_format_string(self):
1722
        """See RepositoryFormat.get_format_string()."""
1723
        return "Bazaar Experimental subtrees\n"
1724
1725
    def get_format_description(self):
1726
        """See RepositoryFormat.get_format_description()."""
2592.3.215 by Robert Collins
Review feedback.
1727
        return "Experimental subtrees\n"