/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Martin Pool
  • Date: 2009-12-14 06:06:59 UTC
  • mfrom: (4889 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4891.
  • Revision ID: mbp@sourcefrog.net-20091214060659-1ucv8hpnky0cbnaj
merge trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
import re
 
18
import sys
16
19
 
17
20
from bzrlib.lazy_import import lazy_import
18
21
lazy_import(globals(), """
19
22
from itertools import izip
20
 
import math
21
 
import md5
22
23
import time
23
24
 
24
25
from bzrlib import (
25
 
        debug,
26
 
        graph,
27
 
        pack,
28
 
        ui,
29
 
        )
 
26
    chk_map,
 
27
    debug,
 
28
    graph,
 
29
    osutils,
 
30
    pack,
 
31
    transactions,
 
32
    ui,
 
33
    xml5,
 
34
    xml6,
 
35
    xml7,
 
36
    )
30
37
from bzrlib.index import (
31
 
    GraphIndex,
32
 
    GraphIndexBuilder,
33
 
    InMemoryGraphIndex,
34
38
    CombinedGraphIndex,
35
39
    GraphIndexPrefixAdapter,
36
40
    )
37
 
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
38
 
from bzrlib.osutils import rand_chars
39
 
from bzrlib.pack import ContainerWriter
40
 
from bzrlib.store import revision
 
41
from bzrlib.knit import (
 
42
    KnitPlainFactory,
 
43
    KnitVersionedFiles,
 
44
    _KnitGraphIndex,
 
45
    _DirectPackAccess,
 
46
    )
41
47
from bzrlib import tsort
42
48
""")
43
49
from bzrlib import (
44
50
    bzrdir,
45
51
    errors,
46
 
    knit,
47
52
    lockable_files,
48
53
    lockdir,
49
 
    osutils,
50
 
    symbol_versioning,
51
 
    transactions,
52
 
    xml5,
53
 
    xml6,
54
 
    xml7,
 
54
    revision as _mod_revision,
55
55
    )
56
56
 
57
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
57
from bzrlib.decorators import needs_write_lock, only_raises
 
58
from bzrlib.btree_index import (
 
59
    BTreeGraphIndex,
 
60
    BTreeBuilder,
 
61
    )
 
62
from bzrlib.index import (
 
63
    GraphIndex,
 
64
    InMemoryGraphIndex,
 
65
    )
58
66
from bzrlib.repofmt.knitrepo import KnitRepository
59
67
from bzrlib.repository import (
60
68
    CommitBuilder,
61
 
    MetaDirRepository,
62
69
    MetaDirRepositoryFormat,
63
70
    RepositoryFormat,
64
71
    RootCommitBuilder,
 
72
    StreamSource,
65
73
    )
66
 
import bzrlib.revision as _mod_revision
67
 
from bzrlib.store.revision.knit import KnitRevisionStore
68
 
from bzrlib.store.versioned import VersionedFileStore
69
74
from bzrlib.trace import (
70
75
    mutter,
71
 
    mutter_callsite,
72
76
    note,
73
77
    warning,
74
78
    )
76
80
 
77
81
class PackCommitBuilder(CommitBuilder):
78
82
    """A subclass of CommitBuilder to add texts with pack semantics.
79
 
    
 
83
 
80
84
    Specifically this uses one knit object rather than one knit object per
81
85
    added text, reducing memory and object pressure.
82
86
    """
90
94
        self._file_graph = graph.Graph(
91
95
            repository._pack_collection.text_index.combined_index)
92
96
 
93
 
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
94
 
        return self.repository._pack_collection._add_text_to_weave(file_id,
95
 
            self._new_revision_id, new_lines, parents, nostore_sha,
96
 
            self.random_revid)
97
 
 
98
97
    def _heads(self, file_id, revision_ids):
99
98
        keys = [(file_id, revision_id) for revision_id in revision_ids]
100
99
        return set([key[1] for key in self._file_graph.heads(keys)])
102
101
 
103
102
class PackRootCommitBuilder(RootCommitBuilder):
104
103
    """A subclass of RootCommitBuilder to add texts with pack semantics.
105
 
    
 
104
 
106
105
    Specifically this uses one knit object rather than one knit object per
107
106
    added text, reducing memory and object pressure.
108
107
    """
116
115
        self._file_graph = graph.Graph(
117
116
            repository._pack_collection.text_index.combined_index)
118
117
 
119
 
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
120
 
        return self.repository._pack_collection._add_text_to_weave(file_id,
121
 
            self._new_revision_id, new_lines, parents, nostore_sha,
122
 
            self.random_revid)
123
 
 
124
118
    def _heads(self, file_id, revision_ids):
125
119
        keys = [(file_id, revision_id) for revision_id in revision_ids]
126
120
        return set([key[1] for key in self._file_graph.heads(keys)])
133
127
    ExistingPack and NewPack are used.
134
128
    """
135
129
 
 
130
    # A map of index 'type' to the file extension and position in the
 
131
    # index_sizes array.
 
132
    index_definitions = {
 
133
        'chk': ('.cix', 4),
 
134
        'revision': ('.rix', 0),
 
135
        'inventory': ('.iix', 1),
 
136
        'text': ('.tix', 2),
 
137
        'signature': ('.six', 3),
 
138
        }
 
139
 
136
140
    def __init__(self, revision_index, inventory_index, text_index,
137
 
        signature_index):
 
141
        signature_index, chk_index=None):
138
142
        """Create a pack instance.
139
143
 
140
144
        :param revision_index: A GraphIndex for determining what revisions are
145
149
        :param text_index: A GraphIndex for determining what file texts
146
150
            are present in the pack and accessing the locations of their
147
151
            texts/deltas (via (fileid, revisionid) tuples).
148
 
        :param revision_index: A GraphIndex for determining what signatures are
 
152
        :param signature_index: A GraphIndex for determining what signatures are
149
153
            present in the Pack and accessing the locations of their texts.
 
154
        :param chk_index: A GraphIndex for accessing content by CHK, if the
 
155
            pack has one.
150
156
        """
151
157
        self.revision_index = revision_index
152
158
        self.inventory_index = inventory_index
153
159
        self.text_index = text_index
154
160
        self.signature_index = signature_index
 
161
        self.chk_index = chk_index
155
162
 
156
163
    def access_tuple(self):
157
164
        """Return a tuple (transport, name) for the pack content."""
158
165
        return self.pack_transport, self.file_name()
159
166
 
 
167
    def _check_references(self):
 
168
        """Make sure our external references are present.
 
169
 
 
170
        Packs are allowed to have deltas whose base is not in the pack, but it
 
171
        must be present somewhere in this collection.  It is not allowed to
 
172
        have deltas based on a fallback repository.
 
173
        (See <https://bugs.launchpad.net/bzr/+bug/288751>)
 
174
        """
 
175
        missing_items = {}
 
176
        for (index_name, external_refs, index) in [
 
177
            ('texts',
 
178
                self._get_external_refs(self.text_index),
 
179
                self._pack_collection.text_index.combined_index),
 
180
            ('inventories',
 
181
                self._get_external_refs(self.inventory_index),
 
182
                self._pack_collection.inventory_index.combined_index),
 
183
            ]:
 
184
            missing = external_refs.difference(
 
185
                k for (idx, k, v, r) in
 
186
                index.iter_entries(external_refs))
 
187
            if missing:
 
188
                missing_items[index_name] = sorted(list(missing))
 
189
        if missing_items:
 
190
            from pprint import pformat
 
191
            raise errors.BzrCheckError(
 
192
                "Newly created pack file %r has delta references to "
 
193
                "items not in its repository:\n%s"
 
194
                % (self, pformat(missing_items)))
 
195
 
160
196
    def file_name(self):
161
197
        """Get the file name for the pack on disk."""
162
198
        return self.name + '.pack'
164
200
    def get_revision_count(self):
165
201
        return self.revision_index.key_count()
166
202
 
 
203
    def index_name(self, index_type, name):
 
204
        """Get the disk name of an index type for pack name 'name'."""
 
205
        return name + Pack.index_definitions[index_type][0]
 
206
 
 
207
    def index_offset(self, index_type):
 
208
        """Get the position in a index_size array for a given index type."""
 
209
        return Pack.index_definitions[index_type][1]
 
210
 
167
211
    def inventory_index_name(self, name):
168
212
        """The inv index is the name + .iix."""
169
213
        return self.index_name('inventory', name)
180
224
        """The text index is the name + .tix."""
181
225
        return self.index_name('text', name)
182
226
 
183
 
    def _external_compression_parents_of_texts(self):
184
 
        keys = set()
185
 
        refs = set()
186
 
        for node in self.text_index.iter_all_entries():
187
 
            keys.add(node[1])
188
 
            refs.update(node[3][1])
189
 
        return refs - keys
 
227
    def _replace_index_with_readonly(self, index_type):
 
228
        unlimited_cache = False
 
229
        if index_type == 'chk':
 
230
            unlimited_cache = True
 
231
        setattr(self, index_type + '_index',
 
232
            self.index_class(self.index_transport,
 
233
                self.index_name(index_type, self.name),
 
234
                self.index_sizes[self.index_offset(index_type)],
 
235
                unlimited_cache=unlimited_cache))
190
236
 
191
237
 
192
238
class ExistingPack(Pack):
193
239
    """An in memory proxy for an existing .pack and its disk indices."""
194
240
 
195
241
    def __init__(self, pack_transport, name, revision_index, inventory_index,
196
 
        text_index, signature_index):
 
242
        text_index, signature_index, chk_index=None):
197
243
        """Create an ExistingPack object.
198
244
 
199
245
        :param pack_transport: The transport where the pack file resides.
200
246
        :param name: The name of the pack on disk in the pack_transport.
201
247
        """
202
248
        Pack.__init__(self, revision_index, inventory_index, text_index,
203
 
            signature_index)
 
249
            signature_index, chk_index)
204
250
        self.name = name
205
251
        self.pack_transport = pack_transport
206
252
        if None in (revision_index, inventory_index, text_index,
214
260
        return not self.__eq__(other)
215
261
 
216
262
    def __repr__(self):
217
 
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
218
 
            id(self), self.transport, self.name)
 
263
        return "<%s.%s object at 0x%x, %s, %s" % (
 
264
            self.__class__.__module__, self.__class__.__name__, id(self),
 
265
            self.pack_transport, self.name)
 
266
 
 
267
 
 
268
class ResumedPack(ExistingPack):
 
269
 
 
270
    def __init__(self, name, revision_index, inventory_index, text_index,
 
271
        signature_index, upload_transport, pack_transport, index_transport,
 
272
        pack_collection, chk_index=None):
 
273
        """Create a ResumedPack object."""
 
274
        ExistingPack.__init__(self, pack_transport, name, revision_index,
 
275
            inventory_index, text_index, signature_index,
 
276
            chk_index=chk_index)
 
277
        self.upload_transport = upload_transport
 
278
        self.index_transport = index_transport
 
279
        self.index_sizes = [None, None, None, None]
 
280
        indices = [
 
281
            ('revision', revision_index),
 
282
            ('inventory', inventory_index),
 
283
            ('text', text_index),
 
284
            ('signature', signature_index),
 
285
            ]
 
286
        if chk_index is not None:
 
287
            indices.append(('chk', chk_index))
 
288
            self.index_sizes.append(None)
 
289
        for index_type, index in indices:
 
290
            offset = self.index_offset(index_type)
 
291
            self.index_sizes[offset] = index._size
 
292
        self.index_class = pack_collection._index_class
 
293
        self._pack_collection = pack_collection
 
294
        self._state = 'resumed'
 
295
        # XXX: perhaps check that the .pack file exists?
 
296
 
 
297
    def access_tuple(self):
 
298
        if self._state == 'finished':
 
299
            return Pack.access_tuple(self)
 
300
        elif self._state == 'resumed':
 
301
            return self.upload_transport, self.file_name()
 
302
        else:
 
303
            raise AssertionError(self._state)
 
304
 
 
305
    def abort(self):
 
306
        self.upload_transport.delete(self.file_name())
 
307
        indices = [self.revision_index, self.inventory_index, self.text_index,
 
308
            self.signature_index]
 
309
        if self.chk_index is not None:
 
310
            indices.append(self.chk_index)
 
311
        for index in indices:
 
312
            index._transport.delete(index._name)
 
313
 
 
314
    def finish(self):
 
315
        self._check_references()
 
316
        index_types = ['revision', 'inventory', 'text', 'signature']
 
317
        if self.chk_index is not None:
 
318
            index_types.append('chk')
 
319
        for index_type in index_types:
 
320
            old_name = self.index_name(index_type, self.name)
 
321
            new_name = '../indices/' + old_name
 
322
            self.upload_transport.rename(old_name, new_name)
 
323
            self._replace_index_with_readonly(index_type)
 
324
        new_name = '../packs/' + self.file_name()
 
325
        self.upload_transport.rename(self.file_name(), new_name)
 
326
        self._state = 'finished'
 
327
 
 
328
    def _get_external_refs(self, index):
 
329
        """Return compression parents for this index that are not present.
 
330
 
 
331
        This returns any compression parents that are referenced by this index,
 
332
        which are not contained *in* this index. They may be present elsewhere.
 
333
        """
 
334
        return index.external_references(1)
219
335
 
220
336
 
221
337
class NewPack(Pack):
222
338
    """An in memory proxy for a pack which is being created."""
223
339
 
224
 
    # A map of index 'type' to the file extension and position in the
225
 
    # index_sizes array.
226
 
    index_definitions = {
227
 
        'revision': ('.rix', 0),
228
 
        'inventory': ('.iix', 1),
229
 
        'text': ('.tix', 2),
230
 
        'signature': ('.six', 3),
231
 
        }
232
 
 
233
 
    def __init__(self, upload_transport, index_transport, pack_transport,
234
 
        upload_suffix='', file_mode=None):
 
340
    def __init__(self, pack_collection, upload_suffix='', file_mode=None):
235
341
        """Create a NewPack instance.
236
342
 
237
 
        :param upload_transport: A writable transport for the pack to be
238
 
            incrementally uploaded to.
239
 
        :param index_transport: A writable transport for the pack's indices to
240
 
            be written to when the pack is finished.
241
 
        :param pack_transport: A writable transport for the pack to be renamed
242
 
            to when the upload is complete. This *must* be the same as
243
 
            upload_transport.clone('../packs').
 
343
        :param pack_collection: A PackCollection into which this is being inserted.
244
344
        :param upload_suffix: An optional suffix to be given to any temporary
245
345
            files created during the pack creation. e.g '.autopack'
246
 
        :param file_mode: An optional file mode to create the new files with.
 
346
        :param file_mode: Unix permissions for newly created file.
247
347
        """
248
348
        # The relative locations of the packs are constrained, but all are
249
349
        # passed in because the caller has them, so as to avoid object churn.
 
350
        index_builder_class = pack_collection._index_builder_class
 
351
        if pack_collection.chk_index is not None:
 
352
            chk_index = index_builder_class(reference_lists=0)
 
353
        else:
 
354
            chk_index = None
250
355
        Pack.__init__(self,
251
356
            # Revisions: parents list, no text compression.
252
 
            InMemoryGraphIndex(reference_lists=1),
 
357
            index_builder_class(reference_lists=1),
253
358
            # Inventory: We want to map compression only, but currently the
254
359
            # knit code hasn't been updated enough to understand that, so we
255
360
            # have a regular 2-list index giving parents and compression
256
361
            # source.
257
 
            InMemoryGraphIndex(reference_lists=2),
 
362
            index_builder_class(reference_lists=2),
258
363
            # Texts: compression and per file graph, for all fileids - so two
259
364
            # reference lists and two elements in the key tuple.
260
 
            InMemoryGraphIndex(reference_lists=2, key_elements=2),
 
365
            index_builder_class(reference_lists=2, key_elements=2),
261
366
            # Signatures: Just blobs to store, no compression, no parents
262
367
            # listing.
263
 
            InMemoryGraphIndex(reference_lists=0),
 
368
            index_builder_class(reference_lists=0),
 
369
            # CHK based storage - just blobs, no compression or parents.
 
370
            chk_index=chk_index
264
371
            )
 
372
        self._pack_collection = pack_collection
 
373
        # When we make readonly indices, we need this.
 
374
        self.index_class = pack_collection._index_class
265
375
        # where should the new pack be opened
266
 
        self.upload_transport = upload_transport
 
376
        self.upload_transport = pack_collection._upload_transport
267
377
        # where are indices written out to
268
 
        self.index_transport = index_transport
 
378
        self.index_transport = pack_collection._index_transport
269
379
        # where is the pack renamed to when it is finished?
270
 
        self.pack_transport = pack_transport
 
380
        self.pack_transport = pack_collection._pack_transport
271
381
        # What file mode to upload the pack and indices with.
272
382
        self._file_mode = file_mode
273
383
        # tracks the content written to the .pack file.
274
 
        self._hash = md5.new()
275
 
        # a four-tuple with the length in bytes of the indices, once the pack
276
 
        # is finalised. (rev, inv, text, sigs)
 
384
        self._hash = osutils.md5()
 
385
        # a tuple with the length in bytes of the indices, once the pack
 
386
        # is finalised. (rev, inv, text, sigs, chk_if_in_use)
277
387
        self.index_sizes = None
278
388
        # How much data to cache when writing packs. Note that this is not
279
389
        # synchronised with reads, because it's not in the transport layer, so
281
391
        # under creation.
282
392
        self._cache_limit = 0
283
393
        # the temporary pack file name.
284
 
        self.random_name = rand_chars(20) + upload_suffix
 
394
        self.random_name = osutils.rand_chars(20) + upload_suffix
285
395
        # when was this pack started ?
286
396
        self.start_time = time.time()
287
397
        # open an output stream for the data added to the pack.
291
401
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
292
402
                time.ctime(), self.upload_transport.base, self.random_name,
293
403
                time.time() - self.start_time)
294
 
        # A list of byte sequences to be written to the new pack, and the 
295
 
        # aggregate size of them.  Stored as a list rather than separate 
 
404
        # A list of byte sequences to be written to the new pack, and the
 
405
        # aggregate size of them.  Stored as a list rather than separate
296
406
        # variables so that the _write_data closure below can update them.
297
407
        self._buffer = [[], 0]
298
 
        # create a callable for adding data 
 
408
        # create a callable for adding data
299
409
        #
300
410
        # robertc says- this is a closure rather than a method on the object
301
411
        # so that the variables are locals, and faster than accessing object
317
427
        self._writer.begin()
318
428
        # what state is the pack in? (open, finished, aborted)
319
429
        self._state = 'open'
 
430
        # no name until we finish writing the content
 
431
        self.name = None
320
432
 
321
433
    def abort(self):
322
434
        """Cancel creating this pack."""
340
452
        return bool(self.get_revision_count() or
341
453
            self.inventory_index.key_count() or
342
454
            self.text_index.key_count() or
343
 
            self.signature_index.key_count())
344
 
 
345
 
    def finish(self):
 
455
            self.signature_index.key_count() or
 
456
            (self.chk_index is not None and self.chk_index.key_count()))
 
457
 
 
458
    def finish_content(self):
 
459
        if self.name is not None:
 
460
            return
 
461
        self._writer.end()
 
462
        if self._buffer[1]:
 
463
            self._write_data('', flush=True)
 
464
        self.name = self._hash.hexdigest()
 
465
 
 
466
    def finish(self, suspend=False):
346
467
        """Finish the new pack.
347
468
 
348
469
        This:
353
474
         - stores the index size tuple for the pack in the index_sizes
354
475
           attribute.
355
476
        """
356
 
        self._writer.end()
357
 
        if self._buffer[1]:
358
 
            self._write_data('', flush=True)
359
 
        self.name = self._hash.hexdigest()
 
477
        self.finish_content()
 
478
        if not suspend:
 
479
            self._check_references()
360
480
        # write indices
361
481
        # XXX: It'd be better to write them all to temporary names, then
362
482
        # rename them all into place, so that the window when only some are
363
483
        # visible is smaller.  On the other hand none will be seen until
364
484
        # they're in the names list.
365
485
        self.index_sizes = [None, None, None, None]
366
 
        self._write_index('revision', self.revision_index, 'revision')
367
 
        self._write_index('inventory', self.inventory_index, 'inventory')
368
 
        self._write_index('text', self.text_index, 'file texts')
 
486
        self._write_index('revision', self.revision_index, 'revision', suspend)
 
487
        self._write_index('inventory', self.inventory_index, 'inventory',
 
488
            suspend)
 
489
        self._write_index('text', self.text_index, 'file texts', suspend)
369
490
        self._write_index('signature', self.signature_index,
370
 
            'revision signatures')
 
491
            'revision signatures', suspend)
 
492
        if self.chk_index is not None:
 
493
            self.index_sizes.append(None)
 
494
            self._write_index('chk', self.chk_index,
 
495
                'content hash bytes', suspend)
371
496
        self.write_stream.close()
372
497
        # Note that this will clobber an existing pack with the same name,
373
498
        # without checking for hash collisions. While this is undesirable this
380
505
        #  - try for HASH.pack
381
506
        #  - try for temporary-name
382
507
        #  - refresh the pack-list to see if the pack is now absent
383
 
        self.upload_transport.rename(self.random_name,
384
 
                '../packs/' + self.name + '.pack')
 
508
        new_name = self.name + '.pack'
 
509
        if not suspend:
 
510
            new_name = '../packs/' + new_name
 
511
        self.upload_transport.rename(self.random_name, new_name)
385
512
        self._state = 'finished'
386
513
        if 'pack' in debug.debug_flags:
387
514
            # XXX: size might be interesting?
388
 
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
 
515
            mutter('%s: create_pack: pack finished: %s%s->%s t+%6.3fs',
389
516
                time.ctime(), self.upload_transport.base, self.random_name,
390
 
                self.pack_transport, self.name,
391
 
                time.time() - self.start_time)
 
517
                new_name, time.time() - self.start_time)
392
518
 
393
519
    def flush(self):
394
520
        """Flush any current data."""
398
524
            self._hash.update(bytes)
399
525
            self._buffer[:] = [[], 0]
400
526
 
401
 
    def index_name(self, index_type, name):
402
 
        """Get the disk name of an index type for pack name 'name'."""
403
 
        return name + NewPack.index_definitions[index_type][0]
404
 
 
405
 
    def index_offset(self, index_type):
406
 
        """Get the position in a index_size array for a given index type."""
407
 
        return NewPack.index_definitions[index_type][1]
408
 
 
409
 
    def _replace_index_with_readonly(self, index_type):
410
 
        setattr(self, index_type + '_index',
411
 
            GraphIndex(self.index_transport,
412
 
                self.index_name(index_type, self.name),
413
 
                self.index_sizes[self.index_offset(index_type)]))
 
527
    def _get_external_refs(self, index):
 
528
        return index._external_references()
414
529
 
415
530
    def set_write_cache_size(self, size):
416
531
        self._cache_limit = size
417
532
 
418
 
    def _write_index(self, index_type, index, label):
 
533
    def _write_index(self, index_type, index, label, suspend=False):
419
534
        """Write out an index.
420
535
 
421
536
        :param index_type: The type of index to write - e.g. 'revision'.
423
538
        :param label: What label to give the index e.g. 'revision'.
424
539
        """
425
540
        index_name = self.index_name(index_type, self.name)
426
 
        self.index_sizes[self.index_offset(index_type)] = \
427
 
            self.index_transport.put_file(index_name, index.finish(),
428
 
            mode=self._file_mode)
 
541
        if suspend:
 
542
            transport = self.upload_transport
 
543
        else:
 
544
            transport = self.index_transport
 
545
        self.index_sizes[self.index_offset(index_type)] = transport.put_file(
 
546
            index_name, index.finish(), mode=self._file_mode)
429
547
        if 'pack' in debug.debug_flags:
430
548
            # XXX: size might be interesting?
431
549
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
432
550
                time.ctime(), label, self.upload_transport.base,
433
551
                self.random_name, time.time() - self.start_time)
434
 
        # Replace the writable index on this object with a readonly, 
 
552
        # Replace the writable index on this object with a readonly,
435
553
        # presently unloaded index. We should alter
436
554
        # the index layer to make its finish() error if add_node is
437
555
        # subsequently used. RBC
446
564
    such as 'revision index'.
447
565
 
448
566
    A CombinedIndex provides an index on a single key space built up
449
 
    from several on-disk indices.  The AggregateIndex builds on this 
 
567
    from several on-disk indices.  The AggregateIndex builds on this
450
568
    to provide a knit access layer, and allows having up to one writable
451
569
    index within the collection.
452
570
    """
453
571
    # XXX: Probably 'can be written to' could/should be separated from 'acts
454
572
    # like a knit index' -- mbp 20071024
455
573
 
456
 
    def __init__(self):
457
 
        """Create an AggregateIndex."""
 
574
    def __init__(self, reload_func=None, flush_func=None):
 
575
        """Create an AggregateIndex.
 
576
 
 
577
        :param reload_func: A function to call if we find we are missing an
 
578
            index. Should have the form reload_func() => True if the list of
 
579
            active pack files has changed.
 
580
        """
 
581
        self._reload_func = reload_func
458
582
        self.index_to_pack = {}
459
 
        self.combined_index = CombinedGraphIndex([])
460
 
        self.knit_access = _PackAccess(self.index_to_pack)
 
583
        self.combined_index = CombinedGraphIndex([], reload_func=reload_func)
 
584
        self.data_access = _DirectPackAccess(self.index_to_pack,
 
585
                                             reload_func=reload_func,
 
586
                                             flush_func=flush_func)
 
587
        self.add_callback = None
461
588
 
462
589
    def replace_indices(self, index_to_pack, indices):
463
590
        """Replace the current mappings with fresh ones.
484
611
 
485
612
        Future searches on the aggregate index will seach this new index
486
613
        before all previously inserted indices.
487
 
        
 
614
 
488
615
        :param index: An Index for the pack.
489
616
        :param pack: A Pack instance.
490
617
        """
498
625
 
499
626
        There can be at most one writable index at any time.  Any
500
627
        modifications made to the knit are put into this index.
501
 
        
 
628
 
502
629
        :param index: An index from the pack parameter.
503
630
        :param pack: A Pack instance.
504
631
        """
509
636
        # allow writing: queue writes to a new index
510
637
        self.add_index(index, pack)
511
638
        # Updates the index to packs mapping as a side effect,
512
 
        self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
 
639
        self.data_access.set_writer(pack._writer, index, pack.access_tuple())
513
640
        self.add_callback = index.add_nodes
514
641
 
515
642
    def clear(self):
516
643
        """Reset all the aggregate data to nothing."""
517
 
        self.knit_access.set_writer(None, None, (None, None))
 
644
        self.data_access.set_writer(None, None, (None, None))
518
645
        self.index_to_pack.clear()
519
646
        del self.combined_index._indices[:]
520
647
        self.add_callback = None
521
648
 
522
649
    def remove_index(self, index, pack):
523
650
        """Remove index from the indices used to answer queries.
524
 
        
 
651
 
525
652
        :param index: An index from the pack parameter.
526
653
        :param pack: A Pack instance.
527
654
        """
530
657
        if (self.add_callback is not None and
531
658
            getattr(index, 'add_nodes', None) == self.add_callback):
532
659
            self.add_callback = None
533
 
            self.knit_access.set_writer(None, None, (None, None))
 
660
            self.data_access.set_writer(None, None, (None, None))
534
661
 
535
662
 
536
663
class Packer(object):
537
664
    """Create a pack from packs."""
538
665
 
539
 
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
 
666
    def __init__(self, pack_collection, packs, suffix, revision_ids=None,
 
667
                 reload_func=None):
540
668
        """Create a Packer.
541
669
 
542
670
        :param pack_collection: A RepositoryPackCollection object where the
544
672
        :param packs: The packs to combine.
545
673
        :param suffix: The suffix to use on the temporary files for the pack.
546
674
        :param revision_ids: Revision ids to limit the pack to.
 
675
        :param reload_func: A function to call if a pack file/index goes
 
676
            missing. The side effect of calling this function should be to
 
677
            update self.packs. See also AggregateIndex
547
678
        """
548
679
        self.packs = packs
549
680
        self.suffix = suffix
551
682
        # The pack object we are creating.
552
683
        self.new_pack = None
553
684
        self._pack_collection = pack_collection
 
685
        self._reload_func = reload_func
554
686
        # The index layer keys for the revisions being copied. None for 'all
555
687
        # objects'.
556
688
        self._revision_keys = None
562
694
    def _extra_init(self):
563
695
        """A template hook to allow extending the constructor trivially."""
564
696
 
 
697
    def _pack_map_and_index_list(self, index_attribute):
 
698
        """Convert a list of packs to an index pack map and index list.
 
699
 
 
700
        :param index_attribute: The attribute that the desired index is found
 
701
            on.
 
702
        :return: A tuple (map, list) where map contains the dict from
 
703
            index:pack_tuple, and list contains the indices in the preferred
 
704
            access order.
 
705
        """
 
706
        indices = []
 
707
        pack_map = {}
 
708
        for pack_obj in self.packs:
 
709
            index = getattr(pack_obj, index_attribute)
 
710
            indices.append(index)
 
711
            pack_map[index] = pack_obj
 
712
        return pack_map, indices
 
713
 
 
714
    def _index_contents(self, indices, key_filter=None):
 
715
        """Get an iterable of the index contents from a pack_map.
 
716
 
 
717
        :param indices: The list of indices to query
 
718
        :param key_filter: An optional filter to limit the keys returned.
 
719
        """
 
720
        all_index = CombinedGraphIndex(indices)
 
721
        if key_filter is None:
 
722
            return all_index.iter_all_entries()
 
723
        else:
 
724
            return all_index.iter_entries(key_filter)
 
725
 
565
726
    def pack(self, pb=None):
566
727
        """Create a new pack by reading data from other packs.
567
728
 
568
729
        This does little more than a bulk copy of data. One key difference
569
730
        is that data with the same item key across multiple packs is elided
570
731
        from the output. The new pack is written into the current pack store
571
 
        along with its indices, and the name added to the pack names. The 
 
732
        along with its indices, and the name added to the pack names. The
572
733
        source packs are not altered and are not required to be in the current
573
734
        pack collection.
574
735
 
581
742
        # XXX: - duplicate code warning with start_write_group; fix before
582
743
        #      considering 'done'.
583
744
        if self._pack_collection._new_pack is not None:
584
 
            raise errors.BzrError('call to create_pack_from_packs while '
585
 
                'another pack is being written.')
 
745
            raise errors.BzrError('call to %s.pack() while another pack is'
 
746
                                  ' being written.'
 
747
                                  % (self.__class__.__name__,))
586
748
        if self.revision_ids is not None:
587
749
            if len(self.revision_ids) == 0:
588
750
                # silly fetch request.
589
751
                return None
590
752
            else:
591
753
                self.revision_ids = frozenset(self.revision_ids)
 
754
                self.revision_keys = frozenset((revid,) for revid in
 
755
                    self.revision_ids)
592
756
        if pb is None:
593
757
            self.pb = ui.ui_factory.nested_progress_bar()
594
758
        else:
601
765
 
602
766
    def open_pack(self):
603
767
        """Open a pack for the pack we are creating."""
604
 
        return NewPack(self._pack_collection._upload_transport,
605
 
            self._pack_collection._index_transport,
606
 
            self._pack_collection._pack_transport, upload_suffix=self.suffix,
607
 
            file_mode=self._pack_collection.repo.control_files._file_mode)
 
768
        new_pack = self._pack_collection.pack_factory(self._pack_collection,
 
769
                upload_suffix=self.suffix,
 
770
                file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
 
771
        # We know that we will process all nodes in order, and don't need to
 
772
        # query, so don't combine any indices spilled to disk until we are done
 
773
        new_pack.revision_index.set_optimize(combine_backing_indices=False)
 
774
        new_pack.inventory_index.set_optimize(combine_backing_indices=False)
 
775
        new_pack.text_index.set_optimize(combine_backing_indices=False)
 
776
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
 
777
        return new_pack
 
778
 
 
779
    def _update_pack_order(self, entries, index_to_pack_map):
 
780
        """Determine how we want our packs to be ordered.
 
781
 
 
782
        This changes the sort order of the self.packs list so that packs unused
 
783
        by 'entries' will be at the end of the list, so that future requests
 
784
        can avoid probing them.  Used packs will be at the front of the
 
785
        self.packs list, in the order of their first use in 'entries'.
 
786
 
 
787
        :param entries: A list of (index, ...) tuples
 
788
        :param index_to_pack_map: A mapping from index objects to pack objects.
 
789
        """
 
790
        packs = []
 
791
        seen_indexes = set()
 
792
        for entry in entries:
 
793
            index = entry[0]
 
794
            if index not in seen_indexes:
 
795
                packs.append(index_to_pack_map[index])
 
796
                seen_indexes.add(index)
 
797
        if len(packs) == len(self.packs):
 
798
            if 'pack' in debug.debug_flags:
 
799
                mutter('Not changing pack list, all packs used.')
 
800
            return
 
801
        seen_packs = set(packs)
 
802
        for pack in self.packs:
 
803
            if pack not in seen_packs:
 
804
                packs.append(pack)
 
805
                seen_packs.add(pack)
 
806
        if 'pack' in debug.debug_flags:
 
807
            old_names = [p.access_tuple()[1] for p in self.packs]
 
808
            new_names = [p.access_tuple()[1] for p in packs]
 
809
            mutter('Reordering packs\nfrom: %s\n  to: %s',
 
810
                   old_names, new_names)
 
811
        self.packs = packs
608
812
 
609
813
    def _copy_revision_texts(self):
610
814
        """Copy revision data to the new pack."""
614
818
        else:
615
819
            revision_keys = None
616
820
        # select revision keys
617
 
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
618
 
            self.packs, 'revision_index')[0]
619
 
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
 
821
        revision_index_map, revision_indices = self._pack_map_and_index_list(
 
822
            'revision_index')
 
823
        revision_nodes = self._index_contents(revision_indices, revision_keys)
 
824
        revision_nodes = list(revision_nodes)
 
825
        self._update_pack_order(revision_nodes, revision_index_map)
620
826
        # copy revision keys and adjust values
621
827
        self.pb.update("Copying revision texts", 1)
622
828
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
642
848
        # querying for keys here could introduce a bug where an inventory item
643
849
        # is missed, so do not change it to query separately without cross
644
850
        # checking like the text key check below.
645
 
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
646
 
            self.packs, 'inventory_index')[0]
647
 
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
 
851
        inventory_index_map, inventory_indices = self._pack_map_and_index_list(
 
852
            'inventory_index')
 
853
        inv_nodes = self._index_contents(inventory_indices, inv_keys)
648
854
        # copy inventory keys and adjust values
649
855
        # XXX: Should be a helper function to allow different inv representation
650
856
        # at this point.
684
890
            if missing_text_keys:
685
891
                # TODO: raise a specific error that can handle many missing
686
892
                # keys.
 
893
                mutter("missing keys during fetch: %r", missing_text_keys)
687
894
                a_missing_key = missing_text_keys.pop()
688
895
                raise errors.RevisionNotPresent(a_missing_key[1],
689
896
                    a_missing_key[0])
694
901
            self.new_pack.text_index, readv_group_iter, total_items))
