~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: John Arbash Meinel
  • Author(s): Mark Hammond
  • Date: 2008-09-09 17:02:21 UTC
  • mto: This revision was merged to the branch mainline in revision 3697.
  • Revision ID: john@arbash-meinel.com-20080909170221-svim3jw2mrz0amp3
An updated transparent icon for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
from bzrlib.lazy_import import lazy_import
18
18
lazy_import(globals(), """
19
19
from itertools import izip
20
 
import math
21
20
import md5
22
21
import time
23
22
 
24
23
from bzrlib import (
25
 
        debug,
26
 
        pack,
27
 
        ui,
28
 
        )
 
24
    debug,
 
25
    graph,
 
26
    pack,
 
27
    transactions,
 
28
    ui,
 
29
    )
29
30
from bzrlib.index import (
30
31
    GraphIndex,
31
32
    GraphIndexBuilder,
33
34
    CombinedGraphIndex,
34
35
    GraphIndexPrefixAdapter,
35
36
    )
36
 
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
37
 
from bzrlib.osutils import rand_chars
38
 
from bzrlib.pack import ContainerWriter
39
 
from bzrlib.store import revision
 
37
from bzrlib.knit import (
 
38
    KnitPlainFactory,
 
39
    KnitVersionedFiles,
 
40
    _KnitGraphIndex,
 
41
    _DirectPackAccess,
 
42
    )
 
43
from bzrlib.osutils import rand_chars, split_lines
 
44
from bzrlib import tsort
40
45
""")
41
46
from bzrlib import (
42
47
    bzrdir,
43
 
    deprecated_graph,
44
48
    errors,
45
 
    knit,
46
49
    lockable_files,
47
50
    lockdir,
48
 
    osutils,
49
 
    transactions,
 
51
    symbol_versioning,
50
52
    xml5,
 
53
    xml6,
51
54
    xml7,
52
55
    )
53
56
 
54
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
57
from bzrlib.decorators import needs_write_lock
55
58
from bzrlib.repofmt.knitrepo import KnitRepository
56
59
from bzrlib.repository import (
57
60
    CommitBuilder,
58
 
    MetaDirRepository,
59
61
    MetaDirRepositoryFormat,
 
62
    RepositoryFormat,
60
63
    RootCommitBuilder,
61
64
    )
62
65
import bzrlib.revision as _mod_revision
63
 
from bzrlib.store.revision.knit import KnitRevisionStore
64
 
from bzrlib.store.versioned import VersionedFileStore
65
 
from bzrlib.trace import mutter, note, warning
 
66
from bzrlib.trace import (
 
67
    mutter,
 
68
    warning,
 
69
    )
66
70
 
67
71
 
68
72
class PackCommitBuilder(CommitBuilder):
72
76
    added text, reducing memory and object pressure.
73
77
    """
74
78
 
75
 
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
76
 
        return self.repository._pack_collection._add_text_to_weave(file_id,
77
 
            self._new_revision_id, new_lines, parents, nostore_sha,
78
 
            self.random_revid)
 
79
    def __init__(self, repository, parents, config, timestamp=None,
 
80
                 timezone=None, committer=None, revprops=None,
 
81
                 revision_id=None):
 
82
        CommitBuilder.__init__(self, repository, parents, config,
 
83
            timestamp=timestamp, timezone=timezone, committer=committer,
 
84
            revprops=revprops, revision_id=revision_id)
 
85
        self._file_graph = graph.Graph(
 
86
            repository._pack_collection.text_index.combined_index)
 
87
 
 
88
    def _heads(self, file_id, revision_ids):
 
89
        keys = [(file_id, revision_id) for revision_id in revision_ids]
 
90
        return set([key[1] for key in self._file_graph.heads(keys)])
79
91
 
80
92
 
81
93
class PackRootCommitBuilder(RootCommitBuilder):
85
97
    added text, reducing memory and object pressure.
86
98
    """
87
99
 
88
 
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
89
 
        return self.repository._pack_collection._add_text_to_weave(file_id,
90
 
            self._new_revision_id, new_lines, parents, nostore_sha,
91
 
            self.random_revid)
 
100
    def __init__(self, repository, parents, config, timestamp=None,
 
101
                 timezone=None, committer=None, revprops=None,
 
102
                 revision_id=None):
 
103
        CommitBuilder.__init__(self, repository, parents, config,
 
104
            timestamp=timestamp, timezone=timezone, committer=committer,
 
105
            revprops=revprops, revision_id=revision_id)
 
106
        self._file_graph = graph.Graph(
 
107
            repository._pack_collection.text_index.combined_index)
 
108
 
 
109
    def _heads(self, file_id, revision_ids):
 
110
        keys = [(file_id, revision_id) for revision_id in revision_ids]
 
111
        return set([key[1] for key in self._file_graph.heads(keys)])
92
112
 
93
113
 
94
114
class Pack(object):
110
130
        :param text_index: A GraphIndex for determining what file texts
111
131
            are present in the pack and accessing the locations of their
112
132
            texts/deltas (via (fileid, revisionid) tuples).
113
 
        :param revision_index: A GraphIndex for determining what signatures are
 
133
        :param signature_index: A GraphIndex for determining what signatures are
114
134
            present in the Pack and accessing the locations of their texts.
115
135
        """
116
136
        self.revision_index = revision_index
145
165
        """The text index is the name + .tix."""
146
166
        return self.index_name('text', name)
147
167
 
 
168
    def _external_compression_parents_of_texts(self):
 
169
        keys = set()
 
170
        refs = set()
 
171
        for node in self.text_index.iter_all_entries():
 
172
            keys.add(node[1])
 
173
            refs.update(node[3][1])
 
174
        return refs - keys
 
175
 
148
176
 
149
177
class ExistingPack(Pack):
150
178
    """An in memory proxy for an existing .pack and its disk indices."""
160
188
            signature_index)
161
189
        self.name = name
162
190
        self.pack_transport = pack_transport
163
 
        assert None not in (revision_index, inventory_index, text_index,
164
 
            signature_index, name, pack_transport)
 
191
        if None in (revision_index, inventory_index, text_index,
 
192
                signature_index, name, pack_transport):
 
193
            raise AssertionError()
165
194
 
166
195
    def __eq__(self, other):
167
196
        return self.__dict__ == other.__dict__
171
200
 
172
201
    def __repr__(self):
173
202
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
174
 
            id(self), self.transport, self.name)
 
203
            id(self), self.pack_transport, self.name)
175
204
 
176
205
 
177
206
class NewPack(Pack):
187
216
        }
188
217
 
189
218
    def __init__(self, upload_transport, index_transport, pack_transport,
190
 
        upload_suffix=''):
 
219
        upload_suffix='', file_mode=None):
191
220
        """Create a NewPack instance.
192
221
 
193
222
        :param upload_transport: A writable transport for the pack to be
199
228
            upload_transport.clone('../packs').
200
229
        :param upload_suffix: An optional suffix to be given to any temporary
201
230
            files created during the pack creation. e.g '.autopack'
 
231
        :param file_mode: An optional file mode to create the new files with.
202
232
        """
203
233
        # The relative locations of the packs are constrained, but all are
204
234
        # passed in because the caller has them, so as to avoid object churn.
223
253
        self.index_transport = index_transport
224
254
        # where is the pack renamed to when it is finished?
225
255
        self.pack_transport = pack_transport
 
256
        # What file mode to upload the pack and indices with.
 
257
        self._file_mode = file_mode
226
258
        # tracks the content written to the .pack file.
227
259
        self._hash = md5.new()
228
260
        # a four-tuple with the length in bytes of the indices, once the pack
239
271
        self.start_time = time.time()
240
272
        # open an output stream for the data added to the pack.
241
273
        self.write_stream = self.upload_transport.open_write_stream(
242
 
            self.random_name)
 
274
            self.random_name, mode=self._file_mode)
243
275
        if 'pack' in debug.debug_flags:
244
276
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
245
277
                time.ctime(), self.upload_transport.base, self.random_name,
281
313
 
282
314
    def access_tuple(self):
283
315
        """Return a tuple (transport, name) for the pack content."""
284
 
        assert self._state in ('open', 'finished')
285
316
        if self._state == 'finished':
286
317
            return Pack.access_tuple(self)
287
 
        else:
 
318
        elif self._state == 'open':
288
319
            return self.upload_transport, self.random_name
 
320
        else:
 
321
            raise AssertionError(self._state)
289
322
 
290
323
    def data_inserted(self):
291
324
        """True if data has been added to this pack."""
342
375
                self.pack_transport, self.name,
343
376
                time.time() - self.start_time)
344
377
 
 
378
    def flush(self):
 
379
        """Flush any current data."""
 
380
        if self._buffer[1]:
 
381
            bytes = ''.join(self._buffer[0])
 
382
            self.write_stream.write(bytes)
 
383
            self._hash.update(bytes)
 
384
            self._buffer[:] = [[], 0]
 
385
 
345
386
    def index_name(self, index_type, name):
346
387
        """Get the disk name of an index type for pack name 'name'."""
347
388
        return name + NewPack.index_definitions[index_type][0]
368
409
        """
369
410
        index_name = self.index_name(index_type, self.name)
370
411
        self.index_sizes[self.index_offset(index_type)] = \
371
 
            self.index_transport.put_file(index_name, index.finish())
 
412
            self.index_transport.put_file(index_name, index.finish(),
 
413
            mode=self._file_mode)
372
414
        if 'pack' in debug.debug_flags:
373
415
            # XXX: size might be interesting?
374
416
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
400
442
        """Create an AggregateIndex."""
401
443
        self.index_to_pack = {}
402
444
        self.combined_index = CombinedGraphIndex([])
403
 
        self.knit_access = _PackAccess(self.index_to_pack)
 
445
        self.data_access = _DirectPackAccess(self.index_to_pack)
 
446
        self.add_callback = None
404
447
 
405
448
    def replace_indices(self, index_to_pack, indices):
406
449
        """Replace the current mappings with fresh ones.
445
488
        :param index: An index from the pack parameter.
446
489
        :param pack: A Pack instance.
447
490
        """
448
 
        assert self.add_callback is None, \
449
 
            "%s already has a writable index through %s" % \
450
 
            (self, self.add_callback)
 
491
        if self.add_callback is not None:
 
492
            raise AssertionError(
 
493
                "%s already has a writable index through %s" % \
 
494
                (self, self.add_callback))
451
495
        # allow writing: queue writes to a new index
452
496
        self.add_index(index, pack)
453
497
        # Updates the index to packs mapping as a side effect,
454
 
        self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
 
498
        self.data_access.set_writer(pack._writer, index, pack.access_tuple())
455
499
        self.add_callback = index.add_nodes
456
500
 
457
501
    def clear(self):
458
502
        """Reset all the aggregate data to nothing."""
459
 
        self.knit_access.set_writer(None, None, (None, None))
 
503
        self.data_access.set_writer(None, None, (None, None))
460
504
        self.index_to_pack.clear()
461
505
        del self.combined_index._indices[:]
462
506
        self.add_callback = None
472
516
        if (self.add_callback is not None and
473
517
            getattr(index, 'add_nodes', None) == self.add_callback):
474
518
            self.add_callback = None
475
 
            self.knit_access.set_writer(None, None, (None, None))
 
519
            self.data_access.set_writer(None, None, (None, None))
 
520
 
 
521
 
 
522
class Packer(object):
 