695
902
        self._log_copied_texts()
696
903
 
697
 
    def _check_references(self):
698
 
        """Make sure our external refereneces are present."""
699
 
        external_refs = self.new_pack._external_compression_parents_of_texts()
700
 
        if external_refs:
701
 
            index = self._pack_collection.text_index.combined_index
702
 
            found_items = list(index.iter_entries(external_refs))
703
 
            if len(found_items) != len(external_refs):
704
 
                found_keys = set(k for idx, k, refs, value in found_items)
705
 
                missing_items = external_refs - found_keys
706
 
                missing_file_id, missing_revision_id = missing_items.pop()
707
 
                raise errors.RevisionNotPresent(missing_revision_id,
708
 
                                                missing_file_id)
709
 
 
710
904
    def _create_pack_from_packs(self):
711
905
        self.pb.update("Opening pack", 0, 5)
712
906
        self.new_pack = self.open_pack()
730
924
        self._copy_text_texts()
731
925
        # select signature keys
732
926
        signature_filter = self._revision_keys # same keyspace
733
 
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
734
 
            self.packs, 'signature_index')[0]
735
 
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
 
927
        signature_index_map, signature_indices = self._pack_map_and_index_list(
 
928
            'signature_index')
 
929
        signature_nodes = self._index_contents(signature_indices,
736
930
            signature_filter)
737
931
        # copy signature keys and adjust values
738
932
        self.pb.update("Copying signature texts", 4)
743
937
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
744
938
                new_pack.signature_index.key_count(),
745
939
                time.time() - new_pack.start_time)
746
 
        self._check_references()
 
940
        # copy chk contents
 
941
        # NB XXX: how to check CHK references are present? perhaps by yielding
 
942
        # the items? How should that interact with stacked repos?
 
943
        if new_pack.chk_index is not None:
 
944
            self._copy_chks()
 
945
            if 'pack' in debug.debug_flags:
 
946
                mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
 
947
                    time.ctime(), self._pack_collection._upload_transport.base,
 
948
                    new_pack.random_name,
 
949
                    new_pack.chk_index.key_count(),
 
950
                    time.time() - new_pack.start_time)
 
951
        new_pack._check_references()
747
952
        if not self._use_pack(new_pack):
748
953
            new_pack.abort()
749
954
            return None
752
957
        self._pack_collection.allocate(new_pack)
753
958
        return new_pack
754
959
 
755
 
    def _copy_nodes(self, nodes, index_map, writer, write_index):
756
 
        """Copy knit nodes between packs with no graph references."""
 
960
    def _copy_chks(self, refs=None):
 
961
        # XXX: Todo, recursive follow-pointers facility when fetching some
 
962
        # revisions only.
 
963
        chk_index_map, chk_indices = self._pack_map_and_index_list(
 
964
            'chk_index')
 
965
        chk_nodes = self._index_contents(chk_indices, refs)
 
966
        new_refs = set()
 
967
        # TODO: This isn't strictly tasteful as we are accessing some private
 
968
        #       variables (_serializer). Perhaps a better way would be to have
 
969
        #       Repository._deserialise_chk_node()
 
970
        search_key_func = chk_map.search_key_registry.get(
 
971
            self._pack_collection.repo._serializer.search_key_name)
 
972
        def accumlate_refs(lines):
 
973
            # XXX: move to a generic location
 
974
            # Yay mismatch:
 
975
            bytes = ''.join(lines)
 
976
            node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
 
977
            new_refs.update(node.refs())
 
978
        self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
 
979
            self.new_pack.chk_index, output_lines=accumlate_refs)
 
980
        return new_refs
 
981
 
 
982
    def _copy_nodes(self, nodes, index_map, writer, write_index,
 
983
        output_lines=None):
 
984
        """Copy knit nodes between packs with no graph references.
 
985
 
 
986
        :param output_lines: Output full texts of copied items.
 
987
        """
757
988
        pb = ui.ui_factory.nested_progress_bar()
758
989
        try:
759
990
            return self._do_copy_nodes(nodes, index_map, writer,
760
 
                write_index, pb)
 
991
                write_index, pb, output_lines=output_lines)
761
992
        finally:
762
993
            pb.finished()
763
994
 
764
 
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
 
995
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
 
996
        output_lines=None):
765
997
        # for record verification
766
 
        knit_data = _KnitData(None)
 
998
        knit = KnitVersionedFiles(None, None)
767
999
        # plan a readv on each source pack:
768
1000
        # group by pack
769
1001
        nodes = sorted(nodes)
770
1002
        # how to map this into knit.py - or knit.py into this?
771
1003
        # we don't want the typical knit logic, we want grouping by pack
772
 
        # at this point - perhaps a helper library for the following code 
 
1004
        # at this point - perhaps a helper library for the following code
773
1005
        # duplication points?
774
1006
        request_groups = {}
775
1007
        for index, key, value in nodes:
788
1020
            # linear scan up the pack
789
1021
            pack_readv_requests.sort()
790
1022
            # copy the data
791
 
            transport, path = index_map[index]
792
 
            reader = pack.make_readv_reader(transport, path,
793
 
                [offset[0:2] for offset in pack_readv_requests])
 
1023
            pack_obj = index_map[index]
 
1024
            transport, path = pack_obj.access_tuple()
 
1025
            try:
 
1026
                reader = pack.make_readv_reader(transport, path,
 
1027
                    [offset[0:2] for offset in pack_readv_requests])
 
1028
            except errors.NoSuchFile:
 
1029
                if self._reload_func is not None:
 
1030
                    self._reload_func()
 
1031
                raise
794
1032
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
795
1033
                izip(reader.iter_records(), pack_readv_requests):
796
1034
                raw_data = read_func(None)
797
1035
                # check the header only
798
 
                df, _ = knit_data._parse_record_header(key[-1], raw_data)
799
 
                df.close()
 
1036
                if output_lines is not None:
 
1037
                    output_lines(knit._parse_record(key[-1], raw_data)[0])
 
1038
                else:
 
1039
                    df, _ = knit._parse_record_header(key, raw_data)
 
1040
                    df.close()
800
1041
                pos, size = writer.add_bytes_record(raw_data, names)
801
1042
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
802
1043
                pb.update("Copied record", record_index)
824
1065
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
825
1066
        output_lines, pb, readv_group_iter, total_items):
826
1067
        # for record verification
827
 
        knit_data = _KnitData(None)
 
1068
        knit = KnitVersionedFiles(None, None)
828
1069
        # for line extraction when requested (inventories only)
829
1070
        if output_lines:
830
 
            factory = knit.KnitPlainFactory()
 
1071
            factory = KnitPlainFactory()
831
1072
        record_index = 0
832
1073
        pb.update("Copied record", record_index, total_items)
833
1074
        for index, readv_vector, node_vector in readv_group_iter:
834
1075
            # copy the data
835
 
            transport, path = index_map[index]
836
 
            reader = pack.make_readv_reader(transport, path, readv_vector)
 
1076
            pack_obj = index_map[index]
 
1077
            transport, path = pack_obj.access_tuple()
 
1078
            try:
 
1079
                reader = pack.make_readv_reader(transport, path, readv_vector)
 
1080
            except errors.NoSuchFile:
 
1081
                if self._reload_func is not None:
 
1082
                    self._reload_func()
 
1083
                raise
837
1084
            for (names, read_func), (key, eol_flag, references) in \
838
1085
                izip(reader.iter_records(), node_vector):
839
1086
                raw_data = read_func(None)
840
 
                version_id = key[-1]
841
1087
                if output_lines:
842
1088
                    # read the entire thing
843
 
                    content, _ = knit_data._parse_record(version_id, raw_data)
 
1089
                    content, _ = knit._parse_record(key[-1], raw_data)
844
1090
                    if len(references[-1]) == 0:
845
1091
                        line_iterator = factory.get_fulltext_content(content)
846
1092
                    else:
847
1093
                        line_iterator = factory.get_linedelta_content(content)
848
1094
                    for line in line_iterator:
849
 
                        yield line, version_id
 
1095
                        yield line, key
850
1096
                else:
851
1097
                    # check the header only
852
 
                    df, _ = knit_data._parse_record_header(version_id, raw_data)
 
1098
                    df, _ = knit._parse_record_header(key, raw_data)
853
1099
                    df.close()
854
1100
                pos, size = writer.add_bytes_record(raw_data, names)
855
1101
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
857
1103
                record_index += 1
858
1104
 
859
1105
    def _get_text_nodes(self):
860
 
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
861
 
            self.packs, 'text_index')[0]
862
 
        return text_index_map, self._pack_collection._index_contents(text_index_map,
 
1106
        text_index_map, text_indices = self._pack_map_and_index_list(
 
1107
            'text_index')
 
1108
        return text_index_map, self._index_contents(text_indices,
863
1109
            self._text_filter)
864
1110
 
865
1111
    def _least_readv_node_readv(self, nodes):
866
1112
        """Generate request groups for nodes using the least readv's.
867
 
        
 
1113
 
868
1114
        :param nodes: An iterable of graph index nodes.
869
1115
        :return: Total node count and an iterator of the data needed to perform
870
1116
            readvs to obtain the data for nodes. Each item yielded by the
871
1117
            iterator is a tuple with:
872
1118
            index, readv_vector, node_vector. readv_vector is a list ready to
873
1119
            hand to the transport readv method, and node_vector is a list of
874
 
            (key, eol_flag, references) for the the node retrieved by the
 
1120
            (key, eol_flag, references) for the node retrieved by the
875
1121
            matching readv_vector.
876
1122
        """
877
1123
        # group by pack so we do one readv per pack
911
1157
        """Use up the inv_lines generator and setup a text key filter."""
912
1158
        repo = self._pack_collection.repo
913
1159
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
914
 
            inv_lines, self.revision_ids)
 
1160
            inv_lines, self.revision_keys)
915
1161
        text_filter = []
916
1162
        for fileid, file_revids in fileid_revisions.iteritems():
917
1163
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
968
1214
        # TODO: combine requests in the same index that are in ascending order.
969
1215
        return total, requests
970
1216
 
 
1217
    def open_pack(self):
 
1218
        """Open a pack for the pack we are creating."""
 
1219
        new_pack = super(OptimisingPacker, self).open_pack()
 
1220
        # Turn on the optimization flags for all the index builders.
 
1221
        new_pack.revision_index.set_optimize(for_size=True)
 
1222
        new_pack.inventory_index.set_optimize(for_size=True)
 
1223
        new_pack.text_index.set_optimize(for_size=True)
 
1224
        new_pack.signature_index.set_optimize(for_size=True)
 
1225
        return new_pack
 
1226
 
971
1227
 
972
1228
class ReconcilePacker(Packer):
973
1229
    """A packer which regenerates indices etc as it copies.
974
 
    
 
1230
 
975
1231
    This is used by ``bzr reconcile`` to cause parent text pointers to be
976
1232
    regenerated.
977
1233
    """
1000
1256
        # 1) generate the ideal index
1001
1257
        repo = self._pack_collection.repo
1002
1258
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1003
 
            _1, key, _2, refs in 
 
1259
            _1, key, _2, refs in
1004
1260
            self.new_pack.revision_index.iter_all_entries()])
1005
1261
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1006
1262
        # 2) generate a text_nodes list that contains all the deltas that can
1012
1268
        text_index_map, text_nodes = self._get_text_nodes()
1013
1269
        for node in text_nodes:
1014
1270
            # 0 - index
1015
 
            # 1 - key 
 
1271
            # 1 - key
1016
1272
            # 2 - value
1017
1273
            # 3 - refs
1018
1274
            try:
1058
1314
        # space (we only topo sort the revisions, which is smaller).
1059
1315
        topo_order = tsort.topo_sort(ancestors)
1060
1316
        rev_order = dict(zip(topo_order, range(len(topo_order))))
1061
 
        bad_texts.sort(key=lambda key:rev_order[key[0][1]])
 
1317
        bad_texts.sort(key=lambda key:rev_order.get(key[0][1], 0))
1062
1318
        transaction = repo.get_transaction()
1063
1319
        file_id_index = GraphIndexPrefixAdapter(
1064
1320
            self.new_pack.text_index,
1065
1321
            ('blank', ), 1,
1066
1322
            add_nodes_callback=self.new_pack.text_index.add_nodes)
1067
 
        knit_index = KnitGraphIndex(file_id_index,
1068
 
            add_callback=file_id_index.add_nodes,
1069
 
            deltas=True, parents=True)
1070
 
        output_knit = knit.KnitVersionedFile('reconcile-texts',
1071
 
            self._pack_collection.transport,
1072
 
            index=knit_index,
1073
 
            access_method=_PackAccess(
1074
 
                {self.new_pack.text_index:self.new_pack.access_tuple()},
1075
 
                (self.new_pack._writer, self.new_pack.text_index)),
1076
 
            factory=knit.KnitPlainFactory())
 
1323
        data_access = _DirectPackAccess(
 
1324
                {self.new_pack.text_index:self.new_pack.access_tuple()})
 
1325
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
 
1326
            self.new_pack.access_tuple())
 
1327
        output_texts = KnitVersionedFiles(
 
1328
            _KnitGraphIndex(self.new_pack.text_index,
 
1329
                add_callback=self.new_pack.text_index.add_nodes,
 
1330
                deltas=True, parents=True, is_locked=repo.is_locked),
 
1331
            data_access=data_access, max_delta_chain=200)
1077
1332
        for key, parent_keys in bad_texts:
1078
1333
            # We refer to the new pack to delta data being output.
1079
1334
            # A possible improvement would be to catch errors on short reads
1086
1341
                    raise errors.BzrError('Mismatched key parent %r:%r' %
1087
1342
                        (key, parent_keys))
1088
1343
                parents.append(parent_key[1])
1089
 
            source_weave = repo.weave_store.get_weave(key[0], transaction)
1090
 
            text_lines = source_weave.get_lines(key[1])
1091
 
            # adapt the 'knit' to the current file_id.
1092
 
            file_id_index = GraphIndexPrefixAdapter(
1093
 
                self.new_pack.text_index,
1094
 
                (key[0], ), 1,
1095
 
                add_nodes_callback=self.new_pack.text_index.add_nodes)
1096
 
            knit_index._graph_index = file_id_index