523
    """Create a pack from packs."""
 
524
 
 
525
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
 
526
        """Create a Packer.
 
527
 
 
528
        :param pack_collection: A RepositoryPackCollection object where the
 
529
            new pack is being written to.
 
530
        :param packs: The packs to combine.
 
531
        :param suffix: The suffix to use on the temporary files for the pack.
 
532
        :param revision_ids: Revision ids to limit the pack to.
 
533
        """
 
534
        self.packs = packs
 
535
        self.suffix = suffix
 
536
        self.revision_ids = revision_ids
 
537
        # The pack object we are creating.
 
538
        self.new_pack = None
 
539
        self._pack_collection = pack_collection
 
540
        # The index layer keys for the revisions being copied. None for 'all
 
541
        # objects'.
 
542
        self._revision_keys = None
 
543
        # What text keys to copy. None for 'all texts'. This is set by
 
544
        # _copy_inventory_texts
 
545
        self._text_filter = None
 
546
        self._extra_init()
 
547
 
 
548
    def _extra_init(self):
 
549
        """A template hook to allow extending the constructor trivially."""
 
550
 
 
551
    def pack(self, pb=None):
 
552
        """Create a new pack by reading data from other packs.
 
553
 
 
554
        This does little more than a bulk copy of data. One key difference
 
555
        is that data with the same item key across multiple packs is elided
 
556
        from the output. The new pack is written into the current pack store
 
557
        along with its indices, and the name added to the pack names. The 
 
558
        source packs are not altered and are not required to be in the current
 
559
        pack collection.
 
560
 
 
561
        :param pb: An optional progress bar to use. A nested bar is created if
 
562
            this is None.
 
563
        :return: A Pack object, or None if nothing was copied.
 
564
        """
 
565
        # open a pack - using the same name as the last temporary file
 
566
        # - which has already been flushed, so its safe.
 
567
        # XXX: - duplicate code warning with start_write_group; fix before
 
568
        #      considering 'done'.
 
569
        if self._pack_collection._new_pack is not None:
 
570
            raise errors.BzrError('call to create_pack_from_packs while '
 
571
                'another pack is being written.')
 
572
        if self.revision_ids is not None:
 
573
            if len(self.revision_ids) == 0:
 
574
                # silly fetch request.
 
575
                return None
 
576
            else:
 
577
                self.revision_ids = frozenset(self.revision_ids)
 
578
                self.revision_keys = frozenset((revid,) for revid in
 
579
                    self.revision_ids)
 
580
        if pb is None:
 
581
            self.pb = ui.ui_factory.nested_progress_bar()
 
582
        else:
 
583
            self.pb = pb
 
584
        try:
 
585
            return self._create_pack_from_packs()
 
586
        finally:
 
587
            if pb is None:
 
588
                self.pb.finished()
 
589
 
 
590
    def open_pack(self):
 
591
        """Open a pack for the pack we are creating."""
 
592
        return NewPack(self._pack_collection._upload_transport,
 
593
            self._pack_collection._index_transport,
 
594
            self._pack_collection._pack_transport, upload_suffix=self.suffix,
 
595
            file_mode=self._pack_collection.repo.bzrdir._get_file_mode())
 
596
 
 
597
    def _copy_revision_texts(self):
 
598
        """Copy revision data to the new pack."""
 
599
        # select revisions
 
600
        if self.revision_ids:
 
601
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
 
602
        else:
 
603
            revision_keys = None
 
604
        # select revision keys
 
605
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
606
            self.packs, 'revision_index')[0]
 
607
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
 
608
        # copy revision keys and adjust values
 
609
        self.pb.update("Copying revision texts", 1)
 
610
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
 
611
        list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
 
612
            self.new_pack.revision_index, readv_group_iter, total_items))
 
613
        if 'pack' in debug.debug_flags:
 
614
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
 
615
                time.ctime(), self._pack_collection._upload_transport.base,
 
616
                self.new_pack.random_name,
 
617
                self.new_pack.revision_index.key_count(),
 
618
                time.time() - self.new_pack.start_time)
 
619
        self._revision_keys = revision_keys
 
620
 
 
621
    def _copy_inventory_texts(self):
 
622
        """Copy the inventory texts to the new pack.
 
623
 
 
624
        self._revision_keys is used to determine what inventories to copy.
 
625
 
 
626
        Sets self._text_filter appropriately.
 
627
        """
 
628
        # select inventory keys
 
629
        inv_keys = self._revision_keys # currently the same keyspace, and note that
 
630
        # querying for keys here could introduce a bug where an inventory item
 
631
        # is missed, so do not change it to query separately without cross
 
632
        # checking like the text key check below.
 
633
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
634
            self.packs, 'inventory_index')[0]
 
635
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
 
636
        # copy inventory keys and adjust values
 
637
        # XXX: Should be a helper function to allow different inv representation
 
638
        # at this point.
 
639
        self.pb.update("Copying inventory texts", 2)
 
640
        total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
 
641
        # Only grab the output lines if we will be processing them
 
642
        output_lines = bool(self.revision_ids)
 
643
        inv_lines = self._copy_nodes_graph(inventory_index_map,
 
644
            self.new_pack._writer, self.new_pack.inventory_index,
 
645
            readv_group_iter, total_items, output_lines=output_lines)
 
646
        if self.revision_ids:
 
647
            self._process_inventory_lines(inv_lines)
 
648
        else:
 
649
            # eat the iterator to cause it to execute.
 
650
            list(inv_lines)
 
651
            self._text_filter = None
 
652
        if 'pack' in debug.debug_flags:
 
653
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
 
654
                time.ctime(), self._pack_collection._upload_transport.base,
 
655
                self.new_pack.random_name,
 
656
                self.new_pack.inventory_index.key_count(),
 
657
                time.time() - self.new_pack.start_time)
 
658
 
 
659
    def _copy_text_texts(self):
 
660
        # select text keys
 
661
        text_index_map, text_nodes = self._get_text_nodes()
 
662
        if self._text_filter is not None:
 
663
            # We could return the keys copied as part of the return value from
 
664
            # _copy_nodes_graph but this doesn't work all that well with the
 
665
            # need to get line output too, so we check separately, and as we're
 
666
            # going to buffer everything anyway, we check beforehand, which
 
667
            # saves reading knit data over the wire when we know there are
 
668
            # mising records.
 
669
            text_nodes = set(text_nodes)
 
670
            present_text_keys = set(_node[1] for _node in text_nodes)
 
671
            missing_text_keys = set(self._text_filter) - present_text_keys
 
672
            if missing_text_keys:
 
673
                # TODO: raise a specific error that can handle many missing
 
674
                # keys.
 
675
                a_missing_key = missing_text_keys.pop()
 
676
                raise errors.RevisionNotPresent(a_missing_key[1],
 
677
                    a_missing_key[0])
 
678
        # copy text keys and adjust values
 
679
        self.pb.update("Copying content texts", 3)
 
680
        total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
 
681
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
 
682
            self.new_pack.text_index, readv_group_iter, total_items))
 
683
        self._log_copied_texts()
 
684
 
 
685
    def _check_references(self):
 
686
        """Make sure our external refereneces are present."""
 
687
        external_refs = self.new_pack._external_compression_parents_of_texts()
 
688
        if external_refs:
 
689
            index = self._pack_collection.text_index.combined_index
 
690
            found_items = list(index.iter_entries(external_refs))
 
691
            if len(found_items) != len(external_refs):
 
692
                found_keys = set(k for idx, k, refs, value in found_items)
 
693
                missing_items = external_refs - found_keys
 
694
                missing_file_id, missing_revision_id = missing_items.pop()
 
695
                raise errors.RevisionNotPresent(missing_revision_id,
 
696
                                                missing_file_id)
 
697
 
 
698
    def _create_pack_from_packs(self):
 
699
        self.pb.update("Opening pack", 0, 5)
 
700
        self.new_pack = self.open_pack()
 
701
        new_pack = self.new_pack
 
702
        # buffer data - we won't be reading-back during the pack creation and
 
703
        # this makes a significant difference on sftp pushes.
 
704
        new_pack.set_write_cache_size(1024*1024)
 
705
        if 'pack' in debug.debug_flags:
 
706
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
 
707
                for a_pack in self.packs]
 
708
            if self.revision_ids is not None:
 
709
                rev_count = len(self.revision_ids)
 
710
            else:
 
711
                rev_count = 'all'
 
712
            mutter('%s: create_pack: creating pack from source packs: '
 
713
                '%s%s %s revisions wanted %s t=0',
 
714
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
715
                plain_pack_list, rev_count)
 
716
        self._copy_revision_texts()
 
717
        self._copy_inventory_texts()
 
718
        self._copy_text_texts()
 
719
        # select signature keys
 
720
        signature_filter = self._revision_keys # same keyspace
 
721
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
722
            self.packs, 'signature_index')[0]
 
723
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
 
724
            signature_filter)
 
725
        # copy signature keys and adjust values
 
726
        self.pb.update("Copying signature texts", 4)
 
727
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
 
728
            new_pack.signature_index)
 
729
        if 'pack' in debug.debug_flags:
 
730
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
 
731
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
732
                new_pack.signature_index.key_count(),
 
733
                time.time() - new_pack.start_time)
 
734
        self._check_references()
 
735
        if not self._use_pack(new_pack):
 
736
            new_pack.abort()
 
737
            return None
 
738
        self.pb.update("Finishing pack", 5)
 
739
        new_pack.finish()
 
740
        self._pack_collection.allocate(new_pack)
 
741
        return new_pack
 
742
 
 
743
    def _copy_nodes(self, nodes, index_map, writer, write_index):
 
744
        """Copy knit nodes between packs with no graph references."""
 
745
        pb = ui.ui_factory.nested_progress_bar()
 
746
        try:
 
747
            return self._do_copy_nodes(nodes, index_map, writer,
 
748
                write_index, pb)
 
749
        finally:
 
750
            pb.finished()
 
751
 
 
752
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
 
753
        # for record verification
 
754
        knit = KnitVersionedFiles(None, None)
 
755
        # plan a readv on each source pack:
 
756
        # group by pack
 
757
        nodes = sorted(nodes)
 
758
        # how to map this into knit.py - or knit.py into this?
 
759
        # we don't want the typical knit logic, we want grouping by pack
 
760
        # at this point - perhaps a helper library for the following code 
 
761
        # duplication points?
 
762
        request_groups = {}
 
763
        for index, key, value in nodes:
 
764
            if index not in request_groups:
 
765
                request_groups[index] = []
 
766
            request_groups[index].append((key, value))
 
767
        record_index = 0
 
768
        pb.update("Copied record", record_index, len(nodes))
 
769
        for index, items in request_groups.iteritems():
 
770
            pack_readv_requests = []
 
771
            for key, value in items:
 
772
                # ---- KnitGraphIndex.get_position
 
773
                bits = value[1:].split(' ')
 
774
                offset, length = int(bits[0]), int(bits[1])
 
775
                pack_readv_requests.append((offset, length, (key, value[0])))
 
776
            # linear scan up the pack
 
777
            pack_readv_requests.sort()
 
778
            # copy the data
 
779
            transport, path = index_map[index]
 
780
            reader = pack.make_readv_reader(transport, path,
 
781
                [offset[0:2] for offset in pack_readv_requests])
 
782
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
 
783
                izip(reader.iter_records(), pack_readv_requests):
 