1097
 
            knit_index._add_callback = file_id_index.add_nodes
1098
 
            output_knit.add_lines_with_ghosts(
1099
 
                key[1], parents, text_lines, random_id=True, check_content=False)
 
1344
            text_lines = osutils.split_lines(repo.texts.get_record_stream(
 
1345
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
 
1346
            output_texts.add_lines(key, parent_keys, text_lines,
 
1347
                random_id=True, check_content=False)
1100
1348
        # 5) check that nothing inserted has a reference outside the keyspace.
1101
 
        missing_text_keys = self.new_pack._external_compression_parents_of_texts()
 
1349
        missing_text_keys = self.new_pack.text_index._external_references()
1102
1350
        if missing_text_keys:
1103
 
            raise errors.BzrError('Reference to missing compression parents %r'
 
1351
            raise errors.BzrCheckError('Reference to missing compression parents %r'
1104
1352
                % (missing_text_keys,))
1105
1353
        self._log_copied_texts()
1106
1354
 
1120
1368
 
1121
1369
 
1122
1370
class RepositoryPackCollection(object):
1123
 
    """Management of packs within a repository."""
 
1371
    """Management of packs within a repository.
 
1372
 
 
1373
    :ivar _names: map of {pack_name: (index_size,)}
 
1374
    """
 
1375
 
 
1376
    pack_factory = NewPack
 
1377
    resumed_pack_factory = ResumedPack
1124
1378
 
1125
1379
    def __init__(self, repo, transport, index_transport, upload_transport,
1126
 
                 pack_transport):
 
1380
                 pack_transport, index_builder_class, index_class,
 
1381
                 use_chk_index):
1127
1382
        """Create a new RepositoryPackCollection.
1128
1383
 
1129
 
        :param transport: Addresses the repository base directory 
 
1384
        :param transport: Addresses the repository base directory
1130
1385
            (typically .bzr/repository/).
1131
1386
        :param index_transport: Addresses the directory containing indices.
1132
1387
        :param upload_transport: Addresses the directory into which packs are written
1133
1388
            while they're being created.
1134
1389
        :param pack_transport: Addresses the directory of existing complete packs.
 
1390
        :param index_builder_class: The index builder class to use.
 
1391
        :param index_class: The index class to use.
 
1392
        :param use_chk_index: Whether to setup and manage a CHK index.
1135
1393
        """
 
1394
        # XXX: This should call self.reset()
1136
1395
        self.repo = repo
1137
1396
        self.transport = transport
1138
1397
        self._index_transport = index_transport
1139
1398
        self._upload_transport = upload_transport
1140
1399
        self._pack_transport = pack_transport
1141
 
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
 
1400
        self._index_builder_class = index_builder_class
 
1401
        self._index_class = index_class
 
1402
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
 
1403
            '.cix': 4}
1142
1404
        self.packs = []
1143
1405
        # name:Pack mapping
 
1406
        self._names = None
1144
1407
        self._packs_by_name = {}
1145
1408
        # the previous pack-names content
1146
1409
        self._packs_at_load = None
1147
1410
        # when a pack is being created by this object, the state of that pack.
1148
1411
        self._new_pack = None
1149
1412
        # aggregated revision index data
1150
 
        self.revision_index = AggregateIndex()
1151
 
        self.inventory_index = AggregateIndex()
1152
 
        self.text_index = AggregateIndex()
1153
 
        self.signature_index = AggregateIndex()
 
1413
        flush = self._flush_new_pack
 
1414
        self.revision_index = AggregateIndex(self.reload_pack_names, flush)
 
1415
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
 
1416
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
 
1417
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
 
1418
        if use_chk_index:
 
1419
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
 
1420
        else:
 
1421
            # used to determine if we're using a chk_index elsewhere.
 
1422
            self.chk_index = None
 
1423
        # resumed packs
 
1424
        self._resumed_packs = []
1154
1425
 
1155
1426
    def add_pack_to_memory(self, pack):
1156
1427
        """Make a Pack object available to the repository to satisfy queries.
1157
 
        
 
1428
 
1158
1429
        :param pack: A Pack object.
1159
1430
        """
1160
1431
        if pack.name in self._packs_by_name:
1161
 
            raise AssertionError()
 
1432
            raise AssertionError(
 
1433
                'pack %s already in _packs_by_name' % (pack.name,))
1162
1434
        self.packs.append(pack)
1163
1435
        self._packs_by_name[pack.name] = pack
1164
1436
        self.revision_index.add_index(pack.revision_index, pack)
1165
1437
        self.inventory_index.add_index(pack.inventory_index, pack)
1166
1438
        self.text_index.add_index(pack.text_index, pack)
1167
1439
        self.signature_index.add_index(pack.signature_index, pack)
1168
 
        
1169
 
    def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
1170
 
        nostore_sha, random_revid):
1171
 
        file_id_index = GraphIndexPrefixAdapter(
1172
 
            self.text_index.combined_index,
1173
 
            (file_id, ), 1,
1174
 
            add_nodes_callback=self.text_index.add_callback)
1175
 
        self.repo._text_knit._index._graph_index = file_id_index
1176
 
        self.repo._text_knit._index._add_callback = file_id_index.add_nodes
1177
 
        return self.repo._text_knit.add_lines_with_ghosts(
1178
 
            revision_id, parents, new_lines, nostore_sha=nostore_sha,
1179
 
            random_id=random_revid, check_content=False)[0:2]
 
1440
        if self.chk_index is not None:
 
1441
            self.chk_index.add_index(pack.chk_index, pack)
1180
1442
 
1181
1443
    def all_packs(self):
1182
1444
        """Return a list of all the Pack objects this repository has.
1192
1454
 
1193
1455
    def autopack(self):
1194
1456
        """Pack the pack collection incrementally.
1195
 
        
 
1457
 
1196
1458
        This will not attempt global reorganisation or recompression,
1197
1459
        rather it will just ensure that the total number of packs does
1198
1460
        not grow without bound. It uses the _max_pack_count method to
1204
1466
        in synchronisation with certain steps. Otherwise the names collection
1205
1467
        is not flushed.
1206
1468
 
1207
 
        :return: True if packing took place.
 
1469
        :return: Something evaluating true if packing took place.
1208
1470
        """
 
1471
        while True:
 
1472
            try:
 
1473
                return self._do_autopack()
 
1474
            except errors.RetryAutopack:
 
1475
                # If we get a RetryAutopack exception, we should abort the
 
1476
                # current action, and retry.
 
1477
                pass
 
1478
 
 
1479
    def _do_autopack(self):
1209
1480
        # XXX: Should not be needed when the management of indices is sane.
1210
1481
        total_revisions = self.revision_index.combined_index.key_count()
1211
1482
        total_packs = len(self._names)
1212
1483
        if self._max_pack_count(total_revisions) >= total_packs:
1213
 
            return False
1214
 
        # XXX: the following may want to be a class, to pack with a given
1215
 
        # policy.
1216
 
        mutter('Auto-packing repository %s, which has %d pack files, '
1217
 
            'containing %d revisions into %d packs.', self, total_packs,
1218
 
            total_revisions, self._max_pack_count(total_revisions))
 
1484
            return None
1219
1485
        # determine which packs need changing
1220
1486
        pack_distribution = self.pack_distribution(total_revisions)
1221
1487
        existing_packs = []
1229
1495
                # group their data with the relevant commit, and that may
1230
1496
                # involve rewriting ancient history - which autopack tries to
1231
1497
                # avoid. Alternatively we could not group the data but treat
1232
 
                # each of these as having a single revision, and thus add 
 
1498
                # each of these as having a single revision, and thus add
1233
1499
                # one revision for each to the total revision count, to get
1234
1500
                # a matching distribution.
1235
1501
                continue
1236
1502
            existing_packs.append((revision_count, pack))
1237
1503
        pack_operations = self.plan_autopack_combinations(
1238
1504
            existing_packs, pack_distribution)
1239
 
        self._execute_pack_operations(pack_operations)
1240
 
        return True
 
1505
        num_new_packs = len(pack_operations)
 
1506
        num_old_packs = sum([len(po[1]) for po in pack_operations])
 
1507
        num_revs_affected = sum([po[0] for po in pack_operations])
 
1508
        mutter('Auto-packing repository %s, which has %d pack files, '
 
1509
            'containing %d revisions. Packing %d files into %d affecting %d'
 
1510
            ' revisions', self, total_packs, total_revisions, num_old_packs,
 
1511
            num_new_packs, num_revs_affected)
 
1512
        result = self._execute_pack_operations(pack_operations,
 
1513
                                      reload_func=self._restart_autopack)
 
1514
        mutter('Auto-packing repository %s completed', self)
 
1515
        return result
1241
1516
 
1242
 
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
 
1517
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
 
1518
                                 reload_func=None):
1243
1519
        """Execute a series of pack operations.
1244
1520
 
1245
1521
        :param pack_operations: A list of [revision_count, packs_to_combine].
1246
1522
        :param _packer_class: The class of packer to use (default: Packer).
1247
 
        :return: None.
 
1523
        :return: The new pack names.
1248
1524
        """
1249
1525
        for revision_count, packs in pack_operations:
1250
1526
            # we may have no-ops from the setup logic
1251
1527
            if len(packs) == 0:
1252
1528
                continue
1253
 
            _packer_class(self, packs, '.autopack').pack()
 
1529
            packer = _packer_class(self, packs, '.autopack',
 
1530
                                   reload_func=reload_func)
 
1531
            try:
 
1532
                packer.pack()
 
1533
            except errors.RetryWithNewPacks:
 
1534
                # An exception is propagating out of this context, make sure
 
1535
                # this packer has cleaned up. Packer() doesn't set its new_pack
 
1536
                # state into the RepositoryPackCollection object, so we only
 
1537
                # have access to it directly here.
 
1538
                if packer.new_pack is not None:
 
1539
                    packer.new_pack.abort()
 
1540
                raise
1254
1541
            for pack in packs:
1255
1542
                self._remove_pack_from_memory(pack)
1256
1543
        # record the newly available packs and stop advertising the old
1257
1544
        # packs
1258
 
        self._save_pack_names(clear_obsolete_packs=True)
 
1545
        result = self._save_pack_names(clear_obsolete_packs=True)
1259
1546
        # Move the old packs out of the way now they are no longer referenced.
1260
1547
        for revision_count, packs in pack_operations:
1261
1548
            self._obsolete_packs(packs)
 
1549
        return result
 
1550
 
 
1551
    def _flush_new_pack(self):
 
1552
        if self._new_pack is not None:
 
1553
            self._new_pack.flush()
1262
1554
 
1263
1555
    def lock_names(self):
1264
1556
        """Acquire the mutex around the pack-names index.
1265
 
        
 
1557
 
1266
1558
        This cannot be used in the middle of a read-only transaction on the
1267
1559
        repository.
1268
1560
        """
1269
1561
        self.repo.control_files.lock_write()
1270
1562
 
1271
 
    def pack(self):
 
1563
    def _already_packed(self):
 
1564
        """Is the collection already packed?"""
 
1565
        return not (self.repo._format.pack_compresses or (len(self._names) > 1))
 
1566
 
 
1567
    def pack(self, hint=None):
1272
1568
        """Pack the pack collection totally."""
1273
1569
        self.ensure_loaded()
1274
1570
        total_packs = len(self._names)
1275
 
        if total_packs < 2:
1276
 
            # This is arguably wrong because we might not be optimal, but for
1277
 
            # now lets leave it in. (e.g. reconcile -> one pack. But not
1278
 
            # optimal.
 
1571
        if self._already_packed():
1279
1572
            return
1280
1573
        total_revisions = self.revision_index.combined_index.key_count()
1281
1574
        # XXX: the following may want to be a class, to pack with a given
1282
1575
        # policy.
1283
1576
        mutter('Packing repository %s, which has %d pack files, '
1284
 
            'containing %d revisions into 1 packs.', self, total_packs,
1285
 
            total_revisions)
 
1577
            'containing %d revisions with hint %r.', self, total_packs,
 
1578
            total_revisions, hint)
1286
1579
        # determine which packs need changing
1287
 
        pack_distribution = [1]
1288
1580
        pack_operations = [[0, []]]
1289
1581
        for pack in self.all_packs():
1290
 
            pack_operations[-1][0] += pack.get_revision_count()
1291
 
            pack_operations[-1][1].append(pack)
 
1582
            if hint is None or pack.name in hint:
 
1583
                # Either no hint was provided (so we are packing everything),
 
1584
                # or this pack was included in the hint.
 
1585
                pack_operations[-1][0] += pack.get_revision_count()
 
1586
                pack_operations[-1][1].append(pack)
1292
1587
        self._execute_pack_operations(pack_operations, OptimisingPacker)
1293
1588
 
1294
1589
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
1306
1601
        # plan out what packs to keep, and what to reorganise
1307
1602
        while len(existing_packs):
1308
1603
            # take the largest pack, and if its less than the head of the
1309
 
            # distribution chart we will include its contents in the new pack for
1310
 
            # that position. If its larger, we remove its size from the
 
1604
            # distribution chart we will include its contents in the new pack
 
1605
            # for that position. If its larger, we remove its size from the
1311
1606
            # distribution chart
1312
1607
            next_pack_rev_count, next_pack = existing_packs.pop(0)
1313
1608
            if next_pack_rev_count >= pack_distribution[0]:
1330
1625
                    # this pack is used up, shift left.
1331
1626
                    del pack_distribution[0]
1332
1627
                    pack_operations.append([0, []])
1333
 
        
1334
 
        return pack_operations
 
1628
        # Now that we know which pack files we want to move, shove them all
 
1629
        # into a single pack file.
 
1630
        final_rev_count = 0
 
1631
        final_pack_list = []
 
1632
        for num_revs, pack_files in pack_operations:
 
1633
            final_rev_count += num_revs
 
1634
            final_pack_list.extend(pack_files)
 
1635
        if len(final_pack_list) == 1:
 
1636
            raise AssertionError('We somehow generated an autopack with a'
 
1637
                ' single pack file being moved.')
 
1638
            return []
 
1639
        return [[final_rev_count, final_pack_list]]
1335
1640
 
1336
1641
    def ensure_loaded(self):
 
1642
        """Ensure we have read names from disk.
 
1643
 
 
1644
        :return: True if the disk names had not been previously read.
 
1645
        """
1337
1646
        # NB: if you see an assertion error here, its probably access against
1338
1647
        # an unlocked repo. Naughty.
1339
1648
        if not self.repo.is_locked():
1345
1654
                name = key[0]
1346
1655
                self._names[name] = self._parse_index_sizes(value)
1347
1656
                self._packs_at_load.add((key, value))
 
1657
            result = True
 
1658
        else:
 
1659
            result = False
1348
1660
        # populate all the metadata.
1349
1661
        self.all_packs()
 
1662
        return result
1350
1663
 
1351
1664
    def _parse_index_sizes(self, value):
1352
1665
        """Parse a string of index sizes."""
1365
1678
            inv_index = self._make_index(name, '.iix')
1366
1679
            txt_index = self._make_index(name, '.tix')
1367
1680
            sig_index = self._make_index(name, '.six')
 
1681
            if self.chk_index is not None:
 
1682
                chk_index = self._make_index(name, '.cix', unlimited_cache=True)
 
1683
            else:
 
1684
                chk_index = None
1368
1685
            result = ExistingPack(self._pack_transport, name, rev_index,
1369
 
                inv_index, txt_index, sig_index)
 
1686
                inv_index, txt_index, sig_index, chk_index)
1370
1687
            self.add_pack_to_memory(result)
1371
1688
            return result
1372
1689
 
 
1690
    def _resume_pack(self, name):
 
1691
        """Get a suspended Pack object by name.
 
1692
 
 
1693
        :param name: The name of the pack - e.g. '123456'
 
1694
        :return: A Pack object.
 
1695
        """
 
1696
        if not re.match('[a-f0-9]{32}', name):
 
1697
            # Tokens should be md5sums of the suspended pack file, i.e. 32 hex
 
1698
            # digits.
 
1699
            raise errors.UnresumableWriteGroup(
 
1700
                self.repo, [name], 'Malformed write group token')
 
1701
        try:
 
1702
            rev_index = self._make_index(name, '.rix', resume=True)
 
1703
            inv_index = self._make_index(name, '.iix', resume=True)
 
1704
            txt_index = self._make_index(name, '.tix', resume=True)
 
1705
            sig_index = self._make_index(name, '.six', resume=True)
 
1706
            if self.chk_index is not None:
 
1707
                chk_index = self._make_index(name, '.cix', resume=True,
 
1708
                                             unlimited_cache=True)
 
1709
            else:
 
1710
                chk_index = None
 
1711
            result = self.resumed_pack_factory(name, rev_index, inv_index,
 
1712
                txt_index, sig_index, self._upload_transport,
 
1713
                self._pack_transport, self._index_transport, self,
 
1714
                chk_index=chk_index)
 
1715
        except errors.NoSuchFile, e:
 
1716
            raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
 
1717
        self.add_pack_to_memory(result)
 
1718
        self._resumed_packs.append(result)
 
1719
        return result
 
1720
 
1373
1721
    def allocate(self, a_new_pack):
1374
1722
        """Allocate name in the list of packs.