784
                raw_data = read_func(None)
 
785
                # check the header only
 
786
                df, _ = knit._parse_record_header(key, raw_data)
 
787
                df.close()
 
788
                pos, size = writer.add_bytes_record(raw_data, names)
 
789
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
 
790
                pb.update("Copied record", record_index)
 
791
                record_index += 1
 
792
 
 
793
    def _copy_nodes_graph(self, index_map, writer, write_index,
 
794
        readv_group_iter, total_items, output_lines=False):
 
795
        """Copy knit nodes between packs.
 
796
 
 
797
        :param output_lines: Return lines present in the copied data as
 
798
            an iterator of line,version_id.
 
799
        """
 
800
        pb = ui.ui_factory.nested_progress_bar()
 
801
        try:
 
802
            for result in self._do_copy_nodes_graph(index_map, writer,
 
803
                write_index, output_lines, pb, readv_group_iter, total_items):
 
804
                yield result
 
805
        except Exception:
 
806
            # Python 2.4 does not permit try:finally: in a generator.
 
807
            pb.finished()
 
808
            raise
 
809
        else:
 
810
            pb.finished()
 
811
 
 
812
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
 
813
        output_lines, pb, readv_group_iter, total_items):
 
814
        # for record verification
 
815
        knit = KnitVersionedFiles(None, None)
 
816
        # for line extraction when requested (inventories only)
 
817
        if output_lines:
 
818
            factory = KnitPlainFactory()
 
819
        record_index = 0
 
820
        pb.update("Copied record", record_index, total_items)
 
821
        for index, readv_vector, node_vector in readv_group_iter:
 
822
            # copy the data
 
823
            transport, path = index_map[index]
 
824
            reader = pack.make_readv_reader(transport, path, readv_vector)
 
825
            for (names, read_func), (key, eol_flag, references) in \
 
826
                izip(reader.iter_records(), node_vector):
 
827
                raw_data = read_func(None)
 
828
                if output_lines:
 
829
                    # read the entire thing
 
830
                    content, _ = knit._parse_record(key[-1], raw_data)
 
831
                    if len(references[-1]) == 0:
 
832
                        line_iterator = factory.get_fulltext_content(content)
 
833
                    else:
 
834
                        line_iterator = factory.get_linedelta_content(content)
 
835
                    for line in line_iterator:
 
836
                        yield line, key
 
837
                else:
 
838
                    # check the header only
 
839
                    df, _ = knit._parse_record_header(key, raw_data)
 
840
                    df.close()
 
841
                pos, size = writer.add_bytes_record(raw_data, names)
 
842
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
 
843
                pb.update("Copied record", record_index)
 
844
                record_index += 1
 
845
 
 
846
    def _get_text_nodes(self):
 
847
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
848
            self.packs, 'text_index')[0]
 
849
        return text_index_map, self._pack_collection._index_contents(text_index_map,
 
850
            self._text_filter)
 
851
 
 
852
    def _least_readv_node_readv(self, nodes):
 
853
        """Generate request groups for nodes using the least readv's.
 
854
        
 
855
        :param nodes: An iterable of graph index nodes.
 
856
        :return: Total node count and an iterator of the data needed to perform
 
857
            readvs to obtain the data for nodes. Each item yielded by the
 
858
            iterator is a tuple with:
 
859
            index, readv_vector, node_vector. readv_vector is a list ready to
 
860
            hand to the transport readv method, and node_vector is a list of
 
861
            (key, eol_flag, references) for the the node retrieved by the
 
862
            matching readv_vector.
 
863
        """
 
864
        # group by pack so we do one readv per pack
 
865
        nodes = sorted(nodes)
 
866
        total = len(nodes)
 
867
        request_groups = {}
 
868
        for index, key, value, references in nodes:
 
869
            if index not in request_groups:
 
870
                request_groups[index] = []
 
871
            request_groups[index].append((key, value, references))
 
872
        result = []
 
873
        for index, items in request_groups.iteritems():
 
874
            pack_readv_requests = []
 
875
            for key, value, references in items:
 
876
                # ---- KnitGraphIndex.get_position
 
877
                bits = value[1:].split(' ')
 
878
                offset, length = int(bits[0]), int(bits[1])
 
879
                pack_readv_requests.append(
 
880
                    ((offset, length), (key, value[0], references)))
 
881
            # linear scan up the pack to maximum range combining.
 
882
            pack_readv_requests.sort()
 
883
            # split out the readv and the node data.
 
884
            pack_readv = [readv for readv, node in pack_readv_requests]
 
885
            node_vector = [node for readv, node in pack_readv_requests]
 
886
            result.append((index, pack_readv, node_vector))
 
887
        return total, result
 
888
 
 
889
    def _log_copied_texts(self):
 
890
        if 'pack' in debug.debug_flags:
 
891
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
 
892
                time.ctime(), self._pack_collection._upload_transport.base,
 
893
                self.new_pack.random_name,
 
894
                self.new_pack.text_index.key_count(),
 
895
                time.time() - self.new_pack.start_time)
 
896
 
 
897
    def _process_inventory_lines(self, inv_lines):
 
898
        """Use up the inv_lines generator and setup a text key filter."""
 
899
        repo = self._pack_collection.repo
 
900
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
 
901
            inv_lines, self.revision_keys)
 
902
        text_filter = []
 
903
        for fileid, file_revids in fileid_revisions.iteritems():
 
904
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
 
905
        self._text_filter = text_filter
 
906
 
 
907
    def _revision_node_readv(self, revision_nodes):
 
908
        """Return the total revisions and the readv's to issue.
 
909
 
 
910
        :param revision_nodes: The revision index contents for the packs being
 
911
            incorporated into the new pack.
 
912
        :return: As per _least_readv_node_readv.
 
913
        """
 
914
        return self._least_readv_node_readv(revision_nodes)
 
915
 
 
916
    def _use_pack(self, new_pack):
 
917
        """Return True if new_pack should be used.
 
918
 
 
919
        :param new_pack: The pack that has just been created.
 
920
        :return: True if the pack should be used.
 
921
        """
 
922
        return new_pack.data_inserted()
 
923
 
 
924
 
 
925
class OptimisingPacker(Packer):
 
926
    """A packer which spends more time to create better disk layouts."""
 
927
 
 
928
    def _revision_node_readv(self, revision_nodes):
 
929
        """Return the total revisions and the readv's to issue.
 
930
 
 
931
        This sort places revisions in topological order with the ancestors
 
932
        after the children.
 
933
 
 
934
        :param revision_nodes: The revision index contents for the packs being
 
935
            incorporated into the new pack.
 
936
        :return: As per _least_readv_node_readv.
 
937
        """
 
938
        # build an ancestors dict
 
939
        ancestors = {}
 
940
        by_key = {}
 
941
        for index, key, value, references in revision_nodes:
 
942
            ancestors[key] = references[0]
 
943
            by_key[key] = (index, value, references)
 
944
        order = tsort.topo_sort(ancestors)
 
945
        total = len(order)
 
946
        # Single IO is pathological, but it will work as a starting point.
 
947
        requests = []
 
948
        for key in reversed(order):
 
949
            index, value, references = by_key[key]
 
950
            # ---- KnitGraphIndex.get_position
 
951
            bits = value[1:].split(' ')
 
952
            offset, length = int(bits[0]), int(bits[1])
 
953
            requests.append(
 
954
                (index, [(offset, length)], [(key, value[0], references)]))
 
955
        # TODO: combine requests in the same index that are in ascending order.
 
956
        return total, requests
 
957
 
 
958
 
 
959
class ReconcilePacker(Packer):
 
960
    """A packer which regenerates indices etc as it copies.
 
961
    
 
962
    This is used by ``bzr reconcile`` to cause parent text pointers to be
 
963
    regenerated.
 
964
    """
 
965
 
 
966
    def _extra_init(self):
 
967
        self._data_changed = False
 
968
 
 
969
    def _process_inventory_lines(self, inv_lines):
 
970
        """Generate a text key reference map rather for reconciling with."""
 
971
        repo = self._pack_collection.repo
 
972
        refs = repo._find_text_key_references_from_xml_inventory_lines(
 
973
            inv_lines)
 
974
        self._text_refs = refs
 
975
        # during reconcile we:
 
976
        #  - convert unreferenced texts to full texts
 
977
        #  - correct texts which reference a text not copied to be full texts
 
978
        #  - copy all others as-is but with corrected parents.
 
979
        #  - so at this point we don't know enough to decide what becomes a full
 
980
        #    text.
 
981
        self._text_filter = None
 
982
 
 
983
    def _copy_text_texts(self):
 
984
        """generate what texts we should have and then copy."""
 
985
        self.pb.update("Copying content texts", 3)
 
986
        # we have three major tasks here:
 
987
        # 1) generate the ideal index
 
988
        repo = self._pack_collection.repo
 
989
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
 
990
            _1, key, _2, refs in 
 
991
            self.new_pack.revision_index.iter_all_entries()])
 
992
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
 
993
        # 2) generate a text_nodes list that contains all the deltas that can
 
994
        #    be used as-is, with corrected parents.
 
995
        ok_nodes = []
 
996
        bad_texts = []
 
997
        discarded_nodes = []
 
998
        NULL_REVISION = _mod_revision.NULL_REVISION
 
999
        text_index_map, text_nodes = self._get_text_nodes()
 
1000
        for node in text_nodes:
 
1001
            # 0 - index
 
1002
            # 1 - key 
 
1003
            # 2 - value
 
1004
            # 3 - refs
 
1005
            try:
 
1006
                ideal_parents = tuple(ideal_index[node[1]])
 
1007
            except KeyError:
 
1008
                discarded_nodes.append(node)
 
1009
                self._data_changed = True
 
1010
            else:
 
1011
                if ideal_parents == (NULL_REVISION,):
 
1012
                    ideal_parents = ()
 
1013
                if ideal_parents == node[3][0]:
 
1014
                    # no change needed.
 
1015
                    ok_nodes.append(node)
 
1016
                elif ideal_parents[0:1] == node[3][0][0:1]:
 
1017
                    # the left most parent is the same, or there are no parents
 
1018
                    # today. Either way, we can preserve the representation as
 
1019
                    # long as we change the refs to be inserted.
 
1020
                    self._data_changed = True
 
1021
                    ok_nodes.append((node[0], node[1], node[2],
 
1022
                        (ideal_parents, node[3][1])))
 
1023
                    self._data_changed = True
 
1024
                else:
 
1025
                    # Reinsert this text completely
 
1026
                    bad_texts.append((node[1], ideal_parents))
 
1027
                    self._data_changed = True
 
1028
        # we're finished with some data.
 
1029
        del ideal_index
 
1030
        del text_nodes
 
1031
        # 3) bulk copy the ok data
 
1032
        total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
 
1033
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
 
1034
            self.new_pack.text_index, readv_group_iter, total_items))
 
1035
        # 4) adhoc copy all the other texts.
 
1036
        # We have to topologically insert all texts otherwise we can fail to
 
1037
        # reconcile when parts of a single delta chain are preserved intact,
 
1038
        # and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
 
1039
        # reinserted, and if d3 has incorrect parents it will also be
 
1040
        # reinserted. If we insert d3 first, d2 is present (as it was bulk
 
1041
        # copied), so we will try to delta, but d2 is not currently able to be
 
1042
        # extracted because it's basis d1 is not present. Topologically sorting
 