1375
1723
 
1385
1733
 
1386
1734
    def _iter_disk_pack_index(self):
1387
1735
        """Iterate over the contents of the pack-names index.
1388
 
        
 
1736
 
1389
1737
        This is used when loading the list from disk, and before writing to
1390
1738
        detect updates from others during our write operation.
1391
1739
        :return: An iterator of the index contents.
1392
1740
        """
1393
 
        return GraphIndex(self.transport, 'pack-names', None
 
1741
        return self._index_class(self.transport, 'pack-names', None
1394
1742
                ).iter_all_entries()
1395
1743
 
1396
 
    def _make_index(self, name, suffix):
 
1744
    def _make_index(self, name, suffix, resume=False, unlimited_cache=False):
1397
1745
        size_offset = self._suffix_offsets[suffix]
1398
1746
        index_name = name + suffix
1399
 
        index_size = self._names[name][size_offset]
1400
 
        return GraphIndex(
1401
 
            self._index_transport, index_name, index_size)
 
1747
        if resume:
 
1748
            transport = self._upload_transport
 
1749
            index_size = transport.stat(index_name).st_size
 
1750
        else:
 
1751
            transport = self._index_transport
 
1752
            index_size = self._names[name][size_offset]
 
1753
        return self._index_class(transport, index_name, index_size,
 
1754
                                 unlimited_cache=unlimited_cache)
1402
1755
 
1403
1756
    def _max_pack_count(self, total_revisions):
1404
1757
        """Return the maximum number of packs to use for total revisions.
1405
 
        
 
1758
 
1406
1759
        :param total_revisions: The total number of revisions in the
1407
1760
            repository.
1408
1761
        """
1437
1790
            # TODO: Probably needs to know all possible indices for this pack
1438
1791
            # - or maybe list the directory and move all indices matching this
1439
1792
            # name whether we recognize it or not?
1440
 
            for suffix in ('.iix', '.six', '.tix', '.rix'):
 
1793
            suffixes = ['.iix', '.six', '.tix', '.rix']
 
1794
            if self.chk_index is not None:
 
1795
                suffixes.append('.cix')
 
1796
            for suffix in suffixes:
1441
1797
                self._index_transport.rename(pack.name + suffix,
1442
1798
                    '../obsolete_packs/' + pack.name + suffix)
1443
1799
 
1463
1819
 
1464
1820
    def _remove_pack_from_memory(self, pack):
1465
1821
        """Remove pack from the packs accessed by this repository.
1466
 
        
 
1822
 
1467
1823
        Only affects memory state, until self._save_pack_names() is invoked.
1468
1824
        """
1469
1825
        self._names.pop(pack.name)
1470
1826
        self._packs_by_name.pop(pack.name)
1471
1827
        self._remove_pack_indices(pack)
 
1828
        self.packs.remove(pack)
1472
1829
 
1473
1830
    def _remove_pack_indices(self, pack):
1474
1831
        """Remove the indices for pack from the aggregated indices."""
1476
1833
        self.inventory_index.remove_index(pack.inventory_index, pack)
1477
1834
        self.text_index.remove_index(pack.text_index, pack)
1478
1835
        self.signature_index.remove_index(pack.signature_index, pack)
 
1836
        if self.chk_index is not None:
 
1837
            self.chk_index.remove_index(pack.chk_index, pack)
1479
1838
 
1480
1839
    def reset(self):
1481
1840
        """Clear all cached data."""
1482
1841
        # cached revision data
1483
 
        self.repo._revision_knit = None
1484
1842
        self.revision_index.clear()
1485
1843
        # cached signature data
1486
 
        self.repo._signature_knit = None
1487
1844
        self.signature_index.clear()
1488
1845
        # cached file text data
1489
1846
        self.text_index.clear()
1490
 
        self.repo._text_knit = None
1491
1847
        # cached inventory data
1492
1848
        self.inventory_index.clear()
 
1849
        # cached chk data
 
1850
        if self.chk_index is not None:
 
1851
            self.chk_index.clear()
1493
1852
        # remove the open pack
1494
1853
        self._new_pack = None
1495
1854
        # information about packs.
1498
1857
        self._packs_by_name = {}
1499
1858
        self._packs_at_load = None
1500
1859
 
1501
 
    def _make_index_map(self, index_suffix):
1502
 
        """Return information on existing indices.
1503
 
 
1504
 
        :param suffix: Index suffix added to pack name.
1505
 
 
1506
 
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
1507
 
        objects, and pack_map is a mapping from those objects to the 
1508
 
        pack tuple they describe.
1509
 
        """
1510
 
        # TODO: stop using this; it creates new indices unnecessarily.
1511
 
        self.ensure_loaded()
1512
 
        suffix_map = {'.rix': 'revision_index',
1513
 
            '.six': 'signature_index',
1514
 
            '.iix': 'inventory_index',
1515
 
            '.tix': 'text_index',
1516
 
        }
1517
 
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1518
 
            suffix_map[index_suffix])
1519
 
 
1520
 
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1521
 
        """Convert a list of packs to an index pack map and index list.
1522
 
 
1523
 
        :param packs: The packs list to process.
1524
 
        :param index_attribute: The attribute that the desired index is found
1525
 
            on.
1526
 
        :return: A tuple (map, list) where map contains the dict from
1527
 
            index:pack_tuple, and lsit contains the indices in the same order
1528
 
            as the packs list.
1529
 
        """
1530
 
        indices = []
1531
 
        pack_map = {}
1532
 
        for pack in packs:
1533
 
            index = getattr(pack, index_attribute)
1534
 
            indices.append(index)
1535
 
            pack_map[index] = (pack.pack_transport, pack.file_name())
1536
 
        return pack_map, indices
1537
 
 
1538
 
    def _index_contents(self, pack_map, key_filter=None):
1539
 
        """Get an iterable of the index contents from a pack_map.
1540
 
 
1541
 
        :param pack_map: A map from indices to pack details.
1542
 
        :param key_filter: An optional filter to limit the
1543
 
            keys returned.
1544
 
        """
1545
 
        indices = [index for index in pack_map.iterkeys()]
1546
 
        all_index = CombinedGraphIndex(indices)
1547
 
        if key_filter is None:
1548
 
            return all_index.iter_all_entries()
1549
 
        else:
1550
 
            return all_index.iter_entries(key_filter)
1551
 
 
1552
1860
    def _unlock_names(self):
1553
1861
        """Release the mutex around the pack-names index."""
1554
1862
        self.repo.control_files.unlock()
1555
1863
 
1556
 
    def _save_pack_names(self, clear_obsolete_packs=False):
1557
 
        """Save the list of packs.
1558
 
 
1559
 
        This will take out the mutex around the pack names list for the
1560
 
        duration of the method call. If concurrent updates have been made, a
1561
 
        three-way merge between the current list and the current in memory list
1562
 
        is performed.
1563
 
 
1564
 
        :param clear_obsolete_packs: If True, clear out the contents of the
1565
 
            obsolete_packs directory.
1566
 
        """
1567
 
        self.lock_names()
1568
 
        try:
1569
 
            builder = GraphIndexBuilder()
1570
 
            # load the disk nodes across
1571
 
            disk_nodes = set()
1572
 
            for index, key, value in self._iter_disk_pack_index():
1573
 
                disk_nodes.add((key, value))
1574
 
            # do a two-way diff against our original content
1575
 
            current_nodes = set()
1576
 
            for name, sizes in self._names.iteritems():
1577
 
                current_nodes.add(
1578
 
                    ((name, ), ' '.join(str(size) for size in sizes)))
1579
 
            deleted_nodes = self._packs_at_load - current_nodes
1580
 
            new_nodes = current_nodes - self._packs_at_load
1581
 
            disk_nodes.difference_update(deleted_nodes)
1582
 
            disk_nodes.update(new_nodes)
1583
 
            # TODO: handle same-name, index-size-changes here - 
1584
 
            # e.g. use the value from disk, not ours, *unless* we're the one
1585
 
            # changing it.
1586
 
            for key, value in disk_nodes:
1587
 
                builder.add_node(key, value)
1588
 
            self.transport.put_file('pack-names', builder.finish(),
1589
 
                mode=self.repo.control_files._file_mode)
1590
 
            # move the baseline forward
1591
 
            self._packs_at_load = disk_nodes
1592
 
            # now clear out the obsolete packs directory
1593
 
            if clear_obsolete_packs:
1594
 
                self.transport.clone('obsolete_packs').delete_multi(
1595
 
                    self.transport.list_dir('obsolete_packs'))
1596
 
        finally:
1597
 
            self._unlock_names()
1598
 
        # synchronise the memory packs list with what we just wrote:
 
1864
    def _diff_pack_names(self):
 
1865
        """Read the pack names from disk, and compare it to the one in memory.
 
1866
 
 
1867
        :return: (disk_nodes, deleted_nodes, new_nodes)
 
1868
            disk_nodes    The final set of nodes that should be referenced
 
1869
            deleted_nodes Nodes which have been removed from when we started
 
1870
            new_nodes     Nodes that are newly introduced
 
1871
        """
 
1872
        # load the disk nodes across
 
1873
        disk_nodes = set()
 
1874
        for index, key, value in self._iter_disk_pack_index():
 
1875
            disk_nodes.add((key, value))
 
1876
 
 
1877
        # do a two-way diff against our original content
 
1878
        current_nodes = set()
 
1879
        for name, sizes in self._names.iteritems():
 
1880
            current_nodes.add(
 
1881
                ((name, ), ' '.join(str(size) for size in sizes)))
 
1882
 
 
1883
        # Packs no longer present in the repository, which were present when we
 
1884
        # locked the repository
 
1885
        deleted_nodes = self._packs_at_load - current_nodes
 
1886
        # Packs which this process is adding
 
1887
        new_nodes = current_nodes - self._packs_at_load
 
1888
 
 
1889
        # Update the disk_nodes set to include the ones we are adding, and
 
1890
        # remove the ones which were removed by someone else
 
1891
        disk_nodes.difference_update(deleted_nodes)
 
1892
        disk_nodes.update(new_nodes)
 
1893
 
 
1894
        return disk_nodes, deleted_nodes, new_nodes
 
1895
 
 
1896
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
 
1897
        """Given the correct set of pack files, update our saved info.
 
1898
 
 
1899
        :return: (removed, added, modified)
 
1900
            removed     pack names removed from self._names
 
1901
            added       pack names added to self._names
 
1902
            modified    pack names that had changed value
 
1903
        """
 
1904
        removed = []
 
1905
        added = []
 
1906
        modified = []
 
1907
        ## self._packs_at_load = disk_nodes
1599
1908
        new_names = dict(disk_nodes)
1600
1909
        # drop no longer present nodes
1601
1910
        for pack in self.all_packs():
1602
1911
            if (pack.name,) not in new_names:
 
1912
                removed.append(pack.name)
1603
1913
                self._remove_pack_from_memory(pack)
1604
1914
        # add new nodes/refresh existing ones
1605
1915
        for key, value in disk_nodes:
1619
1929
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
1620
1930
                    self._names[name] = sizes
1621
1931
                    self.get_pack_by_name(name)
 
1932
                    modified.append(name)
1622
1933
            else:
1623
1934
                # new
1624
1935
                self._names[name] = sizes
1625
1936
                self.get_pack_by_name(name)
 
1937
                added.append(name)
 
1938
        return removed, added, modified
 
1939
 
 
1940
    def _save_pack_names(self, clear_obsolete_packs=False):
 
1941
        """Save the list of packs.
 
1942
 
 
1943
        This will take out the mutex around the pack names list for the
 
1944
        duration of the method call. If concurrent updates have been made, a
 
1945
        three-way merge between the current list and the current in memory list
 
1946
        is performed.
 
1947
 
 
1948
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1949
            obsolete_packs directory.
 
1950
        :return: A list of the names saved that were not previously on disk.
 
1951
        """
 
1952
        self.lock_names()
 
1953
        try:
 
1954
            builder = self._index_builder_class()
 
1955
            disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
 
1956
            # TODO: handle same-name, index-size-changes here -
 
1957
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1958
            # changing it.
 
1959
            for key, value in disk_nodes:
 
1960
                builder.add_node(key, value)
 
1961
            self.transport.put_file('pack-names', builder.finish(),
 
1962
                mode=self.repo.bzrdir._get_file_mode())
 
1963
            # move the baseline forward
 
1964
            self._packs_at_load = disk_nodes
 
1965
            if clear_obsolete_packs:
 
1966
                self._clear_obsolete_packs()
 
1967
        finally:
 
1968
            self._unlock_names()
 
1969
        # synchronise the memory packs list with what we just wrote:
 
1970
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1971
        return [new_node[0][0] for new_node in new_nodes]
 
1972
 
 
1973
    def reload_pack_names(self):
 
1974
        """Sync our pack listing with what is present in the repository.
 
1975
 
 
1976
        This should be called when we find out that something we thought was
 
1977
        present is now missing. This happens when another process re-packs the
 
1978
        repository, etc.
 
1979
 
 
1980
        :return: True if the in-memory list of packs has been altered at all.
 
1981
        """
 
1982
        # The ensure_loaded call is to handle the case where the first call
 
1983
        # made involving the collection was to reload_pack_names, where we 
 
1984
        # don't have a view of disk contents. Its a bit of a bandaid, and
 
1985
        # causes two reads of pack-names, but its a rare corner case not struck
 
1986
        # with regular push/pull etc.
 
1987
        first_read = self.ensure_loaded()
 
1988
        if first_read:
 
1989
            return True
 
1990
        # out the new value.
 
1991
        disk_nodes, _, _ = self._diff_pack_names()
 
1992
        self._packs_at_load = disk_nodes
 
1993
        (removed, added,
 
1994
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1995
        if removed or added or modified:
 
1996
            return True
 
1997
        return False
 
1998
 
 
1999
    def _restart_autopack(self):
 
2000
        """Reload the pack names list, and restart the autopack code."""
 
2001
        if not self.reload_pack_names():
 
2002
            # Re-raise the original exception, because something went missing
 
2003
            # and a restart didn't find it
 
2004
            raise
 
2005
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
 
2006
 
 
2007
    def _clear_obsolete_packs(self):
 
2008
        """Delete everything from the obsolete-packs directory.
 
2009
        """
 
2010
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
 
2011
        for filename in obsolete_pack_transport.list_dir('.'):
 
2012
            try:
 
2013
                obsolete_pack_transport.delete(filename)
 
2014
            except (errors.PathError, errors.TransportError), e:
 
2015
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1626
2016
 
1627
2017
    def _start_write_group(self):
1628
2018
        # Do not permit preparation for writing if we're not in a 'write lock'.
1629
2019
        if not self.repo.is_write_locked():
1630
2020
            raise errors.NotWriteLocked(self)
1631
 
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
1632
 
            self._pack_transport, upload_suffix='.pack',
1633
 
            file_mode=self.repo.control_files._file_mode)
 
2021
        self._new_pack = self.pack_factory(self, upload_suffix='.pack',
 
2022
            file_mode=self.repo.bzrdir._get_file_mode())
1634
2023
        # allow writing: queue writes to a new index
1635
2024
        self.revision_index.add_writable_index(self._new_pack.revision_index,
1636
2025
            self._new_pack)
1638
2027
            self._new_pack)
1639
2028
        self.text_index.add_writable_index(self._new_pack.text_index,
1640
2029
            self._new_pack)
 
2030
        self._new_pack.text_index.set_optimize(combine_backing_indices=False)
1641
2031
        self.signature_index.add_writable_index(self._new_pack.signature_index,
1642
2032
            self._new_pack)
 
2033
        if self.chk_index is not None:
 
2034
            self.chk_index.add_writable_index(self._new_pack.chk_index,
 
2035
                self._new_pack)
 
2036
            self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
 
2037
            self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
1643
2038
 
1644
 
        # reused revision and signature knits may need updating
1645
 
        #
1646
 
        # "Hysterical raisins. client code in bzrlib grabs those knits outside