1043
        # addresses this. The following generates a sort for all the texts that
 
1044
        # are being inserted without having to reference the entire text key
 
1045
        # space (we only topo sort the revisions, which is smaller).
 
1046
        topo_order = tsort.topo_sort(ancestors)
 
1047
        rev_order = dict(zip(topo_order, range(len(topo_order))))
 
1048
        bad_texts.sort(key=lambda key:rev_order[key[0][1]])
 
1049
        transaction = repo.get_transaction()
 
1050
        file_id_index = GraphIndexPrefixAdapter(
 
1051
            self.new_pack.text_index,
 
1052
            ('blank', ), 1,
 
1053
            add_nodes_callback=self.new_pack.text_index.add_nodes)
 
1054
        data_access = _DirectPackAccess(
 
1055
                {self.new_pack.text_index:self.new_pack.access_tuple()})
 
1056
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
 
1057
            self.new_pack.access_tuple())
 
1058
        output_texts = KnitVersionedFiles(
 
1059
            _KnitGraphIndex(self.new_pack.text_index,
 
1060
                add_callback=self.new_pack.text_index.add_nodes,
 
1061
                deltas=True, parents=True, is_locked=repo.is_locked),
 
1062
            data_access=data_access, max_delta_chain=200)
 
1063
        for key, parent_keys in bad_texts:
 
1064
            # We refer to the new pack to delta data being output.
 
1065
            # A possible improvement would be to catch errors on short reads
 
1066
            # and only flush then.
 
1067
            self.new_pack.flush()
 
1068
            parents = []
 
1069
            for parent_key in parent_keys:
 
1070
                if parent_key[0] != key[0]:
 
1071
                    # Graph parents must match the fileid
 
1072
                    raise errors.BzrError('Mismatched key parent %r:%r' %
 
1073
                        (key, parent_keys))
 
1074
                parents.append(parent_key[1])
 
1075
            text_lines = split_lines(repo.texts.get_record_stream(
 
1076
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
 
1077
            output_texts.add_lines(key, parent_keys, text_lines,
 
1078
                random_id=True, check_content=False)
 
1079
        # 5) check that nothing inserted has a reference outside the keyspace.
 
1080
        missing_text_keys = self.new_pack._external_compression_parents_of_texts()
 
1081
        if missing_text_keys:
 
1082
            raise errors.BzrError('Reference to missing compression parents %r'
 
1083
                % (missing_text_keys,))
 
1084
        self._log_copied_texts()
 
1085
 
 
1086
    def _use_pack(self, new_pack):
 
1087
        """Override _use_pack to check for reconcile having changed content."""
 
1088
        # XXX: we might be better checking this at the copy time.
 
1089
        original_inventory_keys = set()
 
1090
        inv_index = self._pack_collection.inventory_index.combined_index
 
1091
        for entry in inv_index.iter_all_entries():
 
1092
            original_inventory_keys.add(entry[1])
 
1093
        new_inventory_keys = set()
 
1094
        for entry in new_pack.inventory_index.iter_all_entries():
 
1095
            new_inventory_keys.add(entry[1])
 
1096
        if new_inventory_keys != original_inventory_keys:
 
1097
            self._data_changed = True
 
1098
        return new_pack.data_inserted() and self._data_changed
476
1099
 
477
1100
 
478
1101
class RepositoryPackCollection(object):
479
 
    """Management of packs within a repository."""
 
1102
    """Management of packs within a repository.
 
1103
    
 
1104
    :ivar _names: map of {pack_name: (index_size,)}
 
1105
    """
480
1106
 
481
1107
    def __init__(self, repo, transport, index_transport, upload_transport,
482
1108
                 pack_transport):
513
1139
        
514
1140
        :param pack: A Pack object.
515
1141
        """
516
 
        assert pack.name not in self._packs_by_name
 
1142
        if pack.name in self._packs_by_name:
 
1143
            raise AssertionError()
517
1144
        self.packs.append(pack)
518
1145
        self._packs_by_name[pack.name] = pack
519
1146
        self.revision_index.add_index(pack.revision_index, pack)
521
1148
        self.text_index.add_index(pack.text_index, pack)
522
1149
        self.signature_index.add_index(pack.signature_index, pack)
523
1150
        
524
 
    def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
525
 
        nostore_sha, random_revid):
526
 
        file_id_index = GraphIndexPrefixAdapter(
527
 
            self.text_index.combined_index,
528
 
            (file_id, ), 1,
529
 
            add_nodes_callback=self.text_index.add_callback)
530
 
        self.repo._text_knit._index._graph_index = file_id_index
531
 
        self.repo._text_knit._index._add_callback = file_id_index.add_nodes
532
 
        return self.repo._text_knit.add_lines_with_ghosts(
533
 
            revision_id, parents, new_lines, nostore_sha=nostore_sha,
534
 
            random_id=random_revid, check_content=False)[0:2]
535
 
 
536
1151
    def all_packs(self):
537
1152
        """Return a list of all the Pack objects this repository has.
538
1153
 
594
1209
        self._execute_pack_operations(pack_operations)
595
1210
        return True
596
1211
 
597
 
    def create_pack_from_packs(self, packs, suffix, revision_ids=None):
598
 
        """Create a new pack by reading data from other packs.
599
 
 
600
 
        This does little more than a bulk copy of data. One key difference
601
 
        is that data with the same item key across multiple packs is elided
602
 
        from the output. The new pack is written into the current pack store
603
 
        along with its indices, and the name added to the pack names. The 
604
 
        source packs are not altered and are not required to be in the current
605
 
        pack collection.
606
 
 
607
 
        :param packs: An iterable of Packs to combine.
608
 
        :param revision_ids: Either None, to copy all data, or a list
609
 
            of revision_ids to limit the copied data to the data they
610
 
            introduced.
611
 
        :return: A Pack object, or None if nothing was copied.
612
 
        """
613
 
        # open a pack - using the same name as the last temporary file
614
 
        # - which has already been flushed, so its safe.
615
 
        # XXX: - duplicate code warning with start_write_group; fix before
616
 
        #      considering 'done'.
617
 
        if self._new_pack is not None:
618
 
            raise errors.BzrError('call to create_pack_from_packs while '
619
 
                'another pack is being written.')
620
 
        if revision_ids is not None:
621
 
            if len(revision_ids) == 0:
622
 
                # silly fetch request.
623
 
                return None
624
 
            else:
625
 
                revision_ids = frozenset(revision_ids)
626
 
        pb = ui.ui_factory.nested_progress_bar()
627
 
        try:
628
 
            return self._create_pack_from_packs(packs, suffix, revision_ids,
629
 
                pb)
630
 
        finally:
631
 
            pb.finished()
632
 
 
633
 
    def _create_pack_from_packs(self, packs, suffix, revision_ids, pb):
634
 
        pb.update("Opening pack", 0, 5)
635
 
        new_pack = NewPack(self._upload_transport, self._index_transport,
636
 
            self._pack_transport, upload_suffix=suffix)
637
 
        # buffer data - we won't be reading-back during the pack creation and
638
 
        # this makes a significant difference on sftp pushes.
639
 
        new_pack.set_write_cache_size(1024*1024)
640
 
        if 'pack' in debug.debug_flags:
641
 
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
642
 
                for a_pack in packs]
643
 
            if revision_ids is not None:
644
 
                rev_count = len(revision_ids)
645
 
            else:
646
 
                rev_count = 'all'
647
 
            mutter('%s: create_pack: creating pack from source packs: '
648
 
                '%s%s %s revisions wanted %s t=0',
649
 
                time.ctime(), self._upload_transport.base, new_pack.random_name,
650
 
                plain_pack_list, rev_count)
651
 
        # select revisions
652
 
        if revision_ids:
653
 
            revision_keys = [(revision_id,) for revision_id in revision_ids]
654
 
        else:
655
 
            revision_keys = None
656
 
 
657
 
        # select revision keys
658
 
        revision_index_map = self._packs_list_to_pack_map_and_index_list(
659
 
            packs, 'revision_index')[0]
660
 
        revision_nodes = self._index_contents(revision_index_map, revision_keys)
661
 
        # copy revision keys and adjust values
662
 
        pb.update("Copying revision texts", 1)
663
 
        list(self._copy_nodes_graph(revision_nodes, revision_index_map,
664
 
            new_pack._writer, new_pack.revision_index))
665
 
        if 'pack' in debug.debug_flags:
666
 
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
667
 
                time.ctime(), self._upload_transport.base, new_pack.random_name,
668
 
                new_pack.revision_index.key_count(),
669
 
                time.time() - new_pack.start_time)
670
 
        # select inventory keys
671
 
        inv_keys = revision_keys # currently the same keyspace, and note that
672
 
        # querying for keys here could introduce a bug where an inventory item
673
 
        # is missed, so do not change it to query separately without cross
674
 
        # checking like the text key check below.
675
 
        inventory_index_map = self._packs_list_to_pack_map_and_index_list(
676
 
            packs, 'inventory_index')[0]
677
 
        inv_nodes = self._index_contents(inventory_index_map, inv_keys)
678
 
        # copy inventory keys and adjust values
679
 
        # XXX: Should be a helper function to allow different inv representation
680
 
        # at this point.
681
 
        pb.update("Copying inventory texts", 2)
682
 
        inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
683
 
            new_pack._writer, new_pack.inventory_index, output_lines=True)
684
 
        if revision_ids:
685
 
            fileid_revisions = self.repo._find_file_ids_from_xml_inventory_lines(
686
 
                inv_lines, revision_ids)
687
 
            text_filter = []
688
 
            for fileid, file_revids in fileid_revisions.iteritems():
689
 
                text_filter.extend(
690
 
                    [(fileid, file_revid) for file_revid in file_revids])
691
 
        else:
692
 
            # eat the iterator to cause it to execute.
693
 
            list(inv_lines)
694
 
            text_filter = None
695
 
        if 'pack' in debug.debug_flags:
696
 
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
697
 
                time.ctime(), self._upload_transport.base, new_pack.random_name,
698
 
                new_pack.inventory_index.key_count(),
699
 
                time.time() - new_pack.start_time)
700
 
        # select text keys
701
 
        text_index_map = self._packs_list_to_pack_map_and_index_list(
702
 
            packs, 'text_index')[0]
703
 
        text_nodes = self._index_contents(text_index_map, text_filter)
704
 
        if text_filter is not None:
705
 
            # We could return the keys copied as part of the return value from
706
 
            # _copy_nodes_graph but this doesn't work all that well with the
707
 
            # need to get line output too, so we check separately, and as we're
708
 
            # going to buffer everything anyway, we check beforehand, which
709
 
            # saves reading knit data over the wire when we know there are
710
 
            # mising records.
711
 
            text_nodes = set(text_nodes)
712
 
            present_text_keys = set(_node[1] for _node in text_nodes)
713
 
            missing_text_keys = set(text_filter) - present_text_keys
714
 
            if missing_text_keys:
715
 
                # TODO: raise a specific error that can handle many missing
716
 
                # keys.
717
 
                a_missing_key = missing_text_keys.pop()
718
 
                raise errors.RevisionNotPresent(a_missing_key[1],
719
 
                    a_missing_key[0])
720
 
        # copy text keys and adjust values
721
 
        pb.update("Copying content texts", 3)
722
 
        list(self._copy_nodes_graph(text_nodes, text_index_map,
723
 
            new_pack._writer, new_pack.text_index))