1647
 
        # of write groups and then mutates it inside the write group."
1648
 
        if self.repo._revision_knit is not None:
1649
 
            self.repo._revision_knit._index._add_callback = \
1650
 
                self.revision_index.add_callback
1651
 
        if self.repo._signature_knit is not None:
1652
 
            self.repo._signature_knit._index._add_callback = \
1653
 
                self.signature_index.add_callback
1654
 
        # create a reused knit object for text addition in commit.
1655
 
        self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1656
 
            'all-texts', None)
 
2039
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
 
2040
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
 
2041
        self.repo.signatures._index._add_callback = self.signature_index.add_callback
 
2042
        self.repo.texts._index._add_callback = self.text_index.add_callback
1657
2043
 
1658
2044
    def _abort_write_group(self):
1659
2045
        # FIXME: just drop the transient index.
1660
2046
        # forget what names there are
1661
2047
        if self._new_pack is not None:
1662
 
            self._new_pack.abort()
1663
 
            self._remove_pack_indices(self._new_pack)
1664
 
            self._new_pack = None
1665
 
        self.repo._text_knit = None
1666
 
 
 
2048
            try:
 
2049
                self._new_pack.abort()
 
2050
            finally:
 
2051
                # XXX: If we aborted while in the middle of finishing the write
 
2052
                # group, _remove_pack_indices can fail because the indexes are
 
2053
                # already gone.  If they're not there we shouldn't fail in this
 
2054
                # case.  -- mbp 20081113
 
2055
                self._remove_pack_indices(self._new_pack)
 
2056
                self._new_pack = None
 
2057
        for resumed_pack in self._resumed_packs:
 
2058
            try:
 
2059
                resumed_pack.abort()
 
2060
            finally:
 
2061
                # See comment in previous finally block.
 
2062
                try:
 
2063
                    self._remove_pack_indices(resumed_pack)
 
2064
                except KeyError:
 
2065
                    pass
 
2066
        del self._resumed_packs[:]
 
2067
 
 
2068
    def _remove_resumed_pack_indices(self):
 
2069
        for resumed_pack in self._resumed_packs:
 
2070
            self._remove_pack_indices(resumed_pack)
 
2071
        del self._resumed_packs[:]
 
2072
 
 
2073
    def _check_new_inventories(self):
 
2074
        """Detect missing inventories in this write group.
 
2075
 
 
2076
        :returns: list of strs, summarising any problems found.  If the list is
 
2077
            empty no problems were found.
 
2078
        """
 
2079
        # The base implementation does no checks.  GCRepositoryPackCollection
 
2080
        # overrides this.
 
2081
        return []
 
2082
        
1667
2083
    def _commit_write_group(self):
 
2084
        all_missing = set()
 
2085
        for prefix, versioned_file in (
 
2086
                ('revisions', self.repo.revisions),
 
2087
                ('inventories', self.repo.inventories),
 
2088
                ('texts', self.repo.texts),
 
2089
                ('signatures', self.repo.signatures),
 
2090
                ):
 
2091
            missing = versioned_file.get_missing_compression_parent_keys()
 
2092
            all_missing.update([(prefix,) + key for key in missing])
 
2093
        if all_missing:
 
2094
            raise errors.BzrCheckError(
 
2095
                "Repository %s has missing compression parent(s) %r "
 
2096
                 % (self.repo, sorted(all_missing)))
 
2097
        problems = self._check_new_inventories()
 
2098
        if problems:
 
2099
            problems_summary = '\n'.join(problems)
 
2100
            raise errors.BzrCheckError(
 
2101
                "Cannot add revision(s) to repository: " + problems_summary)
1668
2102
        self._remove_pack_indices(self._new_pack)
 
2103
        any_new_content = False
1669
2104
        if self._new_pack.data_inserted():
1670
2105
            # get all the data to disk and read to use
1671
2106
            self._new_pack.finish()
1672
2107
            self.allocate(self._new_pack)
1673
2108
            self._new_pack = None
1674
 
            if not self.autopack():
 
2109
            any_new_content = True
 
2110
        else:
 
2111
            self._new_pack.abort()
 
2112
            self._new_pack = None
 
2113
        for resumed_pack in self._resumed_packs:
 
2114
            # XXX: this is a pretty ugly way to turn the resumed pack into a
 
2115
            # properly committed pack.
 
2116
            self._names[resumed_pack.name] = None
 
2117
            self._remove_pack_from_memory(resumed_pack)
 
2118
            resumed_pack.finish()
 
2119
            self.allocate(resumed_pack)
 
2120
            any_new_content = True
 
2121
        del self._resumed_packs[:]
 
2122
        if any_new_content:
 
2123
            result = self.autopack()
 
2124
            if not result:
1675
2125
                # when autopack takes no steps, the names list is still
1676
2126
                # unsaved.
1677
 
                self._save_pack_names()
 
2127
                return self._save_pack_names()
 
2128
            return result
 
2129
        return []
 
2130
 
 
2131
    def _suspend_write_group(self):
 
2132
        tokens = [pack.name for pack in self._resumed_packs]
 
2133
        self._remove_pack_indices(self._new_pack)
 
2134
        if self._new_pack.data_inserted():
 
2135
            # get all the data to disk and read to use
 
2136
            self._new_pack.finish(suspend=True)
 
2137
            tokens.append(self._new_pack.name)
 
2138
            self._new_pack = None
1678
2139
        else:
1679
2140
            self._new_pack.abort()
1680
2141
            self._new_pack = None
1681
 
        self.repo._text_knit = None
1682
 
 
1683
 
 
1684
 
class KnitPackRevisionStore(KnitRevisionStore):
1685
 
    """An object to adapt access from RevisionStore's to use KnitPacks.
1686
 
 
1687
 
    This class works by replacing the original RevisionStore.
1688
 
    We need to do this because the KnitPackRevisionStore is less
1689
 
    isolated in its layering - it uses services from the repo.
1690
 
    """
1691
 
 
1692
 
    def __init__(self, repo, transport, revisionstore):
1693
 
        """Create a KnitPackRevisionStore on repo with revisionstore.
1694
 
 
1695
 
        This will store its state in the Repository, use the
1696
 
        indices to provide a KnitGraphIndex,
1697
 
        and at the end of transactions write new indices.
1698
 
        """
1699
 
        KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1700
 
        self.repo = repo
1701
 
        self._serializer = revisionstore._serializer
1702
 
        self.transport = transport
1703
 
 
1704
 
    def get_revision_file(self, transaction):
1705
 
        """Get the revision versioned file object."""
1706
 
        if getattr(self.repo, '_revision_knit', None) is not None:
1707
 
            return self.repo._revision_knit
1708
 
        self.repo._pack_collection.ensure_loaded()
1709
 
        add_callback = self.repo._pack_collection.revision_index.add_callback
1710
 
        # setup knit specific objects
1711
 
        knit_index = KnitGraphIndex(
1712
 
            self.repo._pack_collection.revision_index.combined_index,
1713
 
            add_callback=add_callback)
1714
 
        self.repo._revision_knit = knit.KnitVersionedFile(
1715
 
            'revisions', self.transport.clone('..'),
1716
 
            self.repo.control_files._file_mode,
1717
 
            create=False,
1718
 
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1719
 
            access_method=self.repo._pack_collection.revision_index.knit_access)
1720
 
        return self.repo._revision_knit
1721
 
 
1722
 
    def get_signature_file(self, transaction):
1723
 
        """Get the signature versioned file object."""
1724
 
        if getattr(self.repo, '_signature_knit', None) is not None:
1725
 
            return self.repo._signature_knit
1726
 
        self.repo._pack_collection.ensure_loaded()
1727
 
        add_callback = self.repo._pack_collection.signature_index.add_callback
1728
 
        # setup knit specific objects
1729
 
        knit_index = KnitGraphIndex(
1730
 
            self.repo._pack_collection.signature_index.combined_index,
1731
 
            add_callback=add_callback, parents=False)
1732
 
        self.repo._signature_knit = knit.KnitVersionedFile(
1733
 
            'signatures', self.transport.clone('..'),
1734
 
            self.repo.control_files._file_mode,
1735
 
            create=False,
1736
 
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1737
 
            access_method=self.repo._pack_collection.signature_index.knit_access)
1738
 
        return self.repo._signature_knit
1739
 
 
1740
 
 
1741
 
class KnitPackTextStore(VersionedFileStore):
1742
 
    """Presents a TextStore abstraction on top of packs.
1743
 
 
1744
 
    This class works by replacing the original VersionedFileStore.
1745
 
    We need to do this because the KnitPackRevisionStore is less
1746
 
    isolated in its layering - it uses services from the repo and shares them
1747
 
    with all the data written in a single write group.
1748
 
    """
1749
 
 
1750
 
    def __init__(self, repo, transport, weavestore):
1751
 
        """Create a KnitPackTextStore on repo with weavestore.
1752
 
 
1753
 
        This will store its state in the Repository, use the
1754
 
        indices FileNames to provide a KnitGraphIndex,
1755
 
        and at the end of transactions write new indices.
1756
 
        """
1757
 
        # don't call base class constructor - it's not suitable.
1758
 
        # no transient data stored in the transaction
1759
 
        # cache.
1760
 
        self._precious = False
1761
 
        self.repo = repo
1762
 
        self.transport = transport
1763
 
        self.weavestore = weavestore
1764
 
        # XXX for check() which isn't updated yet
1765
 
        self._transport = weavestore._transport
1766
 
 
1767
 
    def get_weave_or_empty(self, file_id, transaction):
1768
 
        """Get a 'Knit' backed by the .tix indices.
1769
 
 
1770
 
        The transaction parameter is ignored.
1771
 
        """
1772
 
        self.repo._pack_collection.ensure_loaded()
1773
 
        add_callback = self.repo._pack_collection.text_index.add_callback
1774
 
        # setup knit specific objects
1775
 
        file_id_index = GraphIndexPrefixAdapter(
1776
 
            self.repo._pack_collection.text_index.combined_index,
1777
 
            (file_id, ), 1, add_nodes_callback=add_callback)
1778
 
        knit_index = KnitGraphIndex(file_id_index,
1779
 
            add_callback=file_id_index.add_nodes,
1780
 
            deltas=True, parents=True)
1781
 
        return knit.KnitVersionedFile('text:' + file_id,
1782
 
            self.transport.clone('..'),
1783
 
            None,
1784
 
            index=knit_index,
1785
 
            access_method=self.repo._pack_collection.text_index.knit_access,
1786
 
            factory=knit.KnitPlainFactory())
1787
 
 
1788
 
    get_weave = get_weave_or_empty
1789
 
 
1790
 
    def __iter__(self):
1791
 
        """Generate a list of the fileids inserted, for use by check."""
1792
 
        self.repo._pack_collection.ensure_loaded()
1793
 
        ids = set()
1794
 
        for index, key, value, refs in \
1795
 
            self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1796
 
            ids.add(key[0])
1797
 
        return iter(ids)
1798
 
 
1799
 
 
1800
 
class InventoryKnitThunk(object):
1801
 
    """An object to manage thunking get_inventory_weave to pack based knits."""
1802
 
 
1803
 
    def __init__(self, repo, transport):
1804
 
        """Create an InventoryKnitThunk for repo at transport.
1805
 
 
1806
 
        This will store its state in the Repository, use the
1807
 
        indices FileNames to provide a KnitGraphIndex,
1808
 
        and at the end of transactions write a new index..
1809
 
        """
1810
 
        self.repo = repo
1811
 
        self.transport = transport
1812
 
 
1813
 
    def get_weave(self):
1814
 
        """Get a 'Knit' that contains inventory data."""
1815
 
        self.repo._pack_collection.ensure_loaded()
1816
 
        add_callback = self.repo._pack_collection.inventory_index.add_callback
1817
 
        # setup knit specific objects
1818
 
        knit_index = KnitGraphIndex(
1819
 
            self.repo._pack_collection.inventory_index.combined_index,
1820
 
            add_callback=add_callback, deltas=True, parents=True)
1821
 
        return knit.KnitVersionedFile(
1822
 
            'inventory', self.transport.clone('..'),
1823
 
            self.repo.control_files._file_mode,
1824
 
            create=False,
1825
 
            index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1826
 
            access_method=self.repo._pack_collection.inventory_index.knit_access)
 
2142
        self._remove_resumed_pack_indices()
 
2143
        return tokens
 
2144
 
 
2145
    def _resume_write_group(self, tokens):
 
2146
        for token in tokens:
 
2147
            self._resume_pack(token)
1827
2148
 
1828
2149
 
1829
2150
class KnitPackRepository(KnitRepository):
1830
 
    """Experimental graph-knit using repository."""
1831
 
 
1832
 
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1833
 
        control_store, text_store, _commit_builder_class, _serializer):
 
2151
    """Repository with knit objects stored inside pack containers.
 
2152
 
 
2153
    The layering for a KnitPackRepository is:
 
2154
 
 
2155
    Graph        |  HPSS    | Repository public layer |
 
2156
    ===================================================
 
2157
    Tuple based apis below, string based, and key based apis above
 
2158
    ---------------------------------------------------
 
2159
    KnitVersionedFiles
 
2160
      Provides .texts, .revisions etc
 
2161
      This adapts the N-tuple keys to physical knit records which only have a
 
2162
      single string identifier (for historical reasons), which in older formats
 
2163
      was always the revision_id, and in the mapped code for packs is always
 
2164
      the last element of key tuples.
 
2165
    ---------------------------------------------------
 
2166
    GraphIndex
 
2167
      A separate GraphIndex is used for each of the
 
2168
      texts/inventories/revisions/signatures contained within each individual
 
2169
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
 
2170
      semantic value.
 
2171
    ===================================================
 
2172
 
 
2173
    """
 
2174
 
 
2175
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
 
2176
        _serializer):
1834
2177
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1835
 
            _revision_store, control_store, text_store, _commit_builder_class,
1836
 
            _serializer)
1837
 
        index_transport = control_files._transport.clone('indices')
1838
 
        self._pack_collection = RepositoryPackCollection(self, control_files._transport,
 
2178
            _commit_builder_class, _serializer)
 
2179
        index_transport = self._transport.clone('indices')
 
2180
        self._pack_collection = RepositoryPackCollection(self, self._transport,
1839
2181
            index_transport,
1840
 
            control_files._transport.clone('upload'),
1841
 
            control_files._transport.clone('packs'))
1842
 
        self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1843
 
        self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1844
 
        self._inv_thunk = InventoryKnitThunk(self, index_transport)
 
2182
            self._transport.clone('upload'),
 
2183
            self._transport.clone('packs'),
 
2184
            _format.index_builder_class,
 
2185
            _format.index_class,
 
2186
            use_chk_index=self._format.supports_chks,
 
2187
            )
 
2188
        self.inventories = KnitVersionedFiles(
 
2189
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
 
2190
                add_callback=self._pack_collection.inventory_index.add_callback,
 
2191
                deltas=True, parents=True, is_locked=self.is_locked),
 
2192
            data_access=self._pack_collection.inventory_index.data_access,
 
2193
            max_delta_chain=200)
 
2194
        self.revisions = KnitVersionedFiles(
 
2195
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
 
2196
                add_callback=self._pack_collection.revision_index.add_callback,
 
2197
                deltas=False, parents=True, is_locked=self.is_locked,
 
2198
                track_external_parent_refs=True),
 
2199
            data_access=self._pack_collection.revision_index.data_access,
 
2200
            max_delta_chain=0)
 
2201
        self.signatures = KnitVersionedFiles(
 
2202
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
 
2203
                add_callback=self._pack_collection.signature_index.add_callback,
 
2204
                deltas=False, parents=False, is_locked=self.is_locked),
 
2205
            data_access=self._pack_collection.signature_index.data_access,
 
2206
            max_delta_chain=0)
 
2207
        self.texts = KnitVersionedFiles(
 
2208
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
 
2209
                add_callback=self._pack_collection.text_index.add_callback,
 
2210
                deltas=True, parents=True, is_locked=self.is_locked),
 
2211
            data_access=self._pack_collection.text_index.data_access,
 
2212
            max_delta_chain=200)
 
2213
        if _format.supports_chks:
 
2214
            # No graph, no compression:- references from chks are between
 
2215
            # different objects not temporal versions of the same; and without
 
2216
            # some sort of temporal structure knit compression will just fail.
 
2217
            self.chk_bytes = KnitVersionedFiles(
 
2218
                _KnitGraphIndex(self._pack_collection.chk_index.combined_index,
 
2219
                    add_callback=self._pack_collection.chk_index.add_callback,
 
2220
                    deltas=False, parents=False, is_locked=self.is_locked),
 
2221
                data_access=self._pack_collection.chk_index.data_access,
 
2222
                max_delta_chain=0)
 
2223
        else:
 
2224
            self.chk_bytes = None
1845
2225
        # True when the repository object is 'write locked' (as opposed to the
1846
 
        # physical lock only taken out around changes to the pack-names list.) 
 
2226
        # physical lock only taken out around changes to the pack-names list.)
1847
2227
        # Another way to represent this would be a decorator around the control
1848
2228
        # files object that presents logical locks as physical ones - if this
1849
2229
        # gets ugly consider that alternative design. RBC 20071011
1854
2234
        self._reconcile_fixes_text_parents = True
1855
2235
        self._reconcile_backsup_inventory = False
1856
2236
 
 
2237
    def _warn_if_deprecated(self):
 
2238
        # This class isn't deprecated, but one sub-format is
 
2239
        if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
 
2240
            from bzrlib import repository
 
2241
            if repository._deprecation_warning_done:
 
2242
                return
 
2243
            repository._deprecation_warning_done = True
 
2244
            warning("Format %s for %s is deprecated - please use"
 
2245
                    " 'bzr upgrade --1.6.1-rich-root'"
 
2246
                    % (self._format, self.bzrdir.transport.base))
 
2247
 
1857
2248
    def _abort_write_group(self):
 
2249
        self.revisions._index._key_dependencies.clear()
1858
2250
        self._pack_collection._abort_write_group()
1859
2251
 
1860
 
    def _find_inconsistent_revision_parents(self):
1861
 
        """Find revisions with incorrectly cached parents.
1862
 
 
1863
 
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
1864
 
            parents-in-revision).
1865
 
        """
1866
 
        if not self.is_locked():
1867
 
            raise errors.ObjectNotLocked(self)
1868
 
        pb = ui.ui_factory.nested_progress_bar()
1869
 
        result = []
1870
 
        try:
1871
 
            revision_nodes = self._pack_collection.revision_index \
1872
 
                .combined_index.iter_all_entries()
1873
 
            index_positions = []
1874
 
            # Get the cached index values for all revisions, and also the location
1875
 
            # in each index of the revision text so we can perform linear IO.
1876
 
            for index, key, value, refs in revision_nodes:
1877
 
                pos, length = value[1:].split(' ')
1878
 
                index_positions.append((index, int(pos), key[0],
1879
 
                    tuple(parent[0] for parent in refs[0])))
1880
 
                pb.update("Reading revision index.", 0, 0)
1881
 
            index_positions.sort()
1882
 
            batch_count = len(index_positions) / 1000 + 1
1883
 
            pb.update("Checking cached revision graph.", 0, batch_count)
1884
 
            for offset in xrange(batch_count):
1885
 
                pb.update("Checking cached revision graph.", offset)
1886
 
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1887
 
                if not to_query:
1888
 
                    break
1889
 
                rev_ids = [item[2] for item in to_query]
1890
 
                revs = self.get_revisions(rev_ids)
1891
 
                for revision, item in zip(revs, to_query):
1892
 
                    index_parents = item[3]
1893
 
                    rev_parents = tuple(revision.parent_ids)
1894
 
                    if index_parents != rev_parents:
1895
 
                        result.append((revision.revision_id, index_parents, rev_parents))
1896
 
        finally:
1897
 
            pb.finished()
1898
 
        return result
1899
 
 
1900
 
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
1901
 
    def get_parents(self, revision_ids):
1902
 
        """See graph._StackedParentsProvider.get_parents."""
1903
 
        parent_map = self.get_parent_map(revision_ids)
1904
 
        return [parent_map.get(r, None) for r in revision_ids]
1905
 
 
1906
 
    def get_parent_map(self, keys):
1907
 
        """See graph._StackedParentsProvider.get_parent_map
1908
 
 
1909
 
        This implementation accesses the combined revision index to provide
1910
 
        answers.
1911
 
        """
1912
 
        self._pack_collection.ensure_loaded()
1913
 
        index = self._pack_collection.revision_index.combined_index
1914
 
        keys = set(keys)
1915
 
        if None in keys:
1916
 
            raise ValueError('get_parent_map(None) is not valid')
1917
 
        if _mod_revision.NULL_REVISION in keys:
1918
 
            keys.discard(_mod_revision.NULL_REVISION)
1919
 
            found_parents = {_mod_revision.NULL_REVISION:()}
1920
 
        else:
1921
 
            found_parents = {}
1922
 
        search_keys = set((revision_id,) for revision_id in keys)
1923
 
        for index, key, value, refs in index.iter_entries(search_keys):
1924
 
            parents = refs[0]
1925
 
            if not parents:
1926
 
                parents = (_mod_revision.NULL_REVISION,)
1927
 
            else:
1928
 
                parents = tuple(parent[0] for parent in parents)
1929
 
            found_parents[key[0]] = parents
1930
 
        return found_parents
1931
 
 
1932
 
    def has_revisions(self, revision_ids):
1933
 
        """See Repository.has_revisions()."""
1934
 
        revision_ids = set(revision_ids)
1935
 
        result = revision_ids.intersection(
1936
 
            set([None, _mod_revision.NULL_REVISION]))
1937
 
        revision_ids.difference_update(result)
1938
 
        index = self._pack_collection.revision_index.combined_index
1939
 
        keys = [(revision_id,) for revision_id in revision_ids]
1940
 
        result.update(node[1][0] for node in index.iter_entries(keys))
1941
 
        return result
 
2252
    def _get_source(self, to_format):
 
2253
        if to_format.network_name() == self._format.network_name():
 
2254
            return KnitPackStreamSource(self, to_format)
 
2255
        return super(KnitPackRepository, self)._get_source(to_format)
1942
2256
 
1943
2257
    def _make_parents_provider(self):
1944
2258
        return graph.CachingParentsProvider(self)
1945
2259
 
1946
2260
    def _refresh_data(self):
1947
 
        if self._write_lock_count == 1 or (
1948
 
            self.control_files._lock_count == 1 and
1949
 
            self.control_files._lock_mode == 'r'):
1950
 
            # forget what names there are
1951
 
            self._pack_collection.reset()
1952
 
            # XXX: Better to do an in-memory merge when acquiring a new lock -
1953
 
            # factor out code from _save_pack_names.
1954
 
            self._pack_collection.ensure_loaded()
 
2261
        if not self.is_locked():
 
2262
            return
 
2263
        self._pack_collection.reload_pack_names()
1955
2264
 
1956
2265
    def _start_write_group(self):
1957
2266
        self._pack_collection._start_write_group()
1958
2267
 
1959
2268
    def _commit_write_group(self):
1960
 
        return self._pack_collection._commit_write_group()
1961
 
 
1962
 
    def get_inventory_weave(self):
1963
 
        return self._inv_thunk.get_weave()
 
2269
        hint = self._pack_collection._commit_write_group()
 
2270
        self.revisions._index._key_dependencies.clear()
 
2271
        return hint
 
2272
 
 
2273
    def suspend_write_group(self):
 
2274
        # XXX check self._write_group is self.get_transaction()?
 
2275
        tokens = self._pack_collection._suspend_write_group()
 
2276
        self.revisions._index._key_dependencies.clear()
 
2277
        self._write_group = None
 
2278
        return tokens
 
2279
 
 
2280
    def _resume_write_group(self, tokens):
 
2281
        self._start_write_group()
 
2282
        try:
 
2283
            self._pack_collection._resume_write_group(tokens)
 
2284
        except errors.UnresumableWriteGroup:
 
2285
            self._abort_write_group()
 
2286
            raise
 
2287
        for pack in self._pack_collection._resumed_packs:
 
2288
            self.revisions._index.scan_unvalidated_index(pack.revision_index)
1964
2289
 
1965
2290
    def get_transaction(self):
1966
2291
        if self._write_lock_count:
1975
2300
        return self._write_lock_count
1976
2301
 
1977
2302
    def lock_write(self, token=None):
1978
 
        if not self._write_lock_count and self.is_locked():
 
2303
        locked = self.is_locked()
 
2304
        if not self._write_lock_count and locked:
1979
2305
            raise errors.ReadOnlyError(self)
1980
2306
        self._write_lock_count += 1
1981
2307
        if self._write_lock_count == 1:
1982
 
            from bzrlib import transactions
1983
2308
            self._transaction = transactions.WriteTransaction()
1984
 
        self._refresh_data()
 
2309
        if not locked:
 
2310
            if 'relock' in debug.debug_flags and self._prev_lock == 'w':
 
2311
                note('%r was write locked again', self)
 
2312
            self._prev_lock = 'w'
 
2313
            for repo in self._fallback_repositories:
 
2314
                # Writes don't affect fallback repos
 
2315
                repo.lock_read()
 
2316
            self._refresh_data()
1985
2317
 
1986
2318
    def lock_read(self):
 
2319
        locked = self.is_locked()
1987
2320
        if self._write_lock_count:
1988
2321
            self._write_lock_count += 1
1989
2322
        else:
1990
2323
            self.control_files.lock_read()
1991
 
        self._refresh_data()
 
2324
        if not locked:
 
2325
            if 'relock' in debug.debug_flags and self._prev_lock == 'r':
 
2326
                note('%r was read locked again', self)
 
2327
            self._prev_lock = 'r'
 
2328
            for repo in self._fallback_repositories:
 
2329
                repo.lock_read()
 
2330
            self._refresh_data()
1992
2331
 
1993
2332
    def leave_lock_in_place(self):
1994
2333
        # not supported - raise an error
1999
2338
        raise NotImplementedError(self.dont_leave_lock_in_place)
2000
2339
 
2001
2340
    @needs_write_lock
2002
 
    def pack(self):
 
2341
    def pack(self, hint=None):
2003
2342
        """Compress the data within the repository.
2004
2343
 
2005
2344
        This will pack all the data to a single pack. In future it may
2006
2345
        recompress deltas or do other such expensive operations.
2007
2346
        """
2008
 
        self._pack_collection.pack()
 
2347
        self._pack_collection.pack(hint=hint)
2009
2348
 
2010
2349
    @needs_write_lock
2011
2350
    def reconcile(self, other=None, thorough=False):
2015
2354
        reconciler.reconcile()
2016
2355
        return reconciler
2017
2356
 
 
2357
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
 
2358
        packer = ReconcilePacker(collection, packs, extension, revs)
 
2359
        return packer.pack(pb)
 
2360
 
 
2361
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2018
2362
    def unlock(self):
2019
2363
        if self._write_lock_count == 1 and self._write_group is not None:
2020
2364
            self.abort_write_group()
2032
2376
        else:
2033
2377
            self.control_files.unlock()
2034
2378
 
 
2379
        if not self.is_locked():
 
2380
            for repo in self._fallback_repositories:
 
2381
                repo.unlock()
 
2382
 
 
2383
 
 
2384
class KnitPackStreamSource(StreamSource):
 
2385
    """A StreamSource used to transfer data between same-format KnitPack repos.
 
2386
 
 
2387
    This source assumes:
 
2388
        1) Same serialization format for all objects
 
2389
        2) Same root information
 
2390
        3) XML format inventories
 
2391
        4) Atomic inserts (so we can stream inventory texts before text
 
2392
           content)
 
2393
        5) No chk_bytes
 
2394
    """
 
2395
 
 
2396
    def __init__(self, from_repository, to_format):
 
2397
        super(KnitPackStreamSource, self).__init__(from_repository, to_format)
 
2398
        self._text_keys = None
 
2399
        self._text_fetch_order = 'unordered'
 
2400
 
 
2401
    def _get_filtered_inv_stream(self, revision_ids):
 
2402
        from_repo = self.from_repository
 
2403
        parent_ids = from_repo._find_parent_ids_of_revisions(revision_ids)
 
2404
        parent_keys = [(p,) for p in parent_ids]
 
2405
        find_text_keys = from_repo._find_text_key_references_from_xml_inventory_lines
 
2406
        parent_text_keys = set(find_text_keys(
 
2407
            from_repo._inventory_xml_lines_for_keys(parent_keys)))
 
2408
        content_text_keys = set()
 
2409
        knit = KnitVersionedFiles(None, None)
 
2410
        factory = KnitPlainFactory()
 
2411
        def find_text_keys_from_content(record):
 
2412
            if record.storage_kind not in ('knit-delta-gz', 'knit-ft-gz'):
 
2413
                raise ValueError("Unknown content storage kind for"
 
2414
                    " inventory text: %s" % (record.storage_kind,))
 
2415
            # It's a knit record, it has a _raw_record field (even if it was
 
2416
            # reconstituted from a network stream).
 
2417
            raw_data = record._raw_record
 
2418
            # read the entire thing
 
2419
            revision_id = record.key[-1]
 
2420
            content, _ = knit._parse_record(revision_id, raw_data)
 
2421
            if record.storage_kind == 'knit-delta-gz':
 
2422
                line_iterator = factory.get_linedelta_content(content)
 
2423
            elif record.storage_kind == 'knit-ft-gz':
 
2424
                line_iterator = factory.get_fulltext_content(content)
 
2425
            content_text_keys.update(find_text_keys(
 
2426
                [(line, revision_id) for line in line_iterator]))
 
2427
        revision_keys = [(r,) for r in revision_ids]
 
2428
        def _filtered_inv_stream():
 
2429
            source_vf = from_repo.inventories
 
2430
            stream = source_vf.get_record_stream(revision_keys,
 
2431
                                                 'unordered', False)
 
2432
            for record in stream:
 
2433
                if record.storage_kind == 'absent':
 
2434
                    raise errors.NoSuchRevision(from_repo, record.key)
 
2435
                find_text_keys_from_content(record)
 
2436
                yield record
 
2437
            self._text_keys = content_text_keys - parent_text_keys
 
2438
        return ('inventories', _filtered_inv_stream())
 
2439
 
 
2440
    def _get_text_stream(self):
 
2441
        # Note: We know we don't have to handle adding root keys, because both
 
2442
        # the source and target are the identical network name.
 
2443
        text_stream = self.from_repository.texts.get_record_stream(
 
2444
                        self._text_keys, self._text_fetch_order, False)
 
2445
        return ('texts', text_stream)
 
2446
 
 
2447
    def get_stream(self, search):
 
2448
        revision_ids = search.get_keys()
 
2449
        for stream_info in self._fetch_revision_texts(revision_ids):
 
2450
            yield stream_info
 
2451
        self._revision_keys = [(rev_id,) for rev_id in revision_ids]
 
2452
        yield self._get_filtered_inv_stream(revision_ids)
 
2453
        yield self._get_text_stream()
 
2454
 
 
2455
 
2035
2456
 
2036
2457
class RepositoryFormatPack(MetaDirRepositoryFormat):
2037
2458
    """Format logic for pack structured repositories.
2058
2479
    # Set this attribute in derived clases to control the _serializer that the
2059
2480
    # repository objects will have passed to their constructor.
2060
2481
    _serializer = None
 
2482
    # Packs are not confused by ghosts.
 
2483
    supports_ghosts = True
2061
2484
    # External references are not supported in pack repositories yet.
2062
2485
    supports_external_lookups = False
2063
 
 
2064
 
    def _get_control_store(self, repo_transport, control_files):
2065
 
        """Return the control store for this repository."""
2066
 
        return VersionedFileStore(
2067
 
            repo_transport,
2068
 
            prefixed=False,
2069
 
            file_mode=control_files._file_mode,
2070
 
            versionedfile_class=knit.make_file_knit,
2071
 
            versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
2072
 
            )
2073
 
 
2074
 
    def _get_revision_store(self, repo_transport, control_files):
2075
 
        """See RepositoryFormat._get_revision_store()."""
2076
 
        versioned_file_store = VersionedFileStore(
2077
 
            repo_transport,
2078
 
            file_mode=control_files._file_mode,
2079
 
            prefixed=False,
2080
 
            precious=True,
2081
 
            versionedfile_class=knit.make_file_knit,
2082
 
            versionedfile_kwargs={'delta': False,
2083
 
                                  'factory': knit.KnitPlainFactory(),
2084
 
                                 },
2085
 
            escaped=True,
2086
 
            )
2087
 
        return KnitRevisionStore(versioned_file_store)
2088
 
 
2089
 
    def _get_text_store(self, transport, control_files):
2090
 
        """See RepositoryFormat._get_text_store()."""
2091
 
        return self._get_versioned_file_store('knits',
2092
 
                                  transport,
2093
 
                                  control_files,
2094
 
                                  versionedfile_class=knit.make_file_knit,
2095
 
                                  versionedfile_kwargs={
2096
 
                                      'create_parent_dir': True,
2097
 
                                      'delay_create': True,
2098
 
                                      'dir_mode': control_files._dir_mode,
2099
 
                                  },
2100
 
                                  escaped=True)
 
2486
    # Most pack formats do not use chk lookups.
 
2487
    supports_chks = False
 
2488
    # What index classes to use
 
2489
    index_builder_class = None
 
2490
    index_class = None
 
2491
    _fetch_uses_deltas = True
 
2492
    fast_deltas = False
2101
2493
 
2102
2494
    def initialize(self, a_bzrdir, shared=False):
2103
2495
        """Create a pack based repository.