724
 
        if 'pack' in debug.debug_flags:
725
 
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
726
 
                time.ctime(), self._upload_transport.base, new_pack.random_name,
727
 
                new_pack.text_index.key_count(),
728
 
                time.time() - new_pack.start_time)
729
 
        # select signature keys
730
 
        signature_filter = revision_keys # same keyspace
731
 
        signature_index_map = self._packs_list_to_pack_map_and_index_list(
732
 
            packs, 'signature_index')[0]
733
 
        signature_nodes = self._index_contents(signature_index_map,
734
 
            signature_filter)
735
 
        # copy signature keys and adjust values
736
 
        pb.update("Copying signature texts", 4)
737
 
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
738
 
            new_pack.signature_index)
739
 
        if 'pack' in debug.debug_flags:
740
 
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
741
 
                time.ctime(), self._upload_transport.base, new_pack.random_name,
742
 
                new_pack.signature_index.key_count(),
743
 
                time.time() - new_pack.start_time)
744
 
        if not new_pack.data_inserted():
745
 
            new_pack.abort()
746
 
            return None
747
 
        pb.update("Finishing pack", 5)
748
 
        new_pack.finish()
749
 
        self.allocate(new_pack)
750
 
        return new_pack
751
 
 
752
 
    def _execute_pack_operations(self, pack_operations):
 
1212
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
753
1213
        """Execute a series of pack operations.
754
1214
 
755
1215
        :param pack_operations: A list of [revision_count, packs_to_combine].
 
1216
        :param _packer_class: The class of packer to use (default: Packer).
756
1217
        :return: None.
757
1218
        """
758
1219
        for revision_count, packs in pack_operations:
759
1220
            # we may have no-ops from the setup logic
760
1221
            if len(packs) == 0:
761
1222
                continue
762
 
            # have a progress bar?
763
 
            self.create_pack_from_packs(packs, '.autopack')
 
1223
            _packer_class(self, packs, '.autopack').pack()
764
1224
            for pack in packs:
765
1225
                self._remove_pack_from_memory(pack)
766
1226
        # record the newly available packs and stop advertising the old
767
1227
        # packs
768
 
        self._save_pack_names()
 
1228
        self._save_pack_names(clear_obsolete_packs=True)
769
1229
        # Move the old packs out of the way now they are no longer referenced.
770
1230
        for revision_count, packs in pack_operations:
771
1231
            self._obsolete_packs(packs)
783
1243
        self.ensure_loaded()
784
1244
        total_packs = len(self._names)
785
1245
        if total_packs < 2:
 
1246
            # This is arguably wrong because we might not be optimal, but for
 
1247
            # now lets leave it in. (e.g. reconcile -> one pack. But not
 
1248
            # optimal.
786
1249
            return
787
1250
        total_revisions = self.revision_index.combined_index.key_count()
788
1251
        # XXX: the following may want to be a class, to pack with a given
794
1257
        pack_distribution = [1]
795
1258
        pack_operations = [[0, []]]
796
1259
        for pack in self.all_packs():
797
 
            revision_count = pack.get_revision_count()
798
 
            pack_operations[-1][0] += revision_count
 
1260
            pack_operations[-1][0] += pack.get_revision_count()
799
1261
            pack_operations[-1][1].append(pack)
800
 
        self._execute_pack_operations(pack_operations)
 
1262
        self._execute_pack_operations(pack_operations, OptimisingPacker)
801
1263
 
802
1264
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
803
1265
        """Plan a pack operation.
841
1303
        
842
1304
        return pack_operations
843
1305
 
844
 
    def _copy_nodes(self, nodes, index_map, writer, write_index):
845
 
        """Copy knit nodes between packs with no graph references."""
846
 
        pb = ui.ui_factory.nested_progress_bar()
847
 
        try:
848
 
            return self._do_copy_nodes(nodes, index_map, writer,
849
 
                write_index, pb)
850
 
        finally:
851
 
            pb.finished()
852
 
 
853
 
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
854
 
        # for record verification
855
 
        knit_data = _KnitData(None)
856
 
        # plan a readv on each source pack:
857
 
        # group by pack
858
 
        nodes = sorted(nodes)
859
 
        # how to map this into knit.py - or knit.py into this?
860
 
        # we don't want the typical knit logic, we want grouping by pack
861
 
        # at this point - perhaps a helper library for the following code 
862
 
        # duplication points?
863
 
        request_groups = {}
864
 
        for index, key, value in nodes:
865
 
            if index not in request_groups:
866
 
                request_groups[index] = []
867
 
            request_groups[index].append((key, value))
868
 
        record_index = 0
869
 
        pb.update("Copied record", record_index, len(nodes))
870
 
        for index, items in request_groups.iteritems():
871
 
            pack_readv_requests = []
872
 
            for key, value in items:
873
 
                # ---- KnitGraphIndex.get_position
874
 
                bits = value[1:].split(' ')
875
 
                offset, length = int(bits[0]), int(bits[1])
876
 
                pack_readv_requests.append((offset, length, (key, value[0])))
877
 
            # linear scan up the pack
878
 
            pack_readv_requests.sort()
879
 
            # copy the data
880
 
            transport, path = index_map[index]
881
 
            reader = pack.make_readv_reader(transport, path,
882
 
                [offset[0:2] for offset in pack_readv_requests])
883
 
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
884
 
                izip(reader.iter_records(), pack_readv_requests):
885
 
                raw_data = read_func(None)
886
 
                # check the header only
887
 
                df, _ = knit_data._parse_record_header(key[-1], raw_data)
888
 
                df.close()
889
 
                pos, size = writer.add_bytes_record(raw_data, names)
890
 
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
891
 
                pb.update("Copied record", record_index)
892
 
                record_index += 1
893
 
 
894
 
    def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
895
 
        output_lines=False):
896
 
        """Copy knit nodes between packs.
897
 
 
898
 
        :param output_lines: Return lines present in the copied data as
899
 
            an iterator.
900
 
        """
901
 
        pb = ui.ui_factory.nested_progress_bar()
902
 
        try:
903
 
            return self._do_copy_nodes_graph(nodes, index_map, writer,
904
 
                write_index, output_lines, pb)
905
 
        finally:
906
 
            pb.finished()
907
 
 
908
 
    def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
909
 
        output_lines, pb):
910
 
        # for record verification
911
 
        knit_data = _KnitData(None)
912
 
        # for line extraction when requested (inventories only)
913
 
        if output_lines:
914
 
            factory = knit.KnitPlainFactory()
915
 
        # plan a readv on each source pack:
916
 
        # group by pack
917
 
        nodes = sorted(nodes)
918
 
        # how to map this into knit.py - or knit.py into this?
919
 
        # we don't want the typical knit logic, we want grouping by pack
920
 
        # at this point - perhaps a helper library for the following code 
921
 
        # duplication points?
922
 
        request_groups = {}
923
 
        record_index = 0
924
 
        pb.update("Copied record", record_index, len(nodes))
925
 
        for index, key, value, references in nodes:
926
 
            if index not in request_groups:
927
 
                request_groups[index] = []
928
 
            request_groups[index].append((key, value, references))
929
 
        for index, items in request_groups.iteritems():
930
 
            pack_readv_requests = []
931
 
            for key, value, references in items:
932
 
                # ---- KnitGraphIndex.get_position
933
 
                bits = value[1:].split(' ')
934
 
                offset, length = int(bits[0]), int(bits[1])
935
 
                pack_readv_requests.append((offset, length, (key, value[0], references)))
936
 
            # linear scan up the pack
937
 
            pack_readv_requests.sort()
938
 
            # copy the data
939
 
            transport, path = index_map[index]
940
 
            reader = pack.make_readv_reader(transport, path,
941
 
                [offset[0:2] for offset in pack_readv_requests])
942
 
            for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
943
 
                izip(reader.iter_records(), pack_readv_requests):
944
 
                raw_data = read_func(None)
945
 
                if output_lines:
946
 
                    # read the entire thing
947
 
                    content, _ = knit_data._parse_record(key[-1], raw_data)
948
 
                    if len(references[-1]) == 0:
949
 
                        line_iterator = factory.get_fulltext_content(content)
950
 
                    else:
951
 
                        line_iterator = factory.get_linedelta_content(content)
952
 
                    for line in line_iterator:
953
 
                        yield line
954
 
                else:
955
 
                    # check the header only
956
 
                    df, _ = knit_data._parse_record_header(key[-1], raw_data)
957
 
                    df.close()
958
 
                pos, size = writer.add_bytes_record(raw_data, names)
959
 
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
960
 
                pb.update("Copied record", record_index)
961
 
                record_index += 1
962
 
 
963
1306
    def ensure_loaded(self):
964
1307
        # NB: if you see an assertion error here, its probably access against
965
1308
        # an unlocked repo. Naughty.
966
 
        assert self.repo.is_locked()
 
1309
        if not self.repo.is_locked():
 
1310
            raise errors.ObjectNotLocked(self.repo)
967
1311
        if self._names is None:
968
1312
            self._names = {}
969
1313
            self._packs_at_load = set()
1004
1348
        """
1005
1349
        self.ensure_loaded()
1006
1350
        if a_new_pack.name in self._names:
1007
 
            # a collision with the packs we know about (not the only possible
1008
 
            # collision, see NewPack.finish() for some discussion). Remove our
1009
 
            # prior reference to it.
1010
 
            self._remove_pack_from_memory(a_new_pack)
 
1351
            raise errors.BzrError(
 
1352
                'Pack %r already exists in %s' % (a_new_pack.name, self))
1011
1353
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
1012
1354
        self.add_pack_to_memory(a_new_pack)
1013
1355
 
1181
1523
        """Release the mutex around the pack-names index."""
1182
1524
        self.repo.control_files.unlock()
1183
1525
 
1184
 
    def _save_pack_names(self):
 
1526
    def _save_pack_names(self, clear_obsolete_packs=False):
1185
1527
        """Save the list of packs.
1186
1528
 
1187
1529
        This will take out the mutex around the pack names list for the
1188
1530
        duration of the method call. If concurrent updates have been made, a
1189
1531
        three-way merge between the current list and the current in memory list
1190
1532
        is performed.
 
1533
 
 
1534
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1535
            obsolete_packs directory.
1191
1536
        """
1192
1537
        self.lock_names()
1193
1538
        try:
1210
1555
            # changing it.
1211
1556
            for key, value in disk_nodes:
1212
1557
                builder.add_node(key, value)
1213
 
            self.transport.put_file('pack-names', builder.finish())
 
1558
            self.transport.put_file('pack-names', builder.finish(),
 
1559
                mode=self.repo.bzrdir._get_file_mode())
1214
1560
            # move the baseline forward
1215
1561
            self._packs_at_load = disk_nodes
 
1562
            if clear_obsolete_packs:
 
1563
                self._clear_obsolete_packs()
1216
1564
        finally:
1217
1565
            self._unlock_names()
1218
1566
        # synchronise the memory packs list with what we just wrote:
1244
1592
                self._names[name] = sizes
1245
1593
                self.get_pack_by_name(name)
1246
1594
 
 
1595
    def _clear_obsolete_packs(self):
 
1596
        """Delete everything from the obsolete-packs directory.
 
1597
        """
 
1598
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
 
1599
        for filename in obsolete_pack_transport.list_dir('.'):
 
1600
            try:
 
1601
                obsolete_pack_transport.delete(filename)
 
1602
            except (errors.PathError, errors.TransportError), e:
 
1603
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
 
1604
 
1247
1605
    def _start_write_group(self):
1248
1606
        # Do not permit preparation for writing if we're not in a 'write lock'.
1249
1607
        if not self.repo.is_write_locked():
1250
1608
            raise errors.NotWriteLocked(self)
1251
1609
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
1252
 
            self._pack_transport, upload_suffix='.pack')
 
1610
            self._pack_transport, upload_suffix='.pack',
 
1611
            file_mode=self.repo.bzrdir._get_file_mode())
1253
1612
        # allow writing: queue writes to a new index
1254
1613
        self.revision_index.add_writable_index(self._new_pack.revision_index,
1255
1614
            self._new_pack)
1260
1619
        self.signature_index.add_writable_index(self._new_pack.signature_index,
1261
1620
            self._new_pack)
1262
1621
 
1263
 
        # reused revision and signature knits may need updating
1264
 
        #
1265
 
        # "Hysterical raisins. client code in bzrlib grabs those knits outside
1266
 
        # of write groups and then mutates it inside the write group."
1267
 
        if self.repo._revision_knit is not None:
1268
 
            self.repo._revision_knit._index._add_callback = \
1269
 
                self.revision_index.add_callback
1270
 
        if self.repo._signature_knit is not None:
1271
 
            self.repo._signature_knit._index._add_callback = \
1272
 
                self.signature_index.add_callback
1273
 
        # create a reused knit object for text addition in commit.
1274
 
        self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1275
 
            'all-texts', None)
 
1622
        self.repo.inventories._index._add_callback = self.inventory_index.add_callback
 
1623
        self.repo.revisions._index._add_callback = self.revision_index.add_callback
 
1624
        self.repo.signatures._index._add_callback = self.signature_index.add_callback
 
1625
        self.repo.texts._index._add_callback = self.text_index.add_callback
1276
1626
 
1277
1627
    def _abort_write_group(self):
1278
1628
        # FIXME: just drop the transient index.
1279
1629
        # forget what names there are
1280
 
        self._new_pack.abort()
1281
 
        self._remove_pack_indices(self._new_pack)
1282
 
        self._new_pack = None
 
1630
        if self._new_pack is not None:
 
1631
            self._new_pack.abort()
 
1632
            self._remove_pack_indices(self._new_pack)
 
1633
            self._new_pack = None
1283
1634
        self.repo._text_knit = None
1284
1635
 
1285
1636
    def _commit_write_group(self):
1299
1650
        self.repo._text_knit = None
1300
1651
 
1301
1652
 
1302
 
class KnitPackRevisionStore(KnitRevisionStore):
1303
 
    """An object to adapt access from RevisionStore's to use KnitPacks.
1304
 
 
1305
 
    This class works by replacing the original RevisionStore.
1306
 
    We need to do this because the KnitPackRevisionStore is less
1307
 
    isolated in its layering - it uses services from the repo.
1308
 
    """
1309
 
 
1310
 
    def __init__(self, repo, transport, revisionstore):
1311
 
        """Create a KnitPackRevisionStore on repo with revisionstore.
1312
 
 
1313
 
        This will store its state in the Repository, use the
1314
 
        indices to provide a KnitGraphIndex,
1315
 
        and at the end of transactions write new indices.
1316
 
        """
1317
 
        KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1318
 
        self.repo = repo
1319
 
        self._serializer = revisionstore._serializer
1320
 
        self.transport = transport
1321
 
 
1322
 
    def get_revision_file(self, transaction):
1323
 
        """Get the revision versioned file object."""
1324
 
        if getattr(self.repo, '_revision_knit', None) is not None:
1325
 
            return self.repo._revision_knit
1326
 
        self.repo._pack_collection.ensure_loaded()
1327
 
        add_callback = self.repo._pack_collection.revision_index.add_callback
1328
 
        # setup knit specific objects
1329
 
        knit_index = KnitGraphIndex(
1330
 
            self.repo._pack_collection.revision_index.combined_index,
1331
 
            add_callback=add_callback)
1332
 
        self.repo._revision_knit = knit.KnitVersionedFile(
1333
 
            'revisions', self.transport.clone('..'),
1334
 
            self.repo.control_files._file_mode,
1335
 
            create=False, access_mode=self.repo._access_mode(),
1336
 
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1337
 
            access_method=self.repo._pack_collection.revision_index.knit_access)
1338
 
        return self.repo._revision_knit
1339
 
 
1340
 
    def get_signature_file(self, transaction):
1341
 
        """Get the signature versioned file object."""
1342
 
        if getattr(self.repo, '_signature_knit', None) is not None:
1343
 
            return self.repo._signature_knit
1344
 
        self.repo._pack_collection.ensure_loaded()
1345
 
        add_callback = self.repo._pack_collection.signature_index.add_callback
1346
 
        # setup knit specific objects
1347
 
        knit_index = KnitGraphIndex(
1348
 
            self.repo._pack_collection.signature_index.combined_index,
1349
 
            add_callback=add_callback, parents=False)
1350
 
        self.repo._signature_knit = knit.KnitVersionedFile(
1351
 
            'signatures', self.transport.clone('..'),
1352
 
            self.repo.control_files._file_mode,
1353
 
            create=False, access_mode=self.repo._access_mode(),
1354
 
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1355
 
            access_method=self.repo._pack_collection.signature_index.knit_access)
1356
 
        return self.repo._signature_knit
1357
 
 
1358
 
 
1359
 
class KnitPackTextStore(VersionedFileStore):
1360
 
    """Presents a TextStore abstraction on top of packs.
1361
 
 
1362
 
    This class works by replacing the original VersionedFileStore.
1363
 
    We need to do this because the KnitPackRevisionStore is less
1364
 
    isolated in its layering - it uses services from the repo and shares them
1365
 
    with all the data written in a single write group.
1366
 
    """
1367
 
 
1368
 
    def __init__(self, repo, transport, weavestore):
1369
 
        """Create a KnitPackTextStore on repo with weavestore.
1370
 
 
1371
 
        This will store its state in the Repository, use the
1372
 
        indices FileNames to provide a KnitGraphIndex,
1373
 
        and at the end of transactions write new indices.
1374
 
        """
1375
 
        # don't call base class constructor - it's not suitable.
1376
 
        # no transient data stored in the transaction
1377
 
        # cache.
1378
 
        self._precious = False
1379
 
        self.repo = repo
1380
 
        self.transport = transport
1381
 
        self.weavestore = weavestore
1382
 
        # XXX for check() which isn't updated yet
1383
 
        self._transport = weavestore._transport
1384
 
 
1385
 
    def get_weave_or_empty(self, file_id, transaction):
1386
 
        """Get a 'Knit' backed by the .tix indices.
1387
 
 
1388
 
        The transaction parameter is ignored.
1389
 
        """
1390
 
        self.repo._pack_collection.ensure_loaded()
1391
 
        add_callback = self.repo._pack_collection.text_index.add_callback
1392
 
        # setup knit specific objects
1393
 
        file_id_index = GraphIndexPrefixAdapter(
1394
 
            self.repo._pack_collection.text_index.combined_index,
1395
 
            (file_id, ), 1, add_nodes_callback=add_callback)
1396
 
        knit_index = KnitGraphIndex(file_id_index,
1397
 
            add_callback=file_id_index.add_nodes,
1398
 
            deltas=True, parents=True)
1399
 
        return knit.KnitVersionedFile('text:' + file_id,
1400
 
            self.transport.clone('..'),
1401
 
            None,
1402
 
            index=knit_index,
1403
 
            access_method=self.repo._pack_collection.text_index.knit_access,
1404
 
            factory=knit.KnitPlainFactory())
1405
 
 
1406
 
    get_weave = get_weave_or_empty
1407
 
 
1408
 
    def __iter__(self):
1409
 
        """Generate a list of the fileids inserted, for use by check."""
1410
 
        self.repo._pack_collection.ensure_loaded()
1411
 
        ids = set()
1412
 
        for index, key, value, refs in \
1413
 
            self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1414
 
            ids.add(key[0])
1415
 
        return iter(ids)
1416
 
 
1417
 
 
1418
 
class InventoryKnitThunk(object):
1419
 
    """An object to manage thunking get_inventory_weave to pack based knits."""
1420
 
 
1421
 
    def __init__(self, repo, transport):
1422
 
        """Create an InventoryKnitThunk for repo at transport.
1423
 
 
1424
 
        This will store its state in the Repository, use the
1425
 
        indices FileNames to provide a KnitGraphIndex,
1426
 
        and at the end of transactions write a new index..
1427
 
        """
1428
 
        self.repo = repo
1429
 
        self.transport = transport
1430
 
 
1431
 
    def get_weave(self):
1432
 
        """Get a 'Knit' that contains inventory data."""
1433
 
        self.repo._pack_collection.ensure_loaded()
1434
 
        add_callback = self.repo._pack_collection.inventory_index.add_callback
1435
 
        # setup knit specific objects
1436
 
        knit_index = KnitGraphIndex(
1437
 
            self.repo._pack_collection.inventory_index.combined_index,
1438
 
            add_callback=add_callback, deltas=True, parents=True)
1439
 
        return knit.KnitVersionedFile(
1440
 
            'inventory', self.transport.clone('..'),
1441
 
            self.repo.control_files._file_mode,
1442
 
            create=False, access_mode=self.repo._access_mode(),
1443
 
            index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1444
 
            access_method=self.repo._pack_collection.inventory_index.knit_access)
1445
 
 
1446
 
 
1447
1653
class KnitPackRepository(KnitRepository):
1448
 
    """Experimental graph-knit using repository."""
1449
 
 
1450
 
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1451
 
        control_store, text_store, _commit_builder_class, _serializer):
 
1654
    """Repository with knit objects stored inside pack containers.
 
1655
    
 
1656
    The layering for a KnitPackRepository is:
 
1657
 
 
1658
    Graph        |  HPSS    | Repository public layer |
 
1659
    ===================================================
 
1660
    Tuple based apis below, string based, and key based apis above
 
1661
    ---------------------------------------------------
 
1662
    KnitVersionedFiles
 
1663
      Provides .texts, .revisions etc
 
1664
      This adapts the N-tuple keys to physical knit records which only have a
 
1665
      single string identifier (for historical reasons), which in older formats
 
1666
      was always the revision_id, and in the mapped code for packs is always
 
1667
      the last element of key tuples.
 
1668
    ---------------------------------------------------
 
1669
    GraphIndex
 
1670
      A separate GraphIndex is used for each of the
 
1671
      texts/inventories/revisions/signatures contained within each individual
 
1672
      pack file. The GraphIndex layer works in N-tuples and is unaware of any
 
1673
      semantic value.
 
1674
    ===================================================
 
1675
    
 
1676
    """
 
1677
 
 
1678
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
 
1679
        _serializer):
1452
1680
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1453
 
            _revision_store, control_store, text_store, _commit_builder_class,
1454
 
            _serializer)
1455
 
        index_transport = control_files._transport.clone('indices')
1456
 
        self._pack_collection = RepositoryPackCollection(self, control_files._transport,
 
1681
            _commit_builder_class, _serializer)
 
1682
        index_transport = self._transport.clone('indices')
 