2109
2501
        """
2110
2502
        mutter('creating repository in %s.', a_bzrdir.transport.base)
2111
2503
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
2112
 
        builder = GraphIndexBuilder()
 
2504
        builder = self.index_builder_class()
2113
2505
        files = [('pack-names', builder.finish())]
2114
2506
        utf8_files = [('format', self.get_format_string())]
2115
 
        
 
2507
 
2116
2508
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2117
2509
        return self.open(a_bzrdir=a_bzrdir, _found=True)
2118
2510
 
2119
2511
    def open(self, a_bzrdir, _found=False, _override_transport=None):
2120
2512
        """See RepositoryFormat.open().
2121
 
        
 
2513
 
2122
2514
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
2123
2515
                                    repository at a slightly different url
2124
2516
                                    than normal. I.e. during 'upgrade'.
2131
2523
            repo_transport = a_bzrdir.get_repository_transport(None)
2132
2524
        control_files = lockable_files.LockableFiles(repo_transport,
2133
2525
                                'lock', lockdir.LockDir)
2134
 
        text_store = self._get_text_store(repo_transport, control_files)
2135
 
        control_store = self._get_control_store(repo_transport, control_files)
2136
 
        _revision_store = self._get_revision_store(repo_transport, control_files)
2137
2526
        return self.repository_class(_format=self,
2138
2527
                              a_bzrdir=a_bzrdir,
2139
2528
                              control_files=control_files,
2140
 
                              _revision_store=_revision_store,
2141
 
                              control_store=control_store,
2142
 
                              text_store=text_store,
2143
2529
                              _commit_builder_class=self._commit_builder_class,
2144
2530
                              _serializer=self._serializer)
2145
2531
 
2152
2538
 
2153
2539
    repository_class = KnitPackRepository
2154
2540
    _commit_builder_class = PackCommitBuilder
2155
 
    _serializer = xml5.serializer_v5
 
2541
    @property
 
2542
    def _serializer(self):
 
2543
        return xml5.serializer_v5
 
2544
    # What index classes to use
 
2545
    index_builder_class = InMemoryGraphIndex
 
2546
    index_class = GraphIndex
2156
2547
 
2157
2548
    def _get_matching_bzrdir(self):
2158
2549
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2170
2561
        """See RepositoryFormat.get_format_description()."""
2171
2562
        return "Packs containing knits without subtree support"
2172
2563
 
2173
 
    def check_conversion_target(self, target_format):
2174
 
        pass
2175
 
 
2176
2564
 
2177
2565
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2178
2566
    """A subtrees parameterized Pack repository.
2188
2576
    _commit_builder_class = PackRootCommitBuilder
2189
2577
    rich_root_data = True
2190
2578
    supports_tree_reference = True
2191
 
    _serializer = xml7.serializer_v7
 
2579
    @property
 
2580
    def _serializer(self):
 
2581
        return xml7.serializer_v7
 
2582
    # What index classes to use
 
2583
    index_builder_class = InMemoryGraphIndex
 
2584
    index_class = GraphIndex
2192
2585
 
2193
2586
    def _get_matching_bzrdir(self):
2194
2587
        return bzrdir.format_registry.make_bzrdir(
2199
2592
 
2200
2593
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2201
2594
 
2202
 
    def check_conversion_target(self, target_format):
2203
 
        if not target_format.rich_root_data:
2204
 
            raise errors.BadConversionTarget(
2205
 
                'Does not support rich root data.', target_format)
2206
 
        if not getattr(target_format, 'supports_tree_reference', False):
2207
 
            raise errors.BadConversionTarget(
2208
 
                'Does not support nested trees', target_format)
2209
 
            
2210
2595
    def get_format_string(self):
2211
2596
        """See RepositoryFormat.get_format_string()."""
2212
2597
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2229
2614
    _commit_builder_class = PackRootCommitBuilder
2230
2615
    rich_root_data = True
2231
2616
    supports_tree_reference = False
2232
 
    _serializer = xml6.serializer_v6
 
2617
    @property
 
2618
    def _serializer(self):
 
2619
        return xml6.serializer_v6
 
2620
    # What index classes to use
 
2621
    index_builder_class = InMemoryGraphIndex
 
2622
    index_class = GraphIndex
2233
2623
 
2234
2624
    def _get_matching_bzrdir(self):
2235
2625
        return bzrdir.format_registry.make_bzrdir(
2240
2630
 
2241
2631
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2242
2632
 
2243
 
    def check_conversion_target(self, target_format):
2244
 
        if not target_format.rich_root_data:
2245
 
            raise errors.BadConversionTarget(
2246
 
                'Does not support rich root data.', target_format)
2247
 
 
2248
2633
    def get_format_string(self):
2249
2634
        """See RepositoryFormat.get_format_string()."""
2250
2635
        return ("Bazaar pack repository format 1 with rich root"
2255
2640
        return "Packs containing knits with rich root support\n"
2256
2641
 
2257
2642
 
2258
 
class RepositoryFormatPackDevelopment0(RepositoryFormatPack):
2259
 
    """A no-subtrees development repository.
2260
 
 
2261
 
    This format should be retained until the second release after bzr 1.0.
2262
 
 
2263
 
    No changes to the disk behaviour from pack-0.92.
2264
 
    """
2265
 
 
2266
 
    repository_class = KnitPackRepository
2267
 
    _commit_builder_class = PackCommitBuilder
2268
 
    _serializer = xml5.serializer_v5
2269
 
 
2270
 
    def _get_matching_bzrdir(self):
2271
 
        return bzrdir.format_registry.make_bzrdir('development0')
2272
 
 
2273
 
    def _ignore_setting_bzrdir(self, format):
2274
 
        pass
2275
 
 
2276
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2277
 
 
2278
 
    def get_format_string(self):
2279
 
        """See RepositoryFormat.get_format_string()."""
2280
 
        return "Bazaar development format 0 (needs bzr.dev from before 1.3)\n"
2281
 
 
2282
 
    def get_format_description(self):
2283
 
        """See RepositoryFormat.get_format_description()."""
2284
 
        return ("Development repository format, currently the same as "
2285
 
            "pack-0.92\n")
2286
 
 
2287
 
    def check_conversion_target(self, target_format):
2288
 
        pass
2289
 
 
2290
 
 
2291
 
class RepositoryFormatPackDevelopment0Subtree(RepositoryFormatPack):
 
2643
class RepositoryFormatKnitPack5(RepositoryFormatPack):
 
2644
    """Repository that supports external references to allow stacking.
 
2645
 
 
2646
    New in release 1.6.
 
2647
 
 
2648
    Supports external lookups, which results in non-truncated ghosts after
 
2649
    reconcile compared to pack-0.92 formats.
 
2650
    """
 
2651
 
 
2652
    repository_class = KnitPackRepository
 
2653
    _commit_builder_class = PackCommitBuilder
 
2654
    supports_external_lookups = True
 
2655
    # What index classes to use
 
2656
    index_builder_class = InMemoryGraphIndex
 
2657
    index_class = GraphIndex
 
2658
 
 
2659
    @property
 
2660
    def _serializer(self):
 
2661
        return xml5.serializer_v5
 
2662
 
 
2663
    def _get_matching_bzrdir(self):
 
2664
        return bzrdir.format_registry.make_bzrdir('1.6')
 
2665
 
 
2666
    def _ignore_setting_bzrdir(self, format):
 
2667
        pass
 
2668
 
 
2669
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2670
 
 
2671
    def get_format_string(self):
 
2672
        """See RepositoryFormat.get_format_string()."""
 
2673
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
 
2674
 
 
2675
    def get_format_description(self):
 
2676
        """See RepositoryFormat.get_format_description()."""
 
2677
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
 
2678
 
 
2679
 
 
2680
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
 
2681
    """A repository with rich roots and stacking.
 
2682
 
 
2683
    New in release 1.6.1.
 
2684
 
 
2685
    Supports stacking on other repositories, allowing data to be accessed
 
2686
    without being stored locally.
 
2687
    """
 
2688
 
 
2689
    repository_class = KnitPackRepository
 
2690
    _commit_builder_class = PackRootCommitBuilder
 
2691
    rich_root_data = True
 
2692
    supports_tree_reference = False # no subtrees
 
2693
    supports_external_lookups = True
 
2694
    # What index classes to use
 
2695
    index_builder_class = InMemoryGraphIndex
 
2696
    index_class = GraphIndex
 
2697
 
 
2698
    @property
 
2699
    def _serializer(self):
 
2700
        return xml6.serializer_v6
 
2701
 
 
2702
    def _get_matching_bzrdir(self):
 
2703
        return bzrdir.format_registry.make_bzrdir(
 
2704
            '1.6.1-rich-root')
 
2705
 
 
2706
    def _ignore_setting_bzrdir(self, format):
 
2707
        pass
 
2708
 
 
2709
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2710
 
 
2711
    def get_format_string(self):
 
2712
        """See RepositoryFormat.get_format_string()."""
 
2713
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
 
2714
 
 
2715
    def get_format_description(self):
 
2716
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
 
2717
 
 
2718
 
 
2719
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
 
2720
    """A repository with rich roots and external references.
 
2721
 
 
2722
    New in release 1.6.
 
2723
 
 
2724
    Supports external lookups, which results in non-truncated ghosts after
 
2725
    reconcile compared to pack-0.92 formats.
 
2726
 
 
2727
    This format was deprecated because the serializer it uses accidentally
 
2728
    supported subtrees, when the format was not intended to. This meant that
 
2729
    someone could accidentally fetch from an incorrect repository.
 
2730
    """
 
2731
 
 
2732
    repository_class = KnitPackRepository
 
2733
    _commit_builder_class = PackRootCommitBuilder
 
2734
    rich_root_data = True
 
2735
    supports_tree_reference = False # no subtrees
 
2736
 
 
2737
    supports_external_lookups = True
 
2738
    # What index classes to use
 
2739
    index_builder_class = InMemoryGraphIndex
 
2740
    index_class = GraphIndex
 
2741
 
 
2742
    @property
 
2743
    def _serializer(self):
 
2744
        return xml7.serializer_v7
 
2745
 
 
2746
    def _get_matching_bzrdir(self):
 
2747
        matching = bzrdir.format_registry.make_bzrdir(
 
2748
            '1.6.1-rich-root')
 
2749
        matching.repository_format = self
 
2750
        return matching
 
2751
 
 
2752
    def _ignore_setting_bzrdir(self, format):
 
2753
        pass
 
2754
 
 
2755
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2756
 
 
2757
    def get_format_string(self):
 
2758
        """See RepositoryFormat.get_format_string()."""
 
2759
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
 
2760
 
 
2761
    def get_format_description(self):
 
2762
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
 
2763
                " (deprecated)")
 
2764
 
 
2765
 
 
2766
class RepositoryFormatKnitPack6(RepositoryFormatPack):
 
2767
    """A repository with stacking and btree indexes,
 
2768
    without rich roots or subtrees.
 
2769
 
 
2770
    This is equivalent to pack-1.6 with B+Tree indices.
 
2771
    """
 
2772
 
 
2773
    repository_class = KnitPackRepository
 
2774
    _commit_builder_class = PackCommitBuilder
 
2775
    supports_external_lookups = True
 
2776
    # What index classes to use
 
2777
    index_builder_class = BTreeBuilder
 
2778
    index_class = BTreeGraphIndex
 
2779
 
 
2780
    @property
 
2781
    def _serializer(self):
 
2782
        return xml5.serializer_v5
 
2783
 
 
2784
    def _get_matching_bzrdir(self):
 
2785
        return bzrdir.format_registry.make_bzrdir('1.9')
 
2786
 
 
2787
    def _ignore_setting_bzrdir(self, format):
 
2788
        pass
 
2789
 
 
2790
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2791
 
 
2792
    def get_format_string(self):
 
2793
        """See RepositoryFormat.get_format_string()."""
 
2794
        return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
 
2795
 
 
2796
    def get_format_description(self):
 
2797
        """See RepositoryFormat.get_format_description()."""
 
2798
        return "Packs 6 (uses btree indexes, requires bzr 1.9)"
 
2799
 
 
2800
 
 
2801
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
 
2802
    """A repository with rich roots, no subtrees, stacking and btree indexes.
 
2803
 
 
2804
    1.6-rich-root with B+Tree indices.
 
2805
    """
 
2806
 
 
2807
    repository_class = KnitPackRepository
 
2808
    _commit_builder_class = PackRootCommitBuilder
 
2809
    rich_root_data = True
 
2810
    supports_tree_reference = False # no subtrees
 
2811
    supports_external_lookups = True
 
2812
    # What index classes to use
 
2813
    index_builder_class = BTreeBuilder
 
2814
    index_class = BTreeGraphIndex
 
2815
 
 
2816
    @property
 
2817
    def _serializer(self):
 
2818
        return xml6.serializer_v6
 
2819
 
 
2820
    def _get_matching_bzrdir(self):
 
2821
        return bzrdir.format_registry.make_bzrdir(
 
2822
            '1.9-rich-root')
 
2823
 
 
2824
    def _ignore_setting_bzrdir(self, format):
 
2825
        pass
 
2826
 
 
2827
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2828
 
 
2829
    def get_format_string(self):
 
2830
        """See RepositoryFormat.get_format_string()."""
 
2831
        return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
 
2832
 
 
2833
    def get_format_description(self):
 
2834
        return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
 
2835
 
 
2836
 
 
2837
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2292
2838
    """A subtrees development repository.
2293
2839
 
2294
 
    This format should be retained until the second release after bzr 1.0.
2295
 
 
2296
 
    No changes to the disk behaviour from pack-0.92-subtree.
 
2840
    This format should be retained until the second release after bzr 1.7.
 
2841
 
 
2842
    1.6.1-subtree[as it might have been] with B+Tree indices.
 
2843
 
 
2844
    This is [now] retained until we have a CHK based subtree format in
 
2845
    development.
2297
2846
    """
2298
2847
 
2299
2848
    repository_class = KnitPackRepository
2300
2849
    _commit_builder_class = PackRootCommitBuilder
2301
2850
    rich_root_data = True
2302
2851
    supports_tree_reference = True
2303
 
    _serializer = xml7.serializer_v7
 
2852
    supports_external_lookups = True
 
2853
    # What index classes to use
 
2854
    index_builder_class = BTreeBuilder
 
2855
    index_class = BTreeGraphIndex
 
2856
 
 
2857
    @property
 
2858
    def _serializer(self):
 
2859
        return xml7.serializer_v7
2304
2860
 
2305
2861
    def _get_matching_bzrdir(self):
2306
2862
        return bzrdir.format_registry.make_bzrdir(
2307
 
            'development0-subtree')
 
2863
            'development-subtree')
2308
2864
 
2309
2865
    def _ignore_setting_bzrdir(self, format):
2310
2866
        pass
2311
2867
 
2312
2868
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2313
2869
 
2314
 
    def check_conversion_target(self, target_format):
2315
 
        if not target_format.rich_root_data:
2316
 
            raise errors.BadConversionTarget(
2317
 
                'Does not support rich root data.', target_format)
2318
 
        if not getattr(target_format, 'supports_tree_reference', False):
2319
 
            raise errors.BadConversionTarget(
2320
 
                'Does not support nested trees', target_format)
2321
 
            
2322
2870
    def get_format_string(self):
2323
2871
        """See RepositoryFormat.get_format_string()."""
2324
 
        return ("Bazaar development format 0 with subtree support "
2325
 
            "(needs bzr.dev from before 1.3)\n")
 
2872
        return ("Bazaar development format 2 with subtree support "
 
2873
            "(needs bzr.dev from before 1.8)\n")
2326
2874
 
2327
2875
    def get_format_description(self):
2328
2876
        """See RepositoryFormat.get_format_description()."""
2329
2877
        return ("Development repository format, currently the same as "
2330
 
            "pack-0.92-subtree\n")
2331
 
 
 
2878
            "1.6.1-subtree with B+Tree indices.\n")
2332
2879