1683
        self._pack_collection = RepositoryPackCollection(self, self._transport,
1457
1684
            index_transport,
1458
 
            control_files._transport.clone('upload'),
1459
 
            control_files._transport.clone('packs'))
1460
 
        self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1461
 
        self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1462
 
        self._inv_thunk = InventoryKnitThunk(self, index_transport)
 
1685
            self._transport.clone('upload'),
 
1686
            self._transport.clone('packs'))
 
1687
        self.inventories = KnitVersionedFiles(
 
1688
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
 
1689
                add_callback=self._pack_collection.inventory_index.add_callback,
 
1690
                deltas=True, parents=True, is_locked=self.is_locked),
 
1691
            data_access=self._pack_collection.inventory_index.data_access,
 
1692
            max_delta_chain=200)
 
1693
        self.revisions = KnitVersionedFiles(
 
1694
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
 
1695
                add_callback=self._pack_collection.revision_index.add_callback,
 
1696
                deltas=False, parents=True, is_locked=self.is_locked),
 
1697
            data_access=self._pack_collection.revision_index.data_access,
 
1698
            max_delta_chain=0)
 
1699
        self.signatures = KnitVersionedFiles(
 
1700
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
 
1701
                add_callback=self._pack_collection.signature_index.add_callback,
 
1702
                deltas=False, parents=False, is_locked=self.is_locked),
 
1703
            data_access=self._pack_collection.signature_index.data_access,
 
1704
            max_delta_chain=0)
 
1705
        self.texts = KnitVersionedFiles(
 
1706
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
 
1707
                add_callback=self._pack_collection.text_index.add_callback,
 
1708
                deltas=True, parents=True, is_locked=self.is_locked),
 
1709
            data_access=self._pack_collection.text_index.data_access,
 
1710
            max_delta_chain=200)
1463
1711
        # True when the repository object is 'write locked' (as opposed to the
1464
1712
        # physical lock only taken out around changes to the pack-names list.) 
1465
1713
        # Another way to represent this would be a decorator around the control
1468
1716
        self._write_lock_count = 0
1469
1717
        self._transaction = None
1470
1718
        # for tests
1471
 
        self._reconcile_does_inventory_gc = False
1472
 
        self._reconcile_fixes_text_parents = False
 
1719
        self._reconcile_does_inventory_gc = True
 
1720
        self._reconcile_fixes_text_parents = True
 
1721
        self._reconcile_backsup_inventory = False
 
1722
        self._fetch_order = 'unordered'
 
1723
 
 
1724
    def _warn_if_deprecated(self):
 
1725
        # This class isn't deprecated, but one sub-format is
 
1726
        if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
 
1727
            from bzrlib import repository
 
1728
            if repository._deprecation_warning_done:
 
1729
                return
 
1730
            repository._deprecation_warning_done = True
 
1731
            warning("Format %s for %s is deprecated - please use"
 
1732
                    " 'bzr upgrade --1.6.1-rich-root'"
 
1733
                    % (self._format, self.bzrdir.transport.base))
1473
1734
 
1474
1735
    def _abort_write_group(self):
1475
1736
        self._pack_collection._abort_write_group()
1476
1737
 
1477
 
    def _access_mode(self):
1478
 
        """Return 'w' or 'r' for depending on whether a write lock is active.
1479
 
        
1480
 
        This method is a helper for the Knit-thunking support objects.
 
1738
    def _find_inconsistent_revision_parents(self):
 
1739
        """Find revisions with incorrectly cached parents.
 
1740
 
 
1741
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1742
            parents-in-revision).
1481
1743
        """
1482
 
        if self.is_write_locked():
1483
 
            return 'w'
1484
 
        return 'r'
 
1744
        if not self.is_locked():
 
1745
            raise errors.ObjectNotLocked(self)
 
1746
        pb = ui.ui_factory.nested_progress_bar()
 
1747
        result = []
 
1748
        try:
 
1749
            revision_nodes = self._pack_collection.revision_index \
 
1750
                .combined_index.iter_all_entries()
 
1751
            index_positions = []
 
1752
            # Get the cached index values for all revisions, and also the location
 
1753
            # in each index of the revision text so we can perform linear IO.
 
1754
            for index, key, value, refs in revision_nodes:
 
1755
                pos, length = value[1:].split(' ')
 
1756
                index_positions.append((index, int(pos), key[0],
 
1757
                    tuple(parent[0] for parent in refs[0])))
 
1758
                pb.update("Reading revision index.", 0, 0)
 
1759
            index_positions.sort()
 
1760
            batch_count = len(index_positions) / 1000 + 1
 
1761
            pb.update("Checking cached revision graph.", 0, batch_count)
 
1762
            for offset in xrange(batch_count):
 
1763
                pb.update("Checking cached revision graph.", offset)
 
1764
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
 
1765
                if not to_query:
 
1766
                    break
 
1767
                rev_ids = [item[2] for item in to_query]
 
1768
                revs = self.get_revisions(rev_ids)
 
1769
                for revision, item in zip(revs, to_query):
 
1770
                    index_parents = item[3]
 
1771
                    rev_parents = tuple(revision.parent_ids)
 
1772
                    if index_parents != rev_parents:
 
1773
                        result.append((revision.revision_id, index_parents, rev_parents))
 
1774
        finally:
 
1775
            pb.finished()
 
1776
        return result
1485
1777
 
 
1778
    @symbol_versioning.deprecated_method(symbol_versioning.one_one)
1486
1779
    def get_parents(self, revision_ids):
1487
 
        """See StackedParentsProvider.get_parents.
1488
 
        
1489
 
        This implementation accesses the combined revision index to provide
1490
 
        answers.
1491
 
        """
1492
 
        self._pack_collection.ensure_loaded()
1493
 
        index = self._pack_collection.revision_index.combined_index
1494
 
        search_keys = set()
1495
 
        for revision_id in revision_ids:
1496
 
            if revision_id != _mod_revision.NULL_REVISION:
1497
 
                search_keys.add((revision_id,))
1498
 
        found_parents = {_mod_revision.NULL_REVISION:[]}
1499
 
        for index, key, value, refs in index.iter_entries(search_keys):
1500
 
            parents = refs[0]
1501
 
            if not parents:
1502
 
                parents = (_mod_revision.NULL_REVISION,)
1503
 
            else:
1504
 
                parents = tuple(parent[0] for parent in parents)
1505
 
            found_parents[key[0]] = parents
1506
 
        result = []
1507
 
        for revision_id in revision_ids:
1508
 
            try:
1509
 
                result.append(found_parents[revision_id])
1510
 
            except KeyError:
1511
 
                result.append(None)
1512
 
        return result
 
1780
        """See graph._StackedParentsProvider.get_parents."""
 
1781
        parent_map = self.get_parent_map(revision_ids)
 
1782
        return [parent_map.get(r, None) for r in revision_ids]
1513
1783
 
1514
1784
    def _make_parents_provider(self):
1515
 
        return self
 
1785
        return graph.CachingParentsProvider(self)
1516
1786
 
1517
1787
    def _refresh_data(self):
1518
1788
        if self._write_lock_count == 1 or (
1530
1800
    def _commit_write_group(self):
1531
1801
        return self._pack_collection._commit_write_group()
1532
1802
 
1533
 
    def get_inventory_weave(self):
1534
 
        return self._inv_thunk.get_weave()
1535
 
 
1536
1803
    def get_transaction(self):
1537
1804
        if self._write_lock_count:
1538
1805
            return self._transaction
1550
1817
            raise errors.ReadOnlyError(self)
1551
1818
        self._write_lock_count += 1
1552
1819
        if self._write_lock_count == 1:
1553
 
            from bzrlib import transactions
1554
1820
            self._transaction = transactions.WriteTransaction()
 
1821
            for repo in self._fallback_repositories:
 
1822
                # Writes don't affect fallback repos
 
1823
                repo.lock_read()
1555
1824
        self._refresh_data()
1556
1825
 
1557
1826
    def lock_read(self):
1559
1828
            self._write_lock_count += 1
1560
1829
        else:
1561
1830
            self.control_files.lock_read()
 
1831
            for repo in self._fallback_repositories:
 
1832
                # Writes don't affect fallback repos
 
1833
                repo.lock_read()
1562
1834
        self._refresh_data()
1563
1835
 
1564
1836
    def leave_lock_in_place(self):
1600
1872
                transaction = self._transaction
1601
1873
                self._transaction = None
1602
1874
                transaction.finish()
 
1875
                for repo in self._fallback_repositories:
 
1876
                    repo.unlock()
1603
1877
        else:
1604
1878
            self.control_files.unlock()
 
1879
            for repo in self._fallback_repositories:
 
1880
                repo.unlock()
1605
1881
 
1606
1882
 
1607
1883
class RepositoryFormatPack(MetaDirRepositoryFormat):
1629
1905
    # Set this attribute in derived clases to control the _serializer that the
1630
1906
    # repository objects will have passed to their constructor.
1631
1907
    _serializer = None
1632
 
 
1633
 
    def _get_control_store(self, repo_transport, control_files):
1634
 
        """Return the control store for this repository."""
1635
 
        return VersionedFileStore(
1636
 
            repo_transport,
1637
 
            prefixed=False,
1638
 
            file_mode=control_files._file_mode,
1639
 
            versionedfile_class=knit.KnitVersionedFile,
1640
 
            versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
1641
 
            )
1642
 
 
1643
 
    def _get_revision_store(self, repo_transport, control_files):
1644
 
        """See RepositoryFormat._get_revision_store()."""
1645
 
        versioned_file_store = VersionedFileStore(
1646
 
            repo_transport,
1647
 
            file_mode=control_files._file_mode,
1648
 
            prefixed=False,
1649
 
            precious=True,
1650
 
            versionedfile_class=knit.KnitVersionedFile,
1651
 
            versionedfile_kwargs={'delta': False,
1652
 
                                  'factory': knit.KnitPlainFactory(),
1653
 
                                 },
1654
 
            escaped=True,
1655
 
            )
1656
 
        return KnitRevisionStore(versioned_file_store)
1657
 
 
1658
 
    def _get_text_store(self, transport, control_files):
1659
 
        """See RepositoryFormat._get_text_store()."""
1660
 
        return self._get_versioned_file_store('knits',
1661
 
                                  transport,
1662
 
                                  control_files,
1663
 
                                  versionedfile_class=knit.KnitVersionedFile,
1664
 
                                  versionedfile_kwargs={
1665
 
                                      'create_parent_dir': True,
1666
 
                                      'delay_create': True,
1667
 
                                      'dir_mode': control_files._dir_mode,
1668
 
                                  },
1669
 
                                  escaped=True)
 
1908
    # External references are not supported in pack repositories yet.
 
1909
    supports_external_lookups = False
1670
1910
 
1671
1911
    def initialize(self, a_bzrdir, shared=False):
1672
1912
        """Create a pack based repository.
1694
1934
        """
1695
1935
        if not _found:
1696
1936
            format = RepositoryFormat.find_format(a_bzrdir)
1697
 
            assert format.__class__ ==  self.__class__
1698
1937
        if _override_transport is not None:
1699
1938
            repo_transport = _override_transport
1700
1939
        else:
1701
1940
            repo_transport = a_bzrdir.get_repository_transport(None)
1702
1941
        control_files = lockable_files.LockableFiles(repo_transport,
1703
1942
                                'lock', lockdir.LockDir)
1704
 
        text_store = self._get_text_store(repo_transport, control_files)
1705
 
        control_store = self._get_control_store(repo_transport, control_files)
1706
 
        _revision_store = self._get_revision_store(repo_transport, control_files)
1707
1943
        return self.repository_class(_format=self,
1708
1944
                              a_bzrdir=a_bzrdir,
1709
1945
                              control_files=control_files,
1710
 
                              _revision_store=_revision_store,
1711
 
                              control_store=control_store,
1712
 
                              text_store=text_store,
1713
1946
                              _commit_builder_class=self._commit_builder_class,
1714
1947
                              _serializer=self._serializer)
1715
1948
 
1716
1949
 
1717
1950
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1718
 
    """A no-subtrees parameterised Pack repository.
 
1951
    """A no-subtrees parameterized Pack repository.
1719
1952
 
1720
1953
    This format was introduced in 0.92.
1721
1954
    """
1725
1958
    _serializer = xml5.serializer_v5
1726
1959
 
1727
1960
    def _get_matching_bzrdir(self):
1728
 
        return bzrdir.format_registry.make_bzrdir('knitpack-experimental')
 
1961
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
1729
1962
 
1730
1963
    def _ignore_setting_bzrdir(self, format):
1731
1964
        pass
1745
1978
 
1746
1979
 
1747
1980
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1748
 
    """A subtrees parameterised Pack repository.
 
1981
    """A subtrees parameterized Pack repository.
1749
1982
 
1750
1983
    This repository format uses the xml7 serializer to get:
1751
1984
     - support for recording full info about the tree root
1762
1995
 
1763
1996
    def _get_matching_bzrdir(self):
1764
1997
        return bzrdir.format_registry.make_bzrdir(
1765
 
            'knitpack-subtree-experimental')
 
1998
            'pack-0.92-subtree')
1766
1999
 
1767
2000
    def _ignore_setting_bzrdir(self, format):
1768
2001
        pass
1784
2017
    def get_format_description(self):
1785
2018
        """See RepositoryFormat.get_format_description()."""
1786
2019
        return "Packs containing knits with subtree support\n"
 
2020
 
 
2021
 
 
2022
class RepositoryFormatKnitPack4(RepositoryFormatPack):
 
2023
    """A rich-root, no subtrees parameterized Pack repository.
 
2024
 
 
2025
    This repository format uses the xml6 serializer to get:
 
2026
     - support for recording full info about the tree root
 
2027
 
 
2028
    This format was introduced in 1.0.
 
2029
    """
 
2030
 
 
2031
    repository_class = KnitPackRepository
 
2032
    _commit_builder_class = PackRootCommitBuilder
 
2033
    rich_root_data = True
 
2034
    supports_tree_reference = False
 
2035
    _serializer = xml6.serializer_v6
 
2036
 
 
2037
    def _get_matching_bzrdir(self):
 
2038
        return bzrdir.format_registry.make_bzrdir(
 
2039
            'rich-root-pack')
 
2040
 
 
2041
    def _ignore_setting_bzrdir(self, format):
 
2042
        pass
 
2043
 
 
2044
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2045
 
 
2046
    def check_conversion_target(self, target_format):
 
2047
        if not target_format.rich_root_data:
 
2048
            raise errors.BadConversionTarget(
 
2049
                'Does not support rich root data.', target_format)
 
2050
 
 
2051
    def get_format_string(self):
 
2052
        """See RepositoryFormat.get_format_string()."""
 
2053
        return ("Bazaar pack repository format 1 with rich root"
 
2054
                " (needs bzr 1.0)\n")
 
2055
 
 
2056
    def get_format_description(self):
 
2057
        """See RepositoryFormat.get_format_description()."""
 
2058
        return "Packs containing knits with rich root support\n"
 
2059
 
 
2060
 
 
2061
class RepositoryFormatKnitPack5(RepositoryFormatPack):
 
2062
    """Repository that supports external references to allow stacking.
 
2063
 
 
2064
    New in release 1.6.
 
2065
 
 
2066
    Supports external lookups, which results in non-truncated ghosts after
 
2067
    reconcile compared to pack-0.92 formats.
 
2068
    """
 
2069
 
 
2070
    repository_class = KnitPackRepository
 
2071
    _commit_builder_class = PackCommitBuilder
 
2072
    _serializer = xml5.serializer_v5
 
2073
    supports_external_lookups = True
 
2074
 
 
2075
    def _get_matching_bzrdir(self):
 
2076
        return bzrdir.format_registry.make_bzrdir('development1')
 
2077
 
 
2078
    def _ignore_setting_bzrdir(self, format):
 
2079
        pass
 
2080
 
 
2081
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2082
 
 
2083
    def get_format_string(self):
 
2084
        """See RepositoryFormat.get_format_string()."""
 
2085
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
 
2086
 
 
2087
    def get_format_description(self):
 
2088
        """See RepositoryFormat.get_format_description()."""
 
2089
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
 
2090
 
 
2091
    def check_conversion_target(self, target_format):
 
2092
        pass
 
2093
 
 
2094
 
 
2095
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
 
2096
    """A repository with rich roots and stacking.
 
2097
 
 
2098
    New in release 1.6.1.
 
2099
 
 
2100
    Supports stacking on other repositories, allowing data to be accessed
 
2101
    without being stored locally.
 
2102
    """
 
2103
 
 
2104
    repository_class = KnitPackRepository
 
2105
    _commit_builder_class = PackRootCommitBuilder
 
2106
    rich_root_data = True
 
2107
    supports_tree_reference = False # no subtrees
 
2108
    _serializer = xml6.serializer_v6
 
2109
    supports_external_lookups = True
 
2110
 
 
2111
    def _get_matching_bzrdir(self):
 
2112
        return bzrdir.format_registry.make_bzrdir(
 
2113
            '1.6.1-rich-root')
 
2114
 
 
2115
    def _ignore_setting_bzrdir(self, format):
 
2116
        pass
 
2117
 
 
2118
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2119
 
 
2120
    def check_conversion_target(self, target_format):
 
2121
        if not target_format.rich_root_data:
 
2122
            raise errors.BadConversionTarget(
 
2123
                'Does not support rich root data.', target_format)
 
2124
 
 
2125
    def get_format_string(self):
 
2126
        """See RepositoryFormat.get_format_string()."""
 
2127
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
 
2128
 
 
2129
    def get_format_description(self):
 
2130
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
 
2131
 
 
2132
 
 
2133
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
 
2134
    """A repository with rich roots and external references.
 
2135
 
 
2136
    New in release 1.6.
 
2137
 
 
2138
    Supports external lookups, which results in non-truncated ghosts after
 
2139
    reconcile compared to pack-0.92 formats.
 
2140
 
 
2141
    This format was deprecated because the serializer it uses accidentally
 
2142
    supported subtrees, when the format was not intended to. This meant that
 
2143
    someone could accidentally fetch from an incorrect repository.
 
2144
    """
 
2145
 
 
2146
    repository_class = KnitPackRepository
 
2147
    _commit_builder_class = PackRootCommitBuilder
 
2148
    rich_root_data = True
 
2149
    supports_tree_reference = False # no subtrees
 
2150
    _serializer = xml7.serializer_v7
 
2151
 
 
2152
    supports_external_lookups = True
 
2153
 
 
2154
    def _get_matching_bzrdir(self):
 
2155
        return bzrdir.format_registry.make_bzrdir(
 
2156
            'development1-subtree')
 
2157
 
 
2158
    def _ignore_setting_bzrdir(self, format):
 
2159
        pass
 
2160
 
 
2161
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2162
 
 
2163
    def check_conversion_target(self, target_format):
 
2164
        if not target_format.rich_root_data:
 
2165
            raise errors.BadConversionTarget(
 
2166
                'Does not support rich root data.', target_format)
 
2167
 
 
2168
    def get_format_string(self):
 
2169
        """See RepositoryFormat.get_format_string()."""
 
2170
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
 
2171
 
 
2172
    def get_format_description(self):
 
2173
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
 
2174
                " (deprecated)")
 
2175
 
 
2176
 
 
2177
class RepositoryFormatPackDevelopment1(RepositoryFormatPack):
 
2178
    """A no-subtrees development repository.
 
2179
 
 
2180
    This format should be retained until the second release after bzr 1.5.
 
2181
 
 
2182
    Supports external lookups, which results in non-truncated ghosts after
 
2183
    reconcile compared to pack-0.92 formats.
 
2184
    """
 
2185
 
 
2186
    repository_class = KnitPackRepository
 
2187
    _commit_builder_class = PackCommitBuilder
 
2188
    _serializer = xml5.serializer_v5
 
2189
    supports_external_lookups = True
 
2190
 
 
2191
    def _get_matching_bzrdir(self):
 
2192
        return bzrdir.format_registry.make_bzrdir('development1')
 
2193
 
 
2194
    def _ignore_setting_bzrdir(self, format):
 
2195
        pass
 
2196
 
 
2197
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2198
 
 
2199
    def get_format_string(self):
 
2200
        """See RepositoryFormat.get_format_string()."""
 
2201
        return "Bazaar development format 1 (needs bzr.dev from before 1.6)\n"
 
2202
 
 
2203
    def get_format_description(self):
 
2204
        """See RepositoryFormat.get_format_description()."""
 
2205
        return ("Development repository format, currently the same as "
 
2206
            "pack-0.92 with external reference support.\n")
 
2207
 
 
2208
    def check_conversion_target(self, target_format):
 
2209
        pass
 
2210
 
 
2211
 
 
2212
class RepositoryFormatPackDevelopment1Subtree(RepositoryFormatPack):
 
2213
    """A subtrees development repository.
 
2214
 
 
2215
    This format should be retained until the second release after bzr 1.5.
 
2216
 
 
2217
    Supports external lookups, which results in non-truncated ghosts after
 
2218
    reconcile compared to pack-0.92 formats.
 
2219
    """
 
2220
 
 
2221
    repository_class = KnitPackRepository
 
2222
    _commit_builder_class = PackRootCommitBuilder
 
2223
    rich_root_data = True
 
2224
    supports_tree_reference = True
 
2225
    _serializer = xml7.serializer_v7
 
2226
    supports_external_lookups = True
 
2227
 
 
2228
    def _get_matching_bzrdir(self):
 
2229
        return bzrdir.format_registry.make_bzrdir(
 
2230
            'development1-subtree')
 
2231
 
 
2232
    def _ignore_setting_bzrdir(self, format):
 
2233
        pass
 
2234
 
 
2235
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
2236
 
 
2237
    def check_conversion_target(self, target_format):
 
2238
        if not target_format.rich_root_data:
 
2239
            raise errors.BadConversionTarget(
 
2240
                'Does not support rich root data.', target_format)
 
2241
        if not getattr(target_format, 'supports_tree_reference', False):
 
2242
            raise errors.BadConversionTarget(
 
2243
                'Does not support nested trees', target_format)
 
2244
            
 
2245
    def get_format_string(self):
 
2246
        """See RepositoryFormat.get_format_string()."""
 
2247
        return ("Bazaar development format 1 with subtree support "
 
2248
            "(needs bzr.dev from before 1.6)\n")
 
2249
 
 
2250
    def get_format_description(self):
 
2251
        """See RepositoryFormat.get_format_description()."""
 
2252
        return ("Development repository format, currently the same as "
 
2253
            "pack-0.92-subtree with external reference support.\n")