~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Patch Queue Manager
  • Date: 2015-10-05 13:45:00 UTC
  • mfrom: (6603.3.1 bts794146)
  • Revision ID: pqm@pqm.ubuntu.com-20151005134500-v244rho557tv0ukd
(vila) Resolve Bug #1480015: Test failure: hexify removed from paramiko
 (Andrew Starr-Bochicchio) (Andrew Starr-Bochicchio)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2007-2011 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
 
17
from __future__ import absolute_import
 
18
 
17
19
import re
18
20
import sys
19
21
 
24
26
 
25
27
from bzrlib import (
26
28
    chk_map,
 
29
    cleanup,
 
30
    config,
27
31
    debug,
28
32
    graph,
29
33
    osutils,
30
34
    pack,
31
35
    transactions,
 
36
    tsort,
32
37
    ui,
33
 
    xml5,
34
 
    xml6,
35
 
    xml7,
36
38
    )
37
39
from bzrlib.index import (
38
40
    CombinedGraphIndex,
39
 
    GraphIndex,
40
 
    GraphIndexBuilder,
41
41
    GraphIndexPrefixAdapter,
42
 
    InMemoryGraphIndex,
43
 
    )
44
 
from bzrlib.knit import (
45
 
    KnitPlainFactory,
46
 
    KnitVersionedFiles,
47
 
    _KnitGraphIndex,
48
 
    _DirectPackAccess,
49
 
    )
50
 
from bzrlib import tsort
 
42
    )
51
43
""")
52
44
from bzrlib import (
53
 
    bzrdir,
 
45
    btree_index,
54
46
    errors,
55
47
    lockable_files,
56
48
    lockdir,
57
 
    revision as _mod_revision,
58
 
    symbol_versioning,
59
49
    )
60
50
 
61
 
from bzrlib.decorators import needs_write_lock
62
 
from bzrlib.btree_index import (
63
 
    BTreeGraphIndex,
64
 
    BTreeBuilder,
65
 
    )
66
 
from bzrlib.index import (
67
 
    GraphIndex,
68
 
    InMemoryGraphIndex,
69
 
    )
70
 
from bzrlib.repofmt.knitrepo import KnitRepository
 
51
from bzrlib.decorators import (
 
52
    needs_read_lock,
 
53
    needs_write_lock,
 
54
    only_raises,
 
55
    )
 
56
from bzrlib.lock import LogicalLockResult
71
57
from bzrlib.repository import (
72
 
    CommitBuilder,
73
 
    MetaDirRepositoryFormat,
74
 
    RepositoryFormat,
75
 
    RootCommitBuilder,
76
 
    )
77
 
import bzrlib.revision as _mod_revision
 
58
    _LazyListJoin,
 
59
    MetaDirRepository,
 
60
    RepositoryFormatMetaDir,
 
61
    RepositoryWriteLockResult,
 
62
    )
 
63
from bzrlib.vf_repository import (
 
64
    MetaDirVersionedFileRepository,
 
65
    MetaDirVersionedFileRepositoryFormat,
 
66
    VersionedFileCommitBuilder,
 
67
    VersionedFileRootCommitBuilder,
 
68
    )
78
69
from bzrlib.trace import (
79
70
    mutter,
 
71
    note,
80
72
    warning,
81
73
    )
82
74
 
83
75
 
84
 
class PackCommitBuilder(CommitBuilder):
85
 
    """A subclass of CommitBuilder to add texts with pack semantics.
 
76
class PackCommitBuilder(VersionedFileCommitBuilder):
 
77
    """Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
86
78
 
87
79
    Specifically this uses one knit object rather than one knit object per
88
80
    added text, reducing memory and object pressure.
90
82
 
91
83
    def __init__(self, repository, parents, config, timestamp=None,
92
84
                 timezone=None, committer=None, revprops=None,
93
 
                 revision_id=None):
94
 
        CommitBuilder.__init__(self, repository, parents, config,
 
85
                 revision_id=None, lossy=False):
 
86
        VersionedFileCommitBuilder.__init__(self, repository, parents, config,
95
87
            timestamp=timestamp, timezone=timezone, committer=committer,
96
 
            revprops=revprops, revision_id=revision_id)
 
88
            revprops=revprops, revision_id=revision_id, lossy=lossy)
97
89
        self._file_graph = graph.Graph(
98
90
            repository._pack_collection.text_index.combined_index)
99
91
 
102
94
        return set([key[1] for key in self._file_graph.heads(keys)])
103
95
 
104
96
 
105
 
class PackRootCommitBuilder(RootCommitBuilder):
 
97
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
106
98
    """A subclass of RootCommitBuilder to add texts with pack semantics.
107
99
 
108
100
    Specifically this uses one knit object rather than one knit object per
111
103
 
112
104
    def __init__(self, repository, parents, config, timestamp=None,
113
105
                 timezone=None, committer=None, revprops=None,
114
 
                 revision_id=None):
115
 
        CommitBuilder.__init__(self, repository, parents, config,
116
 
            timestamp=timestamp, timezone=timezone, committer=committer,
117
 
            revprops=revprops, revision_id=revision_id)
 
106
                 revision_id=None, lossy=False):
 
107
        super(PackRootCommitBuilder, self).__init__(repository, parents,
 
108
            config, timestamp=timestamp, timezone=timezone,
 
109
            committer=committer, revprops=revprops, revision_id=revision_id,
 
110
            lossy=lossy)
118
111
        self._file_graph = graph.Graph(
119
112
            repository._pack_collection.text_index.combined_index)
120
113
 
228
221
        return self.index_name('text', name)
229
222
 
230
223
    def _replace_index_with_readonly(self, index_type):
231
 
        setattr(self, index_type + '_index',
232
 
            self.index_class(self.index_transport,
233
 
                self.index_name(index_type, self.name),
234
 
                self.index_sizes[self.index_offset(index_type)]))
 
224
        unlimited_cache = False
 
225
        if index_type == 'chk':
 
226
            unlimited_cache = True
 
227
        index = self.index_class(self.index_transport,
 
228
                    self.index_name(index_type, self.name),
 
229
                    self.index_sizes[self.index_offset(index_type)],
 
230
                    unlimited_cache=unlimited_cache)
 
231
        if index_type == 'chk':
 
232
            index._leaf_factory = btree_index._gcchk_factory
 
233
        setattr(self, index_type + '_index', index)
235
234
 
236
235
 
237
236
class ExistingPack(Pack):
268
267
 
269
268
    def __init__(self, name, revision_index, inventory_index, text_index,
270
269
        signature_index, upload_transport, pack_transport, index_transport,
271
 
        pack_collection):
 
270
        pack_collection, chk_index=None):
272
271
        """Create a ResumedPack object."""
273
272
        ExistingPack.__init__(self, pack_transport, name, revision_index,
274
 
            inventory_index, text_index, signature_index)
 
273
            inventory_index, text_index, signature_index,
 
274
            chk_index=chk_index)
275
275
        self.upload_transport = upload_transport
276
276
        self.index_transport = index_transport
277
277
        self.index_sizes = [None, None, None, None]
281
281
            ('text', text_index),
282
282
            ('signature', signature_index),
283
283
            ]
 
284
        if chk_index is not None:
 
285
            indices.append(('chk', chk_index))
 
286
            self.index_sizes.append(None)
284
287
        for index_type, index in indices:
285
288
            offset = self.index_offset(index_type)
286
289
            self.index_sizes[offset] = index._size
301
304
        self.upload_transport.delete(self.file_name())
302
305
        indices = [self.revision_index, self.inventory_index, self.text_index,
303
306
            self.signature_index]
 
307
        if self.chk_index is not None:
 
308
            indices.append(self.chk_index)
304
309
        for index in indices:
305
310
            index._transport.delete(index._name)
306
311
 
307
312
    def finish(self):
308
313
        self._check_references()
309
 
        new_name = '../packs/' + self.file_name()
310
 
        self.upload_transport.rename(self.file_name(), new_name)
311
 
        for index_type in ['revision', 'inventory', 'text', 'signature']:
 
314
        index_types = ['revision', 'inventory', 'text', 'signature']
 
315
        if self.chk_index is not None:
 
316
            index_types.append('chk')
 
317
        for index_type in index_types:
312
318
            old_name = self.index_name(index_type, self.name)
313
319
            new_name = '../indices/' + old_name
314
 
            self.upload_transport.rename(old_name, new_name)
 
320
            self.upload_transport.move(old_name, new_name)
315
321
            self._replace_index_with_readonly(index_type)
 
322
        new_name = '../packs/' + self.file_name()
 
323
        self.upload_transport.move(self.file_name(), new_name)
316
324
        self._state = 'finished'
317
325
 
318
326
    def _get_external_refs(self, index):
 
327
        """Return compression parents for this index that are not present.
 
328
 
 
329
        This returns any compression parents that are referenced by this index,
 
330
        which are not contained *in* this index. They may be present elsewhere.
 
331
        """
319
332
        return index.external_references(1)
320
333
 
321
334
 
412
425
        self._writer.begin()
413
426
        # what state is the pack in? (open, finished, aborted)
414
427
        self._state = 'open'
 
428
        # no name until we finish writing the content
 
429
        self.name = None
415
430
 
416
431
    def abort(self):
417
432
        """Cancel creating this pack."""
438
453
            self.signature_index.key_count() or
439
454
            (self.chk_index is not None and self.chk_index.key_count()))
440
455
 
 
456
    def finish_content(self):
 
457
        if self.name is not None:
 
458
            return
 
459
        self._writer.end()
 
460
        if self._buffer[1]:
 
461
            self._write_data('', flush=True)
 
462
        self.name = self._hash.hexdigest()
 
463
 
441
464
    def finish(self, suspend=False):
442
465
        """Finish the new pack.
443
466
 
449
472
         - stores the index size tuple for the pack in the index_sizes
450
473
           attribute.
451
474
        """
452
 
        self._writer.end()
453
 
        if self._buffer[1]:
454
 
            self._write_data('', flush=True)
455
 
        self.name = self._hash.hexdigest()
 
475
        self.finish_content()
456
476
        if not suspend:
457
477
            self._check_references()
458
478
        # write indices
461
481
        # visible is smaller.  On the other hand none will be seen until
462
482
        # they're in the names list.
463
483
        self.index_sizes = [None, None, None, None]
464
 
        self._write_index('revision', self.revision_index, 'revision', suspend)
 
484
        self._write_index('revision', self.revision_index, 'revision',
 
485
            suspend)
465
486
        self._write_index('inventory', self.inventory_index, 'inventory',
466
487
            suspend)
467
488
        self._write_index('text', self.text_index, 'file texts', suspend)
471
492
            self.index_sizes.append(None)
472
493
            self._write_index('chk', self.chk_index,
473
494
                'content hash bytes', suspend)
474
 
        self.write_stream.close()
 
495
        self.write_stream.close(
 
496
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
475
497
        # Note that this will clobber an existing pack with the same name,
476
498
        # without checking for hash collisions. While this is undesirable this
477
499
        # is something that can be rectified in a subsequent release. One way
486
508
        new_name = self.name + '.pack'
487
509
        if not suspend:
488
510
            new_name = '../packs/' + new_name
489
 
        self.upload_transport.rename(self.random_name, new_name)
 
511
        self.upload_transport.move(self.random_name, new_name)
490
512
        self._state = 'finished'
491
513
        if 'pack' in debug.debug_flags:
492
514
            # XXX: size might be interesting?
520
542
            transport = self.upload_transport
521
543
        else:
522
544
            transport = self.index_transport
523
 
        self.index_sizes[self.index_offset(index_type)] = transport.put_file(
524
 
            index_name, index.finish(), mode=self._file_mode)
 
545
        index_tempfile = index.finish()
 
546
        index_bytes = index_tempfile.read()
 
547
        write_stream = transport.open_write_stream(index_name,
 
548
            mode=self._file_mode)
 
549
        write_stream.write(index_bytes)
 
550
        write_stream.close(
 
551
            want_fdatasync=self._pack_collection.config_stack.get('repository.fdatasync'))
 
552
        self.index_sizes[self.index_offset(index_type)] = len(index_bytes)
525
553
        if 'pack' in debug.debug_flags:
526
554
            # XXX: size might be interesting?
527
555
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
564
592
                                             flush_func=flush_func)
565
593
        self.add_callback = None
566
594
 
567
 
    def replace_indices(self, index_to_pack, indices):
568
 
        """Replace the current mappings with fresh ones.
569
 
 
570
 
        This should probably not be used eventually, rather incremental add and
571
 
        removal of indices. It has been added during refactoring of existing
572
 
        code.
573
 
 
574
 
        :param index_to_pack: A mapping from index objects to
575
 
            (transport, name) tuples for the pack file data.
576
 
        :param indices: A list of indices.
577
 
        """
578
 
        # refresh the revision pack map dict without replacing the instance.
579
 
        self.index_to_pack.clear()
580
 
        self.index_to_pack.update(index_to_pack)
581
 
        # XXX: API break - clearly a 'replace' method would be good?
582
 
        self.combined_index._indices[:] = indices
583
 
        # the current add nodes callback for the current writable index if
584
 
        # there is one.
585
 
        self.add_callback = None
586
 
 
587
595
    def add_index(self, index, pack):
588
596
        """Add index to the aggregate, which is an index for Pack pack.
589
597
 
596
604
        # expose it to the index map
597
605
        self.index_to_pack[index] = pack.access_tuple()
598
606
        # put it at the front of the linear index list
599
 
        self.combined_index.insert_index(0, index)
 
607
        self.combined_index.insert_index(0, index, pack.name)
600
608
 
601
609
    def add_writable_index(self, index, pack):
602
610
        """Add an index which is able to have data added to it.
622
630
        self.data_access.set_writer(None, None, (None, None))
623
631
        self.index_to_pack.clear()
624
632
        del self.combined_index._indices[:]
 
633
        del self.combined_index._index_names[:]
625
634
        self.add_callback = None
626
635
 
627
 
    def remove_index(self, index, pack):
 
636
    def remove_index(self, index):
628
637
        """Remove index from the indices used to answer queries.
629
638
 
630
639
        :param index: An index from the pack parameter.
631
 
        :param pack: A Pack instance.
632
640
        """
633
641
        del self.index_to_pack[index]
634
 
        self.combined_index._indices.remove(index)
 
642
        pos = self.combined_index._indices.index(index)
 
643
        del self.combined_index._indices[pos]
 
644
        del self.combined_index._index_names[pos]
635
645
        if (self.add_callback is not None and
636
646
            getattr(index, 'add_nodes', None) == self.add_callback):
637
647
            self.add_callback = None
667
677
        # What text keys to copy. None for 'all texts'. This is set by
668
678
        # _copy_inventory_texts
669
679
        self._text_filter = None
670
 
        self._extra_init()
671
 
 
672
 
    def _extra_init(self):
673
 
        """A template hook to allow extending the constructor trivially."""
674
 
 
675
 
    def _pack_map_and_index_list(self, index_attribute):
676
 
        """Convert a list of packs to an index pack map and index list.
677
 
 
678
 
        :param index_attribute: The attribute that the desired index is found
679
 
            on.
680
 
        :return: A tuple (map, list) where map contains the dict from
681
 
            index:pack_tuple, and list contains the indices in the preferred
682
 
            access order.
683
 
        """
684
 
        indices = []
685
 
        pack_map = {}
686
 
        for pack_obj in self.packs:
687
 
            index = getattr(pack_obj, index_attribute)
688
 
            indices.append(index)
689
 
            pack_map[index] = pack_obj
690
 
        return pack_map, indices
691
 
 
692
 
    def _index_contents(self, indices, key_filter=None):
693
 
        """Get an iterable of the index contents from a pack_map.
694
 
 
695
 
        :param indices: The list of indices to query
696
 
        :param key_filter: An optional filter to limit the keys returned.
697
 
        """
698
 
        all_index = CombinedGraphIndex(indices)
699
 
        if key_filter is None:
700
 
            return all_index.iter_all_entries()
701
 
        else:
702
 
            return all_index.iter_entries(key_filter)
703
680
 
704
681
    def pack(self, pb=None):
705
682
        """Create a new pack by reading data from other packs.
716
693
        :return: A Pack object, or None if nothing was copied.
717
694
        """
718
695
        # open a pack - using the same name as the last temporary file
719
 
        # - which has already been flushed, so its safe.
 
696
        # - which has already been flushed, so it's safe.
720
697
        # XXX: - duplicate code warning with start_write_group; fix before
721
698
        #      considering 'done'.
722
699
        if self._pack_collection._new_pack is not None:
754
731
        new_pack.signature_index.set_optimize(combine_backing_indices=False)
755
732
        return new_pack
756
733
 
757
 
    def _update_pack_order(self, entries, index_to_pack_map):
758
 
        """Determine how we want our packs to be ordered.
759
 
 
760
 
        This changes the sort order of the self.packs list so that packs unused
761
 
        by 'entries' will be at the end of the list, so that future requests
762
 
        can avoid probing them.  Used packs will be at the front of the
763
 
        self.packs list, in the order of their first use in 'entries'.
764
 
 
765
 
        :param entries: A list of (index, ...) tuples
766
 
        :param index_to_pack_map: A mapping from index objects to pack objects.
767
 
        """
768
 
        packs = []
769
 
        seen_indexes = set()
770
 
        for entry in entries:
771
 
            index = entry[0]
772
 
            if index not in seen_indexes:
773
 
                packs.append(index_to_pack_map[index])
774
 
                seen_indexes.add(index)
775
 
        if len(packs) == len(self.packs):
776
 
            if 'pack' in debug.debug_flags:
777
 
                mutter('Not changing pack list, all packs used.')
778
 
            return
779
 
        seen_packs = set(packs)
780
 
        for pack in self.packs:
781
 
            if pack not in seen_packs:
782
 
                packs.append(pack)
783
 
                seen_packs.add(pack)
784
 
        if 'pack' in debug.debug_flags:
785
 
            old_names = [p.access_tuple()[1] for p in self.packs]
786
 
            new_names = [p.access_tuple()[1] for p in packs]
787
 
            mutter('Reordering packs\nfrom: %s\n  to: %s',
788
 
                   old_names, new_names)
789
 
        self.packs = packs
790
 
 
791
734
    def _copy_revision_texts(self):
792
735
        """Copy revision data to the new pack."""
793
 
        # select revisions
794
 
        if self.revision_ids:
795
 
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
796
 
        else:
797
 
            revision_keys = None
798
 
        # select revision keys
799
 
        revision_index_map, revision_indices = self._pack_map_and_index_list(
800
 
            'revision_index')
801
 
        revision_nodes = self._index_contents(revision_indices, revision_keys)
802
 
        revision_nodes = list(revision_nodes)
803
 
        self._update_pack_order(revision_nodes, revision_index_map)
804
 
        # copy revision keys and adjust values
805
 
        self.pb.update("Copying revision texts", 1)
806
 
        total_items, readv_group_iter = self._revision_node_readv(revision_nodes)
807
 
        list(self._copy_nodes_graph(revision_index_map, self.new_pack._writer,
808
 
            self.new_pack.revision_index, readv_group_iter, total_items))
809
 
        if 'pack' in debug.debug_flags:
810
 
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
811
 
                time.ctime(), self._pack_collection._upload_transport.base,
812
 
                self.new_pack.random_name,
813
 
                self.new_pack.revision_index.key_count(),
814
 
                time.time() - self.new_pack.start_time)
815
 
        self._revision_keys = revision_keys
 
736
        raise NotImplementedError(self._copy_revision_texts)
816
737
 
817
738
    def _copy_inventory_texts(self):
818
739
        """Copy the inventory texts to the new pack.
821
742
 
822
743
        Sets self._text_filter appropriately.
823
744
        """
824
 
        # select inventory keys
825
 
        inv_keys = self._revision_keys # currently the same keyspace, and note that
826
 
        # querying for keys here could introduce a bug where an inventory item
827
 
        # is missed, so do not change it to query separately without cross
828
 
        # checking like the text key check below.
829
 
        inventory_index_map, inventory_indices = self._pack_map_and_index_list(
830
 
            'inventory_index')
831
 
        inv_nodes = self._index_contents(inventory_indices, inv_keys)
832
 
        # copy inventory keys and adjust values
833
 
        # XXX: Should be a helper function to allow different inv representation
834
 
        # at this point.
835
 
        self.pb.update("Copying inventory texts", 2)
836
 
        total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
837
 
        # Only grab the output lines if we will be processing them
838
 
        output_lines = bool(self.revision_ids)
839
 
        inv_lines = self._copy_nodes_graph(inventory_index_map,
840
 
            self.new_pack._writer, self.new_pack.inventory_index,
841
 
            readv_group_iter, total_items, output_lines=output_lines)
842
 
        if self.revision_ids:
843
 
            self._process_inventory_lines(inv_lines)
844
 
        else:
845
 
            # eat the iterator to cause it to execute.
846
 
            list(inv_lines)
847
 
            self._text_filter = None
848
 
        if 'pack' in debug.debug_flags:
849
 
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
850
 
                time.ctime(), self._pack_collection._upload_transport.base,
851
 
                self.new_pack.random_name,
852
 
                self.new_pack.inventory_index.key_count(),
853
 
                time.time() - self.new_pack.start_time)
 
745
        raise NotImplementedError(self._copy_inventory_texts)
854
746
 
855
747
    def _copy_text_texts(self):
856
 
        # select text keys
857
 
        text_index_map, text_nodes = self._get_text_nodes()
858
 
        if self._text_filter is not None:
859
 
            # We could return the keys copied as part of the return value from
860
 
            # _copy_nodes_graph but this doesn't work all that well with the
861
 
            # need to get line output too, so we check separately, and as we're
862
 
            # going to buffer everything anyway, we check beforehand, which
863
 
            # saves reading knit data over the wire when we know there are
864
 
            # mising records.
865
 
            text_nodes = set(text_nodes)
866
 
            present_text_keys = set(_node[1] for _node in text_nodes)
867
 
            missing_text_keys = set(self._text_filter) - present_text_keys
868
 
            if missing_text_keys:
869
 
                # TODO: raise a specific error that can handle many missing
870
 
                # keys.
871
 
                mutter("missing keys during fetch: %r", missing_text_keys)
872
 
                a_missing_key = missing_text_keys.pop()
873
 
                raise errors.RevisionNotPresent(a_missing_key[1],
874
 
                    a_missing_key[0])
875
 
        # copy text keys and adjust values
876
 
        self.pb.update("Copying content texts", 3)
877
 
        total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
878
 
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
879
 
            self.new_pack.text_index, readv_group_iter, total_items))
880
 
        self._log_copied_texts()
 
748
        raise NotImplementedError(self._copy_text_texts)
881
749
 
882
750
    def _create_pack_from_packs(self):
883
 
        self.pb.update("Opening pack", 0, 5)
884
 
        self.new_pack = self.open_pack()
885
 
        new_pack = self.new_pack
886
 
        # buffer data - we won't be reading-back during the pack creation and
887
 
        # this makes a significant difference on sftp pushes.
888
 
        new_pack.set_write_cache_size(1024*1024)
889
 
        if 'pack' in debug.debug_flags:
890
 
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
891
 
                for a_pack in self.packs]
892
 
            if self.revision_ids is not None:
893
 
                rev_count = len(self.revision_ids)
894
 
            else:
895
 
                rev_count = 'all'
896
 
            mutter('%s: create_pack: creating pack from source packs: '
897
 
                '%s%s %s revisions wanted %s t=0',
898
 
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
899
 
                plain_pack_list, rev_count)
900
 
        self._copy_revision_texts()
901
 
        self._copy_inventory_texts()
902
 
        self._copy_text_texts()
903
 
        # select signature keys
904
 
        signature_filter = self._revision_keys # same keyspace
905
 
        signature_index_map, signature_indices = self._pack_map_and_index_list(
906
 
            'signature_index')
907
 
        signature_nodes = self._index_contents(signature_indices,
908
 
            signature_filter)
909
 
        # copy signature keys and adjust values
910
 
        self.pb.update("Copying signature texts", 4)
911
 
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
912
 
            new_pack.signature_index)
913
 
        if 'pack' in debug.debug_flags:
914
 
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
915
 
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
916
 
                new_pack.signature_index.key_count(),
917
 
                time.time() - new_pack.start_time)
918
 
        # copy chk contents
919
 
        # NB XXX: how to check CHK references are present? perhaps by yielding
920
 
        # the items? How should that interact with stacked repos?
921
 
        if new_pack.chk_index is not None:
922
 
            self._copy_chks()
923
 
            if 'pack' in debug.debug_flags:
924
 
                mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
925
 
                    time.ctime(), self._pack_collection._upload_transport.base,
926
 
                    new_pack.random_name,
927
 
                    new_pack.chk_index.key_count(),
928
 
                    time.time() - new_pack.start_time)
929
 
        new_pack._check_references()
930
 
        if not self._use_pack(new_pack):
931
 
            new_pack.abort()
932
 
            return None
933
 
        self.pb.update("Finishing pack", 5)
934
 
        new_pack.finish()
935
 
        self._pack_collection.allocate(new_pack)
936
 
        return new_pack
937
 
 
938
 
    def _copy_chks(self, refs=None):
939
 
        # XXX: Todo, recursive follow-pointers facility when fetching some
940
 
        # revisions only.
941
 
        chk_index_map, chk_indices = self._pack_map_and_index_list(
942
 
            'chk_index')
943
 
        chk_nodes = self._index_contents(chk_indices, refs)
944
 
        new_refs = set()
945
 
        # TODO: This isn't strictly tasteful as we are accessing some private
946
 
        #       variables (_serializer). Perhaps a better way would be to have
947
 
        #       Repository._deserialise_chk_node()
948
 
        search_key_func = chk_map.search_key_registry.get(
949
 
            self._pack_collection.repo._serializer.search_key_name)
950
 
        def accumlate_refs(lines):
951
 
            # XXX: move to a generic location
952
 
            # Yay mismatch:
953
 
            bytes = ''.join(lines)
954
 
            node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
955
 
            new_refs.update(node.refs())
956
 
        self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
957
 
            self.new_pack.chk_index, output_lines=accumlate_refs)
958
 
        return new_refs
959
 
 
960
 
    def _copy_nodes(self, nodes, index_map, writer, write_index,
961
 
        output_lines=None):
962
 
        """Copy knit nodes between packs with no graph references.
963
 
 
964
 
        :param output_lines: Output full texts of copied items.
965
 
        """
966
 
        pb = ui.ui_factory.nested_progress_bar()
967
 
        try:
968
 
            return self._do_copy_nodes(nodes, index_map, writer,
969
 
                write_index, pb, output_lines=output_lines)
970
 
        finally:
971
 
            pb.finished()
972
 
 
973
 
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
974
 
        output_lines=None):
975
 
        # for record verification
976
 
        knit = KnitVersionedFiles(None, None)
977
 
        # plan a readv on each source pack:
978
 
        # group by pack
979
 
        nodes = sorted(nodes)
980
 
        # how to map this into knit.py - or knit.py into this?
981
 
        # we don't want the typical knit logic, we want grouping by pack
982
 
        # at this point - perhaps a helper library for the following code
983
 
        # duplication points?
984
 
        request_groups = {}
985
 
        for index, key, value in nodes:
986
 
            if index not in request_groups:
987
 
                request_groups[index] = []
988
 
            request_groups[index].append((key, value))
989
 
        record_index = 0
990
 
        pb.update("Copied record", record_index, len(nodes))
991
 
        for index, items in request_groups.iteritems():
992
 
            pack_readv_requests = []
993
 
            for key, value in items:
994
 
                # ---- KnitGraphIndex.get_position
995
 
                bits = value[1:].split(' ')
996
 
                offset, length = int(bits[0]), int(bits[1])
997
 
                pack_readv_requests.append((offset, length, (key, value[0])))
998
 
            # linear scan up the pack
999
 
            pack_readv_requests.sort()
1000
 
            # copy the data
1001
 
            pack_obj = index_map[index]
1002
 
            transport, path = pack_obj.access_tuple()
1003
 
            try:
1004
 
                reader = pack.make_readv_reader(transport, path,
1005
 
                    [offset[0:2] for offset in pack_readv_requests])
1006
 
            except errors.NoSuchFile:
1007
 
                if self._reload_func is not None:
1008
 
                    self._reload_func()
1009
 
                raise
1010
 
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
1011
 
                izip(reader.iter_records(), pack_readv_requests):
1012
 
                raw_data = read_func(None)
1013
 
                # check the header only
1014
 
                if output_lines is not None:
1015
 
                    output_lines(knit._parse_record(key[-1], raw_data)[0])
1016
 
                else:
1017
 
                    df, _ = knit._parse_record_header(key, raw_data)
1018
 
                    df.close()
1019
 
                pos, size = writer.add_bytes_record(raw_data, names)
1020
 
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1021
 
                pb.update("Copied record", record_index)
1022
 
                record_index += 1
1023
 
 
1024
 
    def _copy_nodes_graph(self, index_map, writer, write_index,
1025
 
        readv_group_iter, total_items, output_lines=False):
1026
 
        """Copy knit nodes between packs.
1027
 
 
1028
 
        :param output_lines: Return lines present in the copied data as
1029
 
            an iterator of line,version_id.
1030
 
        """
1031
 
        pb = ui.ui_factory.nested_progress_bar()
1032
 
        try:
1033
 
            for result in self._do_copy_nodes_graph(index_map, writer,
1034
 
                write_index, output_lines, pb, readv_group_iter, total_items):
1035
 
                yield result
1036
 
        except Exception:
1037
 
            # Python 2.4 does not permit try:finally: in a generator.
1038
 
            pb.finished()
1039
 
            raise
1040
 
        else:
1041
 
            pb.finished()
1042
 
 
1043
 
    def _do_copy_nodes_graph(self, index_map, writer, write_index,
1044
 
        output_lines, pb, readv_group_iter, total_items):
1045
 
        # for record verification
1046
 
        knit = KnitVersionedFiles(None, None)
1047
 
        # for line extraction when requested (inventories only)
1048
 
        if output_lines:
1049
 
            factory = KnitPlainFactory()
1050
 
        record_index = 0
1051
 
        pb.update("Copied record", record_index, total_items)
1052
 
        for index, readv_vector, node_vector in readv_group_iter:
1053
 
            # copy the data
1054
 
            pack_obj = index_map[index]
1055
 
            transport, path = pack_obj.access_tuple()
1056
 
            try:
1057
 
                reader = pack.make_readv_reader(transport, path, readv_vector)
1058
 
            except errors.NoSuchFile:
1059
 
                if self._reload_func is not None:
1060
 
                    self._reload_func()
1061
 
                raise
1062
 
            for (names, read_func), (key, eol_flag, references) in \
1063
 
                izip(reader.iter_records(), node_vector):
1064
 
                raw_data = read_func(None)
1065
 
                if output_lines:
1066
 
                    # read the entire thing
1067
 
                    content, _ = knit._parse_record(key[-1], raw_data)
1068
 
                    if len(references[-1]) == 0:
1069
 
                        line_iterator = factory.get_fulltext_content(content)
1070
 
                    else:
1071
 
                        line_iterator = factory.get_linedelta_content(content)
1072
 
                    for line in line_iterator:
1073
 
                        yield line, key
1074
 
                else:
1075
 
                    # check the header only
1076
 
                    df, _ = knit._parse_record_header(key, raw_data)
1077
 
                    df.close()
1078
 
                pos, size = writer.add_bytes_record(raw_data, names)
1079
 
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1080
 
                pb.update("Copied record", record_index)
1081
 
                record_index += 1
1082
 
 
1083
 
    def _get_text_nodes(self):
1084
 
        text_index_map, text_indices = self._pack_map_and_index_list(
1085
 
            'text_index')
1086
 
        return text_index_map, self._index_contents(text_indices,
1087
 
            self._text_filter)
1088
 
 
1089
 
    def _least_readv_node_readv(self, nodes):
1090
 
        """Generate request groups for nodes using the least readv's.
1091
 
 
1092
 
        :param nodes: An iterable of graph index nodes.
1093
 
        :return: Total node count and an iterator of the data needed to perform
1094
 
            readvs to obtain the data for nodes. Each item yielded by the
1095
 
            iterator is a tuple with:
1096
 
            index, readv_vector, node_vector. readv_vector is a list ready to
1097
 
            hand to the transport readv method, and node_vector is a list of
1098
 
            (key, eol_flag, references) for the the node retrieved by the
1099
 
            matching readv_vector.
1100
 
        """
1101
 
        # group by pack so we do one readv per pack
1102
 
        nodes = sorted(nodes)
1103
 
        total = len(nodes)
1104
 
        request_groups = {}
1105
 
        for index, key, value, references in nodes:
1106
 
            if index not in request_groups:
1107
 
                request_groups[index] = []
1108
 
            request_groups[index].append((key, value, references))
1109
 
        result = []
1110
 
        for index, items in request_groups.iteritems():
1111
 
            pack_readv_requests = []
1112
 
            for key, value, references in items:
1113
 
                # ---- KnitGraphIndex.get_position
1114
 
                bits = value[1:].split(' ')
1115
 
                offset, length = int(bits[0]), int(bits[1])
1116
 
                pack_readv_requests.append(
1117
 
                    ((offset, length), (key, value[0], references)))
1118
 
            # linear scan up the pack to maximum range combining.
1119
 
            pack_readv_requests.sort()
1120
 
            # split out the readv and the node data.
1121
 
            pack_readv = [readv for readv, node in pack_readv_requests]
1122
 
            node_vector = [node for readv, node in pack_readv_requests]
1123
 
            result.append((index, pack_readv, node_vector))
1124
 
        return total, result
 
751
        raise NotImplementedError(self._create_pack_from_packs)
1125
752
 
1126
753
    def _log_copied_texts(self):
1127
754
        if 'pack' in debug.debug_flags:
1131
758
                self.new_pack.text_index.key_count(),
1132
759
                time.time() - self.new_pack.start_time)
1133
760
 
1134
 
    def _process_inventory_lines(self, inv_lines):
1135
 
        """Use up the inv_lines generator and setup a text key filter."""
1136
 
        repo = self._pack_collection.repo
1137
 
        fileid_revisions = repo._find_file_ids_from_xml_inventory_lines(
1138
 
            inv_lines, self.revision_keys)
1139
 
        text_filter = []
1140
 
        for fileid, file_revids in fileid_revisions.iteritems():
1141
 
            text_filter.extend([(fileid, file_revid) for file_revid in file_revids])
1142
 
        self._text_filter = text_filter
1143
 
 
1144
 
    def _revision_node_readv(self, revision_nodes):
1145
 
        """Return the total revisions and the readv's to issue.
1146
 
 
1147
 
        :param revision_nodes: The revision index contents for the packs being
1148
 
            incorporated into the new pack.
1149
 
        :return: As per _least_readv_node_readv.
1150
 
        """
1151
 
        return self._least_readv_node_readv(revision_nodes)
1152
 
 
1153
761
    def _use_pack(self, new_pack):
1154
762
        """Return True if new_pack should be used.
1155
763
 
1159
767
        return new_pack.data_inserted()
1160
768
 
1161
769
 
1162
 
class OptimisingPacker(Packer):
1163
 
    """A packer which spends more time to create better disk layouts."""
1164
 
 
1165
 
    def _revision_node_readv(self, revision_nodes):
1166
 
        """Return the total revisions and the readv's to issue.
1167
 
 
1168
 
        This sort places revisions in topological order with the ancestors
1169
 
        after the children.
1170
 
 
1171
 
        :param revision_nodes: The revision index contents for the packs being
1172
 
            incorporated into the new pack.
1173
 
        :return: As per _least_readv_node_readv.
1174
 
        """
1175
 
        # build an ancestors dict
1176
 
        ancestors = {}
1177
 
        by_key = {}
1178
 
        for index, key, value, references in revision_nodes:
1179
 
            ancestors[key] = references[0]
1180
 
            by_key[key] = (index, value, references)
1181
 
        order = tsort.topo_sort(ancestors)
1182
 
        total = len(order)
1183
 
        # Single IO is pathological, but it will work as a starting point.
1184
 
        requests = []
1185
 
        for key in reversed(order):
1186
 
            index, value, references = by_key[key]
1187
 
            # ---- KnitGraphIndex.get_position
1188
 
            bits = value[1:].split(' ')
1189
 
            offset, length = int(bits[0]), int(bits[1])
1190
 
            requests.append(
1191
 
                (index, [(offset, length)], [(key, value[0], references)]))
1192
 
        # TODO: combine requests in the same index that are in ascending order.
1193
 
        return total, requests
1194
 
 
1195
 
    def open_pack(self):
1196
 
        """Open a pack for the pack we are creating."""
1197
 
        new_pack = super(OptimisingPacker, self).open_pack()
1198
 
        # Turn on the optimization flags for all the index builders.
1199
 
        new_pack.revision_index.set_optimize(for_size=True)
1200
 
        new_pack.inventory_index.set_optimize(for_size=True)
1201
 
        new_pack.text_index.set_optimize(for_size=True)
1202
 
        new_pack.signature_index.set_optimize(for_size=True)
1203
 
        return new_pack
1204
 
 
1205
 
 
1206
 
class ReconcilePacker(Packer):
1207
 
    """A packer which regenerates indices etc as it copies.
1208
 
 
1209
 
    This is used by ``bzr reconcile`` to cause parent text pointers to be
1210
 
    regenerated.
1211
 
    """
1212
 
 
1213
 
    def _extra_init(self):
1214
 
        self._data_changed = False
1215
 
 
1216
 
    def _process_inventory_lines(self, inv_lines):
1217
 
        """Generate a text key reference map rather for reconciling with."""
1218
 
        repo = self._pack_collection.repo
1219
 
        refs = repo._find_text_key_references_from_xml_inventory_lines(
1220
 
            inv_lines)
1221
 
        self._text_refs = refs
1222
 
        # during reconcile we:
1223
 
        #  - convert unreferenced texts to full texts
1224
 
        #  - correct texts which reference a text not copied to be full texts
1225
 
        #  - copy all others as-is but with corrected parents.
1226
 
        #  - so at this point we don't know enough to decide what becomes a full
1227
 
        #    text.
1228
 
        self._text_filter = None
1229
 
 
1230
 
    def _copy_text_texts(self):
1231
 
        """generate what texts we should have and then copy."""
1232
 
        self.pb.update("Copying content texts", 3)
1233
 
        # we have three major tasks here:
1234
 
        # 1) generate the ideal index
1235
 
        repo = self._pack_collection.repo
1236
 
        ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1237
 
            _1, key, _2, refs in
1238
 
            self.new_pack.revision_index.iter_all_entries()])
1239
 
        ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1240
 
        # 2) generate a text_nodes list that contains all the deltas that can
1241
 
        #    be used as-is, with corrected parents.
1242
 
        ok_nodes = []
1243
 
        bad_texts = []
1244
 
        discarded_nodes = []
1245
 
        NULL_REVISION = _mod_revision.NULL_REVISION
1246
 
        text_index_map, text_nodes = self._get_text_nodes()
1247
 
        for node in text_nodes:
1248
 
            # 0 - index
1249
 
            # 1 - key
1250
 
            # 2 - value
1251
 
            # 3 - refs
1252
 
            try:
1253
 
                ideal_parents = tuple(ideal_index[node[1]])
1254
 
            except KeyError:
1255
 
                discarded_nodes.append(node)
1256
 
                self._data_changed = True
1257
 
            else:
1258
 
                if ideal_parents == (NULL_REVISION,):
1259
 
                    ideal_parents = ()
1260
 
                if ideal_parents == node[3][0]:
1261
 
                    # no change needed.
1262
 
                    ok_nodes.append(node)
1263
 
                elif ideal_parents[0:1] == node[3][0][0:1]:
1264
 
                    # the left most parent is the same, or there are no parents
1265
 
                    # today. Either way, we can preserve the representation as
1266
 
                    # long as we change the refs to be inserted.
1267
 
                    self._data_changed = True
1268
 
                    ok_nodes.append((node[0], node[1], node[2],
1269
 
                        (ideal_parents, node[3][1])))
1270
 
                    self._data_changed = True
1271
 
                else:
1272
 
                    # Reinsert this text completely
1273
 
                    bad_texts.append((node[1], ideal_parents))
1274
 
                    self._data_changed = True
1275
 
        # we're finished with some data.
1276
 
        del ideal_index
1277
 
        del text_nodes
1278
 
        # 3) bulk copy the ok data
1279
 
        total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1280
 
        list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1281
 
            self.new_pack.text_index, readv_group_iter, total_items))
1282
 
        # 4) adhoc copy all the other texts.
1283
 
        # We have to topologically insert all texts otherwise we can fail to
1284
 
        # reconcile when parts of a single delta chain are preserved intact,
1285
 
        # and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1286
 
        # reinserted, and if d3 has incorrect parents it will also be
1287
 
        # reinserted. If we insert d3 first, d2 is present (as it was bulk
1288
 
        # copied), so we will try to delta, but d2 is not currently able to be
1289
 
        # extracted because it's basis d1 is not present. Topologically sorting
1290
 
        # addresses this. The following generates a sort for all the texts that
1291
 
        # are being inserted without having to reference the entire text key
1292
 
        # space (we only topo sort the revisions, which is smaller).
1293
 
        topo_order = tsort.topo_sort(ancestors)
1294
 
        rev_order = dict(zip(topo_order, range(len(topo_order))))
1295
 
        bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1296
 
        transaction = repo.get_transaction()
1297
 
        file_id_index = GraphIndexPrefixAdapter(
1298
 
            self.new_pack.text_index,
1299
 
            ('blank', ), 1,
1300
 
            add_nodes_callback=self.new_pack.text_index.add_nodes)
1301
 
        data_access = _DirectPackAccess(
1302
 
                {self.new_pack.text_index:self.new_pack.access_tuple()})
1303
 
        data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1304
 
            self.new_pack.access_tuple())
1305
 
        output_texts = KnitVersionedFiles(
1306
 
            _KnitGraphIndex(self.new_pack.text_index,
1307
 
                add_callback=self.new_pack.text_index.add_nodes,
1308
 
                deltas=True, parents=True, is_locked=repo.is_locked),
1309
 
            data_access=data_access, max_delta_chain=200)
1310
 
        for key, parent_keys in bad_texts:
1311
 
            # We refer to the new pack to delta data being output.
1312
 
            # A possible improvement would be to catch errors on short reads
1313
 
            # and only flush then.
1314
 
            self.new_pack.flush()
1315
 
            parents = []
1316
 
            for parent_key in parent_keys:
1317
 
                if parent_key[0] != key[0]:
1318
 
                    # Graph parents must match the fileid
1319
 
                    raise errors.BzrError('Mismatched key parent %r:%r' %
1320
 
                        (key, parent_keys))
1321
 
                parents.append(parent_key[1])
1322
 
            text_lines = osutils.split_lines(repo.texts.get_record_stream(
1323
 
                [key], 'unordered', True).next().get_bytes_as('fulltext'))
1324
 
            output_texts.add_lines(key, parent_keys, text_lines,
1325
 
                random_id=True, check_content=False)
1326
 
        # 5) check that nothing inserted has a reference outside the keyspace.
1327
 
        missing_text_keys = self.new_pack.text_index._external_references()
1328
 
        if missing_text_keys:
1329
 
            raise errors.BzrCheckError('Reference to missing compression parents %r'
1330
 
                % (missing_text_keys,))
1331
 
        self._log_copied_texts()
1332
 
 
1333
 
    def _use_pack(self, new_pack):
1334
 
        """Override _use_pack to check for reconcile having changed content."""
1335
 
        # XXX: we might be better checking this at the copy time.
1336
 
        original_inventory_keys = set()
1337
 
        inv_index = self._pack_collection.inventory_index.combined_index
1338
 
        for entry in inv_index.iter_all_entries():
1339
 
            original_inventory_keys.add(entry[1])
1340
 
        new_inventory_keys = set()
1341
 
        for entry in new_pack.inventory_index.iter_all_entries():
1342
 
            new_inventory_keys.add(entry[1])
1343
 
        if new_inventory_keys != original_inventory_keys:
1344
 
            self._data_changed = True
1345
 
        return new_pack.data_inserted() and self._data_changed
1346
 
 
1347
 
 
1348
770
class RepositoryPackCollection(object):
1349
771
    """Management of packs within a repository.
1350
772
 
1351
773
    :ivar _names: map of {pack_name: (index_size,)}
1352
774
    """
1353
775
 
1354
 
    pack_factory = NewPack
 
776
    pack_factory = None
 
777
    resumed_pack_factory = None
 
778
    normal_packer_class = None
 
779
    optimising_packer_class = None
1355
780
 
1356
781
    def __init__(self, repo, transport, index_transport, upload_transport,
1357
782
                 pack_transport, index_builder_class, index_class,
1392
817
        self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
1393
818
        self.text_index = AggregateIndex(self.reload_pack_names, flush)
1394
819
        self.signature_index = AggregateIndex(self.reload_pack_names, flush)
 
820
        all_indices = [self.revision_index, self.inventory_index,
 
821
                self.text_index, self.signature_index]
1395
822
        if use_chk_index:
1396
823
            self.chk_index = AggregateIndex(self.reload_pack_names, flush)
 
824
            all_indices.append(self.chk_index)
1397
825
        else:
1398
826
            # used to determine if we're using a chk_index elsewhere.
1399
827
            self.chk_index = None
 
828
        # Tell all the CombinedGraphIndex objects about each other, so they can
 
829
        # share hints about which pack names to search first.
 
830
        all_combined = [agg_idx.combined_index for agg_idx in all_indices]
 
831
        for combined_idx in all_combined:
 
832
            combined_idx.set_sibling_indices(
 
833
                set(all_combined).difference([combined_idx]))
1400
834
        # resumed packs
1401
835
        self._resumed_packs = []
 
836
        self.config_stack = config.LocationStack(self.transport.base)
 
837
 
 
838
    def __repr__(self):
 
839
        return '%s(%r)' % (self.__class__.__name__, self.repo)
1402
840
 
1403
841
    def add_pack_to_memory(self, pack):
1404
842
        """Make a Pack object available to the repository to satisfy queries.
1443
881
        in synchronisation with certain steps. Otherwise the names collection
1444
882
        is not flushed.
1445
883
 
1446
 
        :return: True if packing took place.
 
884
        :return: Something evaluating true if packing took place.
1447
885
        """
1448
886
        while True:
1449
887
            try:
1450
888
                return self._do_autopack()
1451
 
            except errors.RetryAutopack, e:
 
889
            except errors.RetryAutopack:
1452
890
                # If we get a RetryAutopack exception, we should abort the
1453
891
                # current action, and retry.
1454
892
                pass
1458
896
        total_revisions = self.revision_index.combined_index.key_count()
1459
897
        total_packs = len(self._names)
1460
898
        if self._max_pack_count(total_revisions) >= total_packs:
1461
 
            return False
 
899
            return None
1462
900
        # determine which packs need changing
1463
901
        pack_distribution = self.pack_distribution(total_revisions)
1464
902
        existing_packs = []
1486
924
            'containing %d revisions. Packing %d files into %d affecting %d'
1487
925
            ' revisions', self, total_packs, total_revisions, num_old_packs,
1488
926
            num_new_packs, num_revs_affected)
1489
 
        self._execute_pack_operations(pack_operations,
 
927
        result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
1490
928
                                      reload_func=self._restart_autopack)
1491
929
        mutter('Auto-packing repository %s completed', self)
1492
 
        return True
 
930
        return result
1493
931
 
1494
 
    def _execute_pack_operations(self, pack_operations, _packer_class=Packer,
1495
 
                                 reload_func=None):
 
932
    def _execute_pack_operations(self, pack_operations, packer_class,
 
933
            reload_func=None):
1496
934
        """Execute a series of pack operations.
1497
935
 
1498
936
        :param pack_operations: A list of [revision_count, packs_to_combine].
1499
 
        :param _packer_class: The class of packer to use (default: Packer).
1500
 
        :return: None.
 
937
        :param packer_class: The class of packer to use
 
938
        :return: The new pack names.
1501
939
        """
1502
940
        for revision_count, packs in pack_operations:
1503
941
            # we may have no-ops from the setup logic
1504
942
            if len(packs) == 0:
1505
943
                continue
1506
 
            packer = _packer_class(self, packs, '.autopack',
 
944
            packer = packer_class(self, packs, '.autopack',
1507
945
                                   reload_func=reload_func)
1508
946
            try:
1509
 
                packer.pack()
 
947
                result = packer.pack()
1510
948
            except errors.RetryWithNewPacks:
1511
949
                # An exception is propagating out of this context, make sure
1512
950
                # this packer has cleaned up. Packer() doesn't set its new_pack
1515
953
                if packer.new_pack is not None:
1516
954
                    packer.new_pack.abort()
1517
955
                raise
 
956
            if result is None:
 
957
                return
1518
958
            for pack in packs:
1519
959
                self._remove_pack_from_memory(pack)
1520
960
        # record the newly available packs and stop advertising the old
1521
961
        # packs
1522
 
        self._save_pack_names(clear_obsolete_packs=True)
1523
 
        # Move the old packs out of the way now they are no longer referenced.
1524
 
        for revision_count, packs in pack_operations:
1525
 
            self._obsolete_packs(packs)
 
962
        to_be_obsoleted = []
 
963
        for _, packs in pack_operations:
 
964
            to_be_obsoleted.extend(packs)
 
965
        result = self._save_pack_names(clear_obsolete_packs=True,
 
966
                                       obsolete_packs=to_be_obsoleted)
 
967
        return result
1526
968
 
1527
969
    def _flush_new_pack(self):
1528
970
        if self._new_pack is not None:
1538
980
 
1539
981
    def _already_packed(self):
1540
982
        """Is the collection already packed?"""
1541
 
        return len(self._names) < 2
 
983
        return not (self.repo._format.pack_compresses or (len(self._names) > 1))
1542
984
 
1543
 
    def pack(self):
 
985
    def pack(self, hint=None, clean_obsolete_packs=False):
1544
986
        """Pack the pack collection totally."""
1545
987
        self.ensure_loaded()
1546
988
        total_packs = len(self._names)
1547
989
        if self._already_packed():
1548
 
            # This is arguably wrong because we might not be optimal, but for
1549
 
            # now lets leave it in. (e.g. reconcile -> one pack. But not
1550
 
            # optimal.
1551
990
            return
1552
991
        total_revisions = self.revision_index.combined_index.key_count()
1553
992
        # XXX: the following may want to be a class, to pack with a given
1554
993
        # policy.
1555
994
        mutter('Packing repository %s, which has %d pack files, '
1556
 
            'containing %d revisions into 1 packs.', self, total_packs,
1557
 
            total_revisions)
 
995
            'containing %d revisions with hint %r.', self, total_packs,
 
996
            total_revisions, hint)
 
997
        while True:
 
998
            try:
 
999
                self._try_pack_operations(hint)
 
1000
            except RetryPackOperations:
 
1001
                continue
 
1002
            break
 
1003
 
 
1004
        if clean_obsolete_packs:
 
1005
            self._clear_obsolete_packs()
 
1006
 
 
1007
    def _try_pack_operations(self, hint):
 
1008
        """Calculate the pack operations based on the hint (if any), and
 
1009
        execute them.
 
1010
        """
1558
1011
        # determine which packs need changing
1559
 
        pack_distribution = [1]
1560
1012
        pack_operations = [[0, []]]
1561
1013
        for pack in self.all_packs():
1562
 
            pack_operations[-1][0] += pack.get_revision_count()
1563
 
            pack_operations[-1][1].append(pack)
1564
 
        self._execute_pack_operations(pack_operations, OptimisingPacker)
 
1014
            if hint is None or pack.name in hint:
 
1015
                # Either no hint was provided (so we are packing everything),
 
1016
                # or this pack was included in the hint.
 
1017
                pack_operations[-1][0] += pack.get_revision_count()
 
1018
                pack_operations[-1][1].append(pack)
 
1019
        self._execute_pack_operations(pack_operations,
 
1020
            packer_class=self.optimising_packer_class,
 
1021
            reload_func=self._restart_pack_operations)
1565
1022
 
1566
1023
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
1567
1024
        """Plan a pack operation.
1577
1034
        pack_operations = [[0, []]]
1578
1035
        # plan out what packs to keep, and what to reorganise
1579
1036
        while len(existing_packs):
1580
 
            # take the largest pack, and if its less than the head of the
 
1037
            # take the largest pack, and if it's less than the head of the
1581
1038
            # distribution chart we will include its contents in the new pack
1582
 
            # for that position. If its larger, we remove its size from the
 
1039
            # for that position. If it's larger, we remove its size from the
1583
1040
            # distribution chart
1584
1041
            next_pack_rev_count, next_pack = existing_packs.pop(0)
1585
1042
            if next_pack_rev_count >= pack_distribution[0]:
1620
1077
 
1621
1078
        :return: True if the disk names had not been previously read.
1622
1079
        """
1623
 
        # NB: if you see an assertion error here, its probably access against
 
1080
        # NB: if you see an assertion error here, it's probably access against
1624
1081
        # an unlocked repo. Naughty.
1625
1082
        if not self.repo.is_locked():
1626
1083
            raise errors.ObjectNotLocked(self.repo)
1656
1113
            txt_index = self._make_index(name, '.tix')
1657
1114
            sig_index = self._make_index(name, '.six')
1658
1115
            if self.chk_index is not None:
1659
 
                chk_index = self._make_index(name, '.cix')
 
1116
                chk_index = self._make_index(name, '.cix', is_chk=True)
1660
1117
            else:
1661
1118
                chk_index = None
1662
1119
            result = ExistingPack(self._pack_transport, name, rev_index,
1680
1137
            inv_index = self._make_index(name, '.iix', resume=True)
1681
1138
            txt_index = self._make_index(name, '.tix', resume=True)
1682
1139
            sig_index = self._make_index(name, '.six', resume=True)
1683
 
            result = ResumedPack(name, rev_index, inv_index, txt_index,
1684
 
                sig_index, self._upload_transport, self._pack_transport,
1685
 
                self._index_transport, self)
 
1140
            if self.chk_index is not None:
 
1141
                chk_index = self._make_index(name, '.cix', resume=True,
 
1142
                                             is_chk=True)
 
1143
            else:
 
1144
                chk_index = None
 
1145
            result = self.resumed_pack_factory(name, rev_index, inv_index,
 
1146
                txt_index, sig_index, self._upload_transport,
 
1147
                self._pack_transport, self._index_transport, self,
 
1148
                chk_index=chk_index)
1686
1149
        except errors.NoSuchFile, e:
1687
1150
            raise errors.UnresumableWriteGroup(self.repo, [name], str(e))
1688
1151
        self.add_pack_to_memory(result)
1712
1175
        return self._index_class(self.transport, 'pack-names', None
1713
1176
                ).iter_all_entries()
1714
1177
 
1715
 
    def _make_index(self, name, suffix, resume=False):
 
1178
    def _make_index(self, name, suffix, resume=False, is_chk=False):
1716
1179
        size_offset = self._suffix_offsets[suffix]
1717
1180
        index_name = name + suffix
1718
1181
        if resume:
1721
1184
        else:
1722
1185
            transport = self._index_transport
1723
1186
            index_size = self._names[name][size_offset]
1724
 
        return self._index_class(transport, index_name, index_size)
 
1187
        index = self._index_class(transport, index_name, index_size,
 
1188
                                  unlimited_cache=is_chk)
 
1189
        if is_chk and self._index_class is btree_index.BTreeGraphIndex: 
 
1190
            index._leaf_factory = btree_index._gcchk_factory
 
1191
        return index
1725
1192
 
1726
1193
    def _max_pack_count(self, total_revisions):
1727
1194
        """Return the maximum number of packs to use for total revisions.
1755
1222
        :param return: None.
1756
1223
        """
1757
1224
        for pack in packs:
1758
 
            pack.pack_transport.rename(pack.file_name(),
1759
 
                '../obsolete_packs/' + pack.file_name())
 
1225
            try:
 
1226
                try:
 
1227
                    pack.pack_transport.move(pack.file_name(),
 
1228
                        '../obsolete_packs/' + pack.file_name())
 
1229
                except errors.NoSuchFile:
 
1230
                    # perhaps obsolete_packs was removed? Let's create it and
 
1231
                    # try again
 
1232
                    try:
 
1233
                        pack.pack_transport.mkdir('../obsolete_packs/')
 
1234
                    except errors.FileExists:
 
1235
                        pass
 
1236
                    pack.pack_transport.move(pack.file_name(),
 
1237
                        '../obsolete_packs/' + pack.file_name())
 
1238
            except (errors.PathError, errors.TransportError), e:
 
1239
                # TODO: Should these be warnings or mutters?
 
1240
                mutter("couldn't rename obsolete pack, skipping it:\n%s"
 
1241
                       % (e,))
1760
1242
            # TODO: Probably needs to know all possible indices for this pack
1761
1243
            # - or maybe list the directory and move all indices matching this
1762
1244
            # name whether we recognize it or not?
1764
1246
            if self.chk_index is not None:
1765
1247
                suffixes.append('.cix')
1766
1248
            for suffix in suffixes:
1767
 
                self._index_transport.rename(pack.name + suffix,
1768
 
                    '../obsolete_packs/' + pack.name + suffix)
 
1249
                try:
 
1250
                    self._index_transport.move(pack.name + suffix,
 
1251
                        '../obsolete_packs/' + pack.name + suffix)
 
1252
                except (errors.PathError, errors.TransportError), e:
 
1253
                    mutter("couldn't rename obsolete index, skipping it:\n%s"
 
1254
                           % (e,))
1769
1255
 
1770
1256
    def pack_distribution(self, total_revisions):
1771
1257
        """Generate a list of the number of revisions to put in each pack.
1797
1283
        self._remove_pack_indices(pack)
1798
1284
        self.packs.remove(pack)
1799
1285
 
1800
 
    def _remove_pack_indices(self, pack):
1801
 
        """Remove the indices for pack from the aggregated indices."""
1802
 
        self.revision_index.remove_index(pack.revision_index, pack)
1803
 
        self.inventory_index.remove_index(pack.inventory_index, pack)
1804
 
        self.text_index.remove_index(pack.text_index, pack)
1805
 
        self.signature_index.remove_index(pack.signature_index, pack)
1806
 
        if self.chk_index is not None:
1807
 
            self.chk_index.remove_index(pack.chk_index, pack)
 
1286
    def _remove_pack_indices(self, pack, ignore_missing=False):
 
1287
        """Remove the indices for pack from the aggregated indices.
 
1288
        
 
1289
        :param ignore_missing: Suppress KeyErrors from calling remove_index.
 
1290
        """
 
1291
        for index_type in Pack.index_definitions.keys():
 
1292
            attr_name = index_type + '_index'
 
1293
            aggregate_index = getattr(self, attr_name)
 
1294
            if aggregate_index is not None:
 
1295
                pack_index = getattr(pack, attr_name)
 
1296
                try:
 
1297
                    aggregate_index.remove_index(pack_index)
 
1298
                except KeyError:
 
1299
                    if ignore_missing:
 
1300
                        continue
 
1301
                    raise
1808
1302
 
1809
1303
    def reset(self):
1810
1304
        """Clear all cached data."""
1811
1305
        # cached revision data
1812
 
        self.repo._revision_knit = None
1813
1306
        self.revision_index.clear()
1814
1307
        # cached signature data
1815
 
        self.repo._signature_knit = None
1816
1308
        self.signature_index.clear()
1817
1309
        # cached file text data
1818
1310
        self.text_index.clear()
1819
 
        self.repo._text_knit = None
1820
1311
        # cached inventory data
1821
1312
        self.inventory_index.clear()
1822
1313
        # cached chk data
1846
1337
        disk_nodes = set()
1847
1338
        for index, key, value in self._iter_disk_pack_index():
1848
1339
            disk_nodes.add((key, value))
 
1340
        orig_disk_nodes = set(disk_nodes)
1849
1341
 
1850
1342
        # do a two-way diff against our original content
1851
1343
        current_nodes = set()
1864
1356
        disk_nodes.difference_update(deleted_nodes)
1865
1357
        disk_nodes.update(new_nodes)
1866
1358
 
1867
 
        return disk_nodes, deleted_nodes, new_nodes
 
1359
        return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
1868
1360
 
1869
1361
    def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1870
1362
        """Given the correct set of pack files, update our saved info.
1898
1390
                    # disk index because the set values are the same, unless
1899
1391
                    # the only index shows up as deleted by the set difference
1900
1392
                    # - which it may. Until there is a specific test for this,
1901
 
                    # assume its broken. RBC 20071017.
 
1393
                    # assume it's broken. RBC 20071017.
1902
1394
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
1903
1395
                    self._names[name] = sizes
1904
1396
                    self.get_pack_by_name(name)
1910
1402
                added.append(name)
1911
1403
        return removed, added, modified
1912
1404
 
1913
 
    def _save_pack_names(self, clear_obsolete_packs=False):
 
1405
    def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
1914
1406
        """Save the list of packs.
1915
1407
 
1916
1408
        This will take out the mutex around the pack names list for the
1920
1412
 
1921
1413
        :param clear_obsolete_packs: If True, clear out the contents of the
1922
1414
            obsolete_packs directory.
 
1415
        :param obsolete_packs: Packs that are obsolete once the new pack-names
 
1416
            file has been written.
 
1417
        :return: A list of the names saved that were not previously on disk.
1923
1418
        """
 
1419
        already_obsolete = []
1924
1420
        self.lock_names()
1925
1421
        try:
1926
1422
            builder = self._index_builder_class()
1927
 
            disk_nodes, deleted_nodes, new_nodes = self._diff_pack_names()
 
1423
            (disk_nodes, deleted_nodes, new_nodes,
 
1424
             orig_disk_nodes) = self._diff_pack_names()
1928
1425
            # TODO: handle same-name, index-size-changes here -
1929
1426
            # e.g. use the value from disk, not ours, *unless* we're the one
1930
1427
            # changing it.
1932
1429
                builder.add_node(key, value)
1933
1430
            self.transport.put_file('pack-names', builder.finish(),
1934
1431
                mode=self.repo.bzrdir._get_file_mode())
1935
 
            # move the baseline forward
1936
1432
            self._packs_at_load = disk_nodes
1937
1433
            if clear_obsolete_packs:
1938
 
                self._clear_obsolete_packs()
 
1434
                to_preserve = None
 
1435
                if obsolete_packs:
 
1436
                    to_preserve = set([o.name for o in obsolete_packs])
 
1437
                already_obsolete = self._clear_obsolete_packs(to_preserve)
1939
1438
        finally:
1940
1439
            self._unlock_names()
1941
1440
        # synchronise the memory packs list with what we just wrote:
1942
1441
        self._syncronize_pack_names_from_disk_nodes(disk_nodes)
 
1442
        if obsolete_packs:
 
1443
            # TODO: We could add one more condition here. "if o.name not in
 
1444
            #       orig_disk_nodes and o != the new_pack we haven't written to
 
1445
            #       disk yet. However, the new pack object is not easily
 
1446
            #       accessible here (it would have to be passed through the
 
1447
            #       autopacking code, etc.)
 
1448
            obsolete_packs = [o for o in obsolete_packs
 
1449
                              if o.name not in already_obsolete]
 
1450
            self._obsolete_packs(obsolete_packs)
 
1451
        return [new_node[0][0] for new_node in new_nodes]
1943
1452
 
1944
1453
    def reload_pack_names(self):
1945
1454
        """Sync our pack listing with what is present in the repository.
1952
1461
        """
1953
1462
        # The ensure_loaded call is to handle the case where the first call
1954
1463
        # made involving the collection was to reload_pack_names, where we 
1955
 
        # don't have a view of disk contents. Its a bit of a bandaid, and
1956
 
        # causes two reads of pack-names, but its a rare corner case not struck
1957
 
        # with regular push/pull etc.
 
1464
        # don't have a view of disk contents. It's a bit of a bandaid, and
 
1465
        # causes two reads of pack-names, but it's a rare corner case not
 
1466
        # struck with regular push/pull etc.
1958
1467
        first_read = self.ensure_loaded()
1959
1468
        if first_read:
1960
1469
            return True
1961
1470
        # out the new value.
1962
 
        disk_nodes, _, _ = self._diff_pack_names()
1963
 
        self._packs_at_load = disk_nodes
 
1471
        (disk_nodes, deleted_nodes, new_nodes,
 
1472
         orig_disk_nodes) = self._diff_pack_names()
 
1473
        # _packs_at_load is meant to be the explicit list of names in
 
1474
        # 'pack-names' at then start. As such, it should not contain any
 
1475
        # pending names that haven't been written out yet.
 
1476
        self._packs_at_load = orig_disk_nodes
1964
1477
        (removed, added,
1965
1478
         modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1966
1479
        if removed or added or modified:
1975
1488
            raise
1976
1489
        raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1977
1490
 
1978
 
    def _clear_obsolete_packs(self):
 
1491
    def _restart_pack_operations(self):
 
1492
        """Reload the pack names list, and restart the autopack code."""
 
1493
        if not self.reload_pack_names():
 
1494
            # Re-raise the original exception, because something went missing
 
1495
            # and a restart didn't find it
 
1496
            raise
 
1497
        raise RetryPackOperations(self.repo, False, sys.exc_info())
 
1498
 
 
1499
    def _clear_obsolete_packs(self, preserve=None):
1979
1500
        """Delete everything from the obsolete-packs directory.
 
1501
 
 
1502
        :return: A list of pack identifiers (the filename without '.pack') that
 
1503
            were found in obsolete_packs.
1980
1504
        """
 
1505
        found = []
1981
1506
        obsolete_pack_transport = self.transport.clone('obsolete_packs')
1982
 
        for filename in obsolete_pack_transport.list_dir('.'):
 
1507
        if preserve is None:
 
1508
            preserve = set()
 
1509
        try:
 
1510
            obsolete_pack_files = obsolete_pack_transport.list_dir('.')
 
1511
        except errors.NoSuchFile:
 
1512
            return found
 
1513
        for filename in obsolete_pack_files:
 
1514
            name, ext = osutils.splitext(filename)
 
1515
            if ext == '.pack':
 
1516
                found.append(name)
 
1517
            if name in preserve:
 
1518
                continue
1983
1519
            try:
1984
1520
                obsolete_pack_transport.delete(filename)
1985
1521
            except (errors.PathError, errors.TransportError), e:
1986
 
                warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
 
1522
                warning("couldn't delete obsolete pack, skipping it:\n%s"
 
1523
                        % (e,))
 
1524
        return found
1987
1525
 
1988
1526
    def _start_write_group(self):
1989
1527
        # Do not permit preparation for writing if we're not in a 'write lock'.
2016
1554
        # FIXME: just drop the transient index.
2017
1555
        # forget what names there are
2018
1556
        if self._new_pack is not None:
2019
 
            try:
2020
 
                self._new_pack.abort()
2021
 
            finally:
2022
 
                # XXX: If we aborted while in the middle of finishing the write
2023
 
                # group, _remove_pack_indices can fail because the indexes are
2024
 
                # already gone.  If they're not there we shouldn't fail in this
2025
 
                # case.  -- mbp 20081113
2026
 
                self._remove_pack_indices(self._new_pack)
2027
 
                self._new_pack = None
 
1557
            operation = cleanup.OperationWithCleanups(self._new_pack.abort)
 
1558
            operation.add_cleanup(setattr, self, '_new_pack', None)
 
1559
            # If we aborted while in the middle of finishing the write
 
1560
            # group, _remove_pack_indices could fail because the indexes are
 
1561
            # already gone.  But they're not there we shouldn't fail in this
 
1562
            # case, so we pass ignore_missing=True.
 
1563
            operation.add_cleanup(self._remove_pack_indices, self._new_pack,
 
1564
                ignore_missing=True)
 
1565
            operation.run_simple()
2028
1566
        for resumed_pack in self._resumed_packs:
2029
 
            try:
2030
 
                resumed_pack.abort()
2031
 
            finally:
2032
 
                # See comment in previous finally block.
2033
 
                try:
2034
 
                    self._remove_pack_indices(resumed_pack)
2035
 
                except KeyError:
2036
 
                    pass
 
1567
            operation = cleanup.OperationWithCleanups(resumed_pack.abort)
 
1568
            # See comment in previous finally block.
 
1569
            operation.add_cleanup(self._remove_pack_indices, resumed_pack,
 
1570
                ignore_missing=True)
 
1571
            operation.run_simple()
2037
1572
        del self._resumed_packs[:]
2038
 
        self.repo._text_knit = None
2039
1573
 
2040
1574
    def _remove_resumed_pack_indices(self):
2041
1575
        for resumed_pack in self._resumed_packs:
2042
1576
            self._remove_pack_indices(resumed_pack)
2043
1577
        del self._resumed_packs[:]
2044
1578
 
 
1579
    def _check_new_inventories(self):
 
1580
        """Detect missing inventories in this write group.
 
1581
 
 
1582
        :returns: list of strs, summarising any problems found.  If the list is
 
1583
            empty no problems were found.
 
1584
        """
 
1585
        # The base implementation does no checks.  GCRepositoryPackCollection
 
1586
        # overrides this.
 
1587
        return []
 
1588
        
2045
1589
    def _commit_write_group(self):
2046
1590
        all_missing = set()
2047
1591
        for prefix, versioned_file in (
2056
1600
            raise errors.BzrCheckError(
2057
1601
                "Repository %s has missing compression parent(s) %r "
2058
1602
                 % (self.repo, sorted(all_missing)))
 
1603
        problems = self._check_new_inventories()
 
1604
        if problems:
 
1605
            problems_summary = '\n'.join(problems)
 
1606
            raise errors.BzrCheckError(
 
1607
                "Cannot add revision(s) to repository: " + problems_summary)
2059
1608
        self._remove_pack_indices(self._new_pack)
2060
 
        should_autopack = False
 
1609
        any_new_content = False
2061
1610
        if self._new_pack.data_inserted():
2062
1611
            # get all the data to disk and read to use
2063
1612
            self._new_pack.finish()
2064
1613
            self.allocate(self._new_pack)
2065
1614
            self._new_pack = None
2066
 
            should_autopack = True
 
1615
            any_new_content = True
2067
1616
        else:
2068
1617
            self._new_pack.abort()
2069
1618
            self._new_pack = None
2074
1623
            self._remove_pack_from_memory(resumed_pack)
2075
1624
            resumed_pack.finish()
2076
1625
            self.allocate(resumed_pack)
2077
 
            should_autopack = True
 
1626
            any_new_content = True
2078
1627
        del self._resumed_packs[:]
2079
 
        if should_autopack:
2080
 
            if not self.autopack():
 
1628
        if any_new_content:
 
1629
            result = self.autopack()
 
1630
            if not result:
2081
1631
                # when autopack takes no steps, the names list is still
2082
1632
                # unsaved.
2083
 
                self._save_pack_names()
2084
 
        self.repo._text_knit = None
 
1633
                return self._save_pack_names()
 
1634
            return result
 
1635
        return []
2085
1636
 
2086
1637
    def _suspend_write_group(self):
2087
1638
        tokens = [pack.name for pack in self._resumed_packs]
2095
1646
            self._new_pack.abort()
2096
1647
            self._new_pack = None
2097
1648
        self._remove_resumed_pack_indices()
2098
 
        self.repo._text_knit = None
2099
1649
        return tokens
2100
1650
 
2101
1651
    def _resume_write_group(self, tokens):
2103
1653
            self._resume_pack(token)
2104
1654
 
2105
1655
 
2106
 
class KnitPackRepository(KnitRepository):
 
1656
class PackRepository(MetaDirVersionedFileRepository):
2107
1657
    """Repository with knit objects stored inside pack containers.
2108
1658
 
2109
1659
    The layering for a KnitPackRepository is:
2112
1662
    ===================================================
2113
1663
    Tuple based apis below, string based, and key based apis above
2114
1664
    ---------------------------------------------------
2115
 
    KnitVersionedFiles
 
1665
    VersionedFiles
2116
1666
      Provides .texts, .revisions etc
2117
1667
      This adapts the N-tuple keys to physical knit records which only have a
2118
1668
      single string identifier (for historical reasons), which in older formats
2128
1678
 
2129
1679
    """
2130
1680
 
 
1681
    # These attributes are inherited from the Repository base class. Setting
 
1682
    # them to None ensures that if the constructor is changed to not initialize
 
1683
    # them, or a subclass fails to call the constructor, that an error will
 
1684
    # occur rather than the system working but generating incorrect data.
 
1685
    _commit_builder_class = None
 
1686
    _serializer = None
 
1687
 
2131
1688
    def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2132
1689
        _serializer):
2133
 
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2134
 
            _commit_builder_class, _serializer)
2135
 
        index_transport = self._transport.clone('indices')
2136
 
        self._pack_collection = RepositoryPackCollection(self, self._transport,
2137
 
            index_transport,
2138
 
            self._transport.clone('upload'),
2139
 
            self._transport.clone('packs'),
2140
 
            _format.index_builder_class,
2141
 
            _format.index_class,
2142
 
            use_chk_index=self._format.supports_chks,
2143
 
            )
2144
 
        self.inventories = KnitVersionedFiles(
2145
 
            _KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2146
 
                add_callback=self._pack_collection.inventory_index.add_callback,
2147
 
                deltas=True, parents=True, is_locked=self.is_locked),
2148
 
            data_access=self._pack_collection.inventory_index.data_access,
2149
 
            max_delta_chain=200)
2150
 
        self.revisions = KnitVersionedFiles(
2151
 
            _KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2152
 
                add_callback=self._pack_collection.revision_index.add_callback,
2153
 
                deltas=False, parents=True, is_locked=self.is_locked),
2154
 
            data_access=self._pack_collection.revision_index.data_access,
2155
 
            max_delta_chain=0)
2156
 
        self.signatures = KnitVersionedFiles(
2157
 
            _KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2158
 
                add_callback=self._pack_collection.signature_index.add_callback,
2159
 
                deltas=False, parents=False, is_locked=self.is_locked),
2160
 
            data_access=self._pack_collection.signature_index.data_access,
2161
 
            max_delta_chain=0)
2162
 
        self.texts = KnitVersionedFiles(
2163
 
            _KnitGraphIndex(self._pack_collection.text_index.combined_index,
2164
 
                add_callback=self._pack_collection.text_index.add_callback,
2165
 
                deltas=True, parents=True, is_locked=self.is_locked),
2166
 
            data_access=self._pack_collection.text_index.data_access,
2167
 
            max_delta_chain=200)
2168
 
        if _format.supports_chks:
2169
 
            # No graph, no compression:- references from chks are between
2170
 
            # different objects not temporal versions of the same; and without
2171
 
            # some sort of temporal structure knit compression will just fail.
2172
 
            self.chk_bytes = KnitVersionedFiles(
2173
 
                _KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2174
 
                    add_callback=self._pack_collection.chk_index.add_callback,
2175
 
                    deltas=False, parents=False, is_locked=self.is_locked),
2176
 
                data_access=self._pack_collection.chk_index.data_access,
2177
 
                max_delta_chain=0)
2178
 
        else:
2179
 
            self.chk_bytes = None
2180
 
        # True when the repository object is 'write locked' (as opposed to the
2181
 
        # physical lock only taken out around changes to the pack-names list.)
2182
 
        # Another way to represent this would be a decorator around the control
2183
 
        # files object that presents logical locks as physical ones - if this
2184
 
        # gets ugly consider that alternative design. RBC 20071011
2185
 
        self._write_lock_count = 0
2186
 
        self._transaction = None
2187
 
        # for tests
2188
 
        self._reconcile_does_inventory_gc = True
 
1690
        MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
 
1691
        self._commit_builder_class = _commit_builder_class
 
1692
        self._serializer = _serializer
2189
1693
        self._reconcile_fixes_text_parents = True
2190
 
        self._reconcile_backsup_inventory = False
 
1694
        if self._format.supports_external_lookups:
 
1695
            self._unstacked_provider = graph.CachingParentsProvider(
 
1696
                self._make_parents_provider_unstacked())
 
1697
        else:
 
1698
            self._unstacked_provider = graph.CachingParentsProvider(self)
 
1699
        self._unstacked_provider.disable_cache()
2191
1700
 
2192
 
    def _warn_if_deprecated(self):
2193
 
        # This class isn't deprecated, but one sub-format is
2194
 
        if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2195
 
            from bzrlib import repository
2196
 
            if repository._deprecation_warning_done:
2197
 
                return
2198
 
            repository._deprecation_warning_done = True
2199
 
            warning("Format %s for %s is deprecated - please use"
2200
 
                    " 'bzr upgrade --1.6.1-rich-root'"
2201
 
                    % (self._format, self.bzrdir.transport.base))
 
1701
    @needs_read_lock
 
1702
    def _all_revision_ids(self):
 
1703
        """See Repository.all_revision_ids()."""
 
1704
        return [key[0] for key in self.revisions.keys()]
2202
1705
 
2203
1706
    def _abort_write_group(self):
 
1707
        self.revisions._index._key_dependencies.clear()
2204
1708
        self._pack_collection._abort_write_group()
2205
1709
 
2206
 
    def _find_inconsistent_revision_parents(self):
2207
 
        """Find revisions with incorrectly cached parents.
2208
 
 
2209
 
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
2210
 
            parents-in-revision).
2211
 
        """
2212
 
        if not self.is_locked():
2213
 
            raise errors.ObjectNotLocked(self)
2214
 
        pb = ui.ui_factory.nested_progress_bar()
2215
 
        result = []
2216
 
        try:
2217
 
            revision_nodes = self._pack_collection.revision_index \
2218
 
                .combined_index.iter_all_entries()
2219
 
            index_positions = []
2220
 
            # Get the cached index values for all revisions, and also the
2221
 
            # location in each index of the revision text so we can perform
2222
 
            # linear IO.
2223
 
            for index, key, value, refs in revision_nodes:
2224
 
                node = (index, key, value, refs)
2225
 
                index_memo = self.revisions._index._node_to_position(node)
2226
 
                if index_memo[0] != index:
2227
 
                    raise AssertionError('%r != %r' % (index_memo[0], index))
2228
 
                index_positions.append((index_memo, key[0],
2229
 
                                       tuple(parent[0] for parent in refs[0])))
2230
 
                pb.update("Reading revision index", 0, 0)
2231
 
            index_positions.sort()
2232
 
            batch_size = 1000
2233
 
            pb.update("Checking cached revision graph", 0,
2234
 
                      len(index_positions))
2235
 
            for offset in xrange(0, len(index_positions), 1000):
2236
 
                pb.update("Checking cached revision graph", offset)
2237
 
                to_query = index_positions[offset:offset + batch_size]
2238
 
                if not to_query:
2239
 
                    break
2240
 
                rev_ids = [item[1] for item in to_query]
2241
 
                revs = self.get_revisions(rev_ids)
2242
 
                for revision, item in zip(revs, to_query):
2243
 
                    index_parents = item[2]
2244
 
                    rev_parents = tuple(revision.parent_ids)
2245
 
                    if index_parents != rev_parents:
2246
 
                        result.append((revision.revision_id, index_parents,
2247
 
                                       rev_parents))
2248
 
        finally:
2249
 
            pb.finished()
2250
 
        return result
2251
 
 
2252
1710
    def _make_parents_provider(self):
2253
 
        return graph.CachingParentsProvider(self)
 
1711
        if not self._format.supports_external_lookups:
 
1712
            return self._unstacked_provider
 
1713
        return graph.StackedParentsProvider(_LazyListJoin(
 
1714
            [self._unstacked_provider], self._fallback_repositories))
2254
1715
 
2255
1716
    def _refresh_data(self):
2256
1717
        if not self.is_locked():
2257
1718
            return
2258
1719
        self._pack_collection.reload_pack_names()
 
1720
        self._unstacked_provider.disable_cache()
 
1721
        self._unstacked_provider.enable_cache()
2259
1722
 
2260
1723
    def _start_write_group(self):
2261
1724
        self._pack_collection._start_write_group()
2262
1725
 
2263
1726
    def _commit_write_group(self):
2264
 
        return self._pack_collection._commit_write_group()
 
1727
        hint = self._pack_collection._commit_write_group()
 
1728
        self.revisions._index._key_dependencies.clear()
 
1729
        # The commit may have added keys that were previously cached as
 
1730
        # missing, so reset the cache.
 
1731
        self._unstacked_provider.disable_cache()
 
1732
        self._unstacked_provider.enable_cache()
 
1733
        return hint
2265
1734
 
2266
1735
    def suspend_write_group(self):
2267
1736
        # XXX check self._write_group is self.get_transaction()?
2268
1737
        tokens = self._pack_collection._suspend_write_group()
 
1738
        self.revisions._index._key_dependencies.clear()
2269
1739
        self._write_group = None
2270
1740
        return tokens
2271
1741
 
2272
1742
    def _resume_write_group(self, tokens):
2273
1743
        self._start_write_group()
2274
 
        self._pack_collection._resume_write_group(tokens)
 
1744
        try:
 
1745
            self._pack_collection._resume_write_group(tokens)
 
1746
        except errors.UnresumableWriteGroup:
 
1747
            self._abort_write_group()
 
1748
            raise
 
1749
        for pack in self._pack_collection._resumed_packs:
 
1750
            self.revisions._index.scan_unvalidated_index(pack.revision_index)
2275
1751
 
2276
1752
    def get_transaction(self):
2277
1753
        if self._write_lock_count:
2286
1762
        return self._write_lock_count
2287
1763
 
2288
1764
    def lock_write(self, token=None):
 
1765
        """Lock the repository for writes.
 
1766
 
 
1767
        :return: A bzrlib.repository.RepositoryWriteLockResult.
 
1768
        """
2289
1769
        locked = self.is_locked()
2290
1770
        if not self._write_lock_count and locked:
2291
1771
            raise errors.ReadOnlyError(self)
2292
1772
        self._write_lock_count += 1
2293
1773
        if self._write_lock_count == 1:
2294
1774
            self._transaction = transactions.WriteTransaction()
 
1775
        if not locked:
 
1776
            if 'relock' in debug.debug_flags and self._prev_lock == 'w':
 
1777
                note('%r was write locked again', self)
 
1778
            self._prev_lock = 'w'
 
1779
            self._unstacked_provider.enable_cache()
2295
1780
            for repo in self._fallback_repositories:
2296
1781
                # Writes don't affect fallback repos
2297
1782
                repo.lock_read()
2298
 
        if not locked:
2299
1783
            self._refresh_data()
 
1784
        return RepositoryWriteLockResult(self.unlock, None)
2300
1785
 
2301
1786
    def lock_read(self):
 
1787
        """Lock the repository for reads.
 
1788
 
 
1789
        :return: A bzrlib.lock.LogicalLockResult.
 
1790
        """
2302
1791
        locked = self.is_locked()
2303
1792
        if self._write_lock_count:
2304
1793
            self._write_lock_count += 1
2305
1794
        else:
2306
1795
            self.control_files.lock_read()
 
1796
        if not locked:
 
1797
            if 'relock' in debug.debug_flags and self._prev_lock == 'r':
 
1798
                note('%r was read locked again', self)
 
1799
            self._prev_lock = 'r'
 
1800
            self._unstacked_provider.enable_cache()
2307
1801
            for repo in self._fallback_repositories:
2308
 
                # Writes don't affect fallback repos
2309
1802
                repo.lock_read()
2310
 
        if not locked:
2311
1803
            self._refresh_data()
 
1804
        return LogicalLockResult(self.unlock)
2312
1805
 
2313
1806
    def leave_lock_in_place(self):
2314
1807
        # not supported - raise an error
2319
1812
        raise NotImplementedError(self.dont_leave_lock_in_place)
2320
1813
 
2321
1814
    @needs_write_lock
2322
 
    def pack(self):
 
1815
    def pack(self, hint=None, clean_obsolete_packs=False):
2323
1816
        """Compress the data within the repository.
2324
1817
 
2325
1818
        This will pack all the data to a single pack. In future it may
2326
1819
        recompress deltas or do other such expensive operations.
2327
1820
        """
2328
 
        self._pack_collection.pack()
 
1821
        self._pack_collection.pack(hint=hint, clean_obsolete_packs=clean_obsolete_packs)
2329
1822
 
2330
1823
    @needs_write_lock
2331
1824
    def reconcile(self, other=None, thorough=False):
2336
1829
        return reconciler
2337
1830
 
2338
1831
    def _reconcile_pack(self, collection, packs, extension, revs, pb):
2339
 
        packer = ReconcilePacker(collection, packs, extension, revs)
2340
 
        return packer.pack(pb)
 
1832
        raise NotImplementedError(self._reconcile_pack)
2341
1833
 
 
1834
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2342
1835
    def unlock(self):
2343
1836
        if self._write_lock_count == 1 and self._write_group is not None:
2344
1837
            self.abort_write_group()
 
1838
            self._unstacked_provider.disable_cache()
2345
1839
            self._transaction = None
2346
1840
            self._write_lock_count = 0
2347
1841
            raise errors.BzrError(
2353
1847
                transaction = self._transaction
2354
1848
                self._transaction = None
2355
1849
                transaction.finish()
2356
 
                for repo in self._fallback_repositories:
2357
 
                    repo.unlock()
2358
1850
        else:
2359
1851
            self.control_files.unlock()
 
1852
 
 
1853
        if not self.is_locked():
 
1854
            self._unstacked_provider.disable_cache()
2360
1855
            for repo in self._fallback_repositories:
2361
1856
                repo.unlock()
2362
1857
 
2363
1858
 
2364
 
class RepositoryFormatPack(MetaDirRepositoryFormat):
 
1859
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
2365
1860
    """Format logic for pack structured repositories.
2366
1861
 
2367
1862
    This repository format has:
2397
1892
    index_class = None
2398
1893
    _fetch_uses_deltas = True
2399
1894
    fast_deltas = False
 
1895
    supports_funky_characters = True
 
1896
    revision_graph_can_have_wrong_parents = True
2400
1897
 
2401
1898
    def initialize(self, a_bzrdir, shared=False):
2402
1899
        """Create a pack based repository.
2413
1910
        utf8_files = [('format', self.get_format_string())]
2414
1911
 
2415
1912
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
2416
 
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1913
        repository = self.open(a_bzrdir=a_bzrdir, _found=True)
 
1914
        self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
 
1915
        return repository
2417
1916
 
2418
1917
    def open(self, a_bzrdir, _found=False, _override_transport=None):
2419
1918
        """See RepositoryFormat.open().
2423
1922
                                    than normal. I.e. during 'upgrade'.
2424
1923
        """
2425
1924
        if not _found:
2426
 
            format = RepositoryFormat.find_format(a_bzrdir)
 
1925
            format = RepositoryFormatMetaDir.find_format(a_bzrdir)
2427
1926
        if _override_transport is not None:
2428
1927
            repo_transport = _override_transport
2429
1928
        else:
2437
1936
                              _serializer=self._serializer)
2438
1937
 
2439
1938
 
2440
 
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2441
 
    """A no-subtrees parameterized Pack repository.
2442
 
 
2443
 
    This format was introduced in 0.92.
2444
 
    """
2445
 
 
2446
 
    repository_class = KnitPackRepository
2447
 
    _commit_builder_class = PackCommitBuilder
2448
 
    @property
2449
 
    def _serializer(self):
2450
 
        return xml5.serializer_v5
2451
 
    # What index classes to use
2452
 
    index_builder_class = InMemoryGraphIndex
2453
 
    index_class = GraphIndex
2454
 
 
2455
 
    def _get_matching_bzrdir(self):
2456
 
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2457
 
 
2458
 
    def _ignore_setting_bzrdir(self, format):
2459
 
        pass
2460
 
 
2461
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2462
 
 
2463
 
    def get_format_string(self):
2464
 
        """See RepositoryFormat.get_format_string()."""
2465
 
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2466
 
 
2467
 
    def get_format_description(self):
2468
 
        """See RepositoryFormat.get_format_description()."""
2469
 
        return "Packs containing knits without subtree support"
2470
 
 
2471
 
    def check_conversion_target(self, target_format):
2472
 
        pass
2473
 
 
2474
 
 
2475
 
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2476
 
    """A subtrees parameterized Pack repository.
2477
 
 
2478
 
    This repository format uses the xml7 serializer to get:
2479
 
     - support for recording full info about the tree root
2480
 
     - support for recording tree-references
2481
 
 
2482
 
    This format was introduced in 0.92.
2483
 
    """
2484
 
 
2485
 
    repository_class = KnitPackRepository
2486
 
    _commit_builder_class = PackRootCommitBuilder
2487
 
    rich_root_data = True
2488
 
    supports_tree_reference = True
2489
 
    @property
2490
 
    def _serializer(self):
2491
 
        return xml7.serializer_v7
2492
 
    # What index classes to use
2493
 
    index_builder_class = InMemoryGraphIndex
2494
 
    index_class = GraphIndex
2495
 
 
2496
 
    def _get_matching_bzrdir(self):
2497
 
        return bzrdir.format_registry.make_bzrdir(
2498
 
            'pack-0.92-subtree')
2499
 
 
2500
 
    def _ignore_setting_bzrdir(self, format):
2501
 
        pass
2502
 
 
2503
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2504
 
 
2505
 
    def check_conversion_target(self, target_format):
2506
 
        if not target_format.rich_root_data:
2507
 
            raise errors.BadConversionTarget(
2508
 
                'Does not support rich root data.', target_format)
2509
 
        if not getattr(target_format, 'supports_tree_reference', False):
2510
 
            raise errors.BadConversionTarget(
2511
 
                'Does not support nested trees', target_format)
2512
 
 
2513
 
    def get_format_string(self):
2514
 
        """See RepositoryFormat.get_format_string()."""
2515
 
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2516
 
 
2517
 
    def get_format_description(self):
2518
 
        """See RepositoryFormat.get_format_description()."""
2519
 
        return "Packs containing knits with subtree support\n"
2520
 
 
2521
 
 
2522
 
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2523
 
    """A rich-root, no subtrees parameterized Pack repository.
2524
 
 
2525
 
    This repository format uses the xml6 serializer to get:
2526
 
     - support for recording full info about the tree root
2527
 
 
2528
 
    This format was introduced in 1.0.
2529
 
    """
2530
 
 
2531
 
    repository_class = KnitPackRepository
2532
 
    _commit_builder_class = PackRootCommitBuilder
2533
 
    rich_root_data = True
2534
 
    supports_tree_reference = False
2535
 
    @property
2536
 
    def _serializer(self):
2537
 
        return xml6.serializer_v6
2538
 
    # What index classes to use
2539
 
    index_builder_class = InMemoryGraphIndex
2540
 
    index_class = GraphIndex
2541
 
 
2542
 
    def _get_matching_bzrdir(self):
2543
 
        return bzrdir.format_registry.make_bzrdir(
2544
 
            'rich-root-pack')
2545
 
 
2546
 
    def _ignore_setting_bzrdir(self, format):
2547
 
        pass
2548
 
 
2549
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2550
 
 
2551
 
    def check_conversion_target(self, target_format):
2552
 
        if not target_format.rich_root_data:
2553
 
            raise errors.BadConversionTarget(
2554
 
                'Does not support rich root data.', target_format)
2555
 
 
2556
 
    def get_format_string(self):
2557
 
        """See RepositoryFormat.get_format_string()."""
2558
 
        return ("Bazaar pack repository format 1 with rich root"
2559
 
                " (needs bzr 1.0)\n")
2560
 
 
2561
 
    def get_format_description(self):
2562
 
        """See RepositoryFormat.get_format_description()."""
2563
 
        return "Packs containing knits with rich root support\n"
2564
 
 
2565
 
 
2566
 
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2567
 
    """Repository that supports external references to allow stacking.
2568
 
 
2569
 
    New in release 1.6.
2570
 
 
2571
 
    Supports external lookups, which results in non-truncated ghosts after
2572
 
    reconcile compared to pack-0.92 formats.
2573
 
    """
2574
 
 
2575
 
    repository_class = KnitPackRepository
2576
 
    _commit_builder_class = PackCommitBuilder
2577
 
    supports_external_lookups = True
2578
 
    # What index classes to use
2579
 
    index_builder_class = InMemoryGraphIndex
2580
 
    index_class = GraphIndex
2581
 
 
2582
 
    @property
2583
 
    def _serializer(self):
2584
 
        return xml5.serializer_v5
2585
 
 
2586
 
    def _get_matching_bzrdir(self):
2587
 
        return bzrdir.format_registry.make_bzrdir('1.6')
2588
 
 
2589
 
    def _ignore_setting_bzrdir(self, format):
2590
 
        pass
2591
 
 
2592
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2593
 
 
2594
 
    def get_format_string(self):
2595
 
        """See RepositoryFormat.get_format_string()."""
2596
 
        return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2597
 
 
2598
 
    def get_format_description(self):
2599
 
        """See RepositoryFormat.get_format_description()."""
2600
 
        return "Packs 5 (adds stacking support, requires bzr 1.6)"
2601
 
 
2602
 
    def check_conversion_target(self, target_format):
2603
 
        pass
2604
 
 
2605
 
 
2606
 
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2607
 
    """A repository with rich roots and stacking.
2608
 
 
2609
 
    New in release 1.6.1.
2610
 
 
2611
 
    Supports stacking on other repositories, allowing data to be accessed
2612
 
    without being stored locally.
2613
 
    """
2614
 
 
2615
 
    repository_class = KnitPackRepository
2616
 
    _commit_builder_class = PackRootCommitBuilder
2617
 
    rich_root_data = True
2618
 
    supports_tree_reference = False # no subtrees
2619
 
    supports_external_lookups = True
2620
 
    # What index classes to use
2621
 
    index_builder_class = InMemoryGraphIndex
2622
 
    index_class = GraphIndex
2623
 
 
2624
 
    @property
2625
 
    def _serializer(self):
2626
 
        return xml6.serializer_v6
2627
 
 
2628
 
    def _get_matching_bzrdir(self):
2629
 
        return bzrdir.format_registry.make_bzrdir(
2630
 
            '1.6.1-rich-root')
2631
 
 
2632
 
    def _ignore_setting_bzrdir(self, format):
2633
 
        pass
2634
 
 
2635
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2636
 
 
2637
 
    def check_conversion_target(self, target_format):
2638
 
        if not target_format.rich_root_data:
2639
 
            raise errors.BadConversionTarget(
2640
 
                'Does not support rich root data.', target_format)
2641
 
 
2642
 
    def get_format_string(self):
2643
 
        """See RepositoryFormat.get_format_string()."""
2644
 
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2645
 
 
2646
 
    def get_format_description(self):
2647
 
        return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2648
 
 
2649
 
 
2650
 
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2651
 
    """A repository with rich roots and external references.
2652
 
 
2653
 
    New in release 1.6.
2654
 
 
2655
 
    Supports external lookups, which results in non-truncated ghosts after
2656
 
    reconcile compared to pack-0.92 formats.
2657
 
 
2658
 
    This format was deprecated because the serializer it uses accidentally
2659
 
    supported subtrees, when the format was not intended to. This meant that
2660
 
    someone could accidentally fetch from an incorrect repository.
2661
 
    """
2662
 
 
2663
 
    repository_class = KnitPackRepository
2664
 
    _commit_builder_class = PackRootCommitBuilder
2665
 
    rich_root_data = True
2666
 
    supports_tree_reference = False # no subtrees
2667
 
 
2668
 
    supports_external_lookups = True
2669
 
    # What index classes to use
2670
 
    index_builder_class = InMemoryGraphIndex
2671
 
    index_class = GraphIndex
2672
 
 
2673
 
    @property
2674
 
    def _serializer(self):
2675
 
        return xml7.serializer_v7
2676
 
 
2677
 
    def _get_matching_bzrdir(self):
2678
 
        matching = bzrdir.format_registry.make_bzrdir(
2679
 
            '1.6.1-rich-root')
2680
 
        matching.repository_format = self
2681
 
        return matching
2682
 
 
2683
 
    def _ignore_setting_bzrdir(self, format):
2684
 
        pass
2685
 
 
2686
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2687
 
 
2688
 
    def check_conversion_target(self, target_format):
2689
 
        if not target_format.rich_root_data:
2690
 
            raise errors.BadConversionTarget(
2691
 
                'Does not support rich root data.', target_format)
2692
 
 
2693
 
    def get_format_string(self):
2694
 
        """See RepositoryFormat.get_format_string()."""
2695
 
        return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2696
 
 
2697
 
    def get_format_description(self):
2698
 
        return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2699
 
                " (deprecated)")
2700
 
 
2701
 
 
2702
 
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2703
 
    """A repository with stacking and btree indexes,
2704
 
    without rich roots or subtrees.
2705
 
 
2706
 
    This is equivalent to pack-1.6 with B+Tree indices.
2707
 
    """
2708
 
 
2709
 
    repository_class = KnitPackRepository
2710
 
    _commit_builder_class = PackCommitBuilder
2711
 
    supports_external_lookups = True
2712
 
    # What index classes to use
2713
 
    index_builder_class = BTreeBuilder
2714
 
    index_class = BTreeGraphIndex
2715
 
 
2716
 
    @property
2717
 
    def _serializer(self):
2718
 
        return xml5.serializer_v5
2719
 
 
2720
 
    def _get_matching_bzrdir(self):
2721
 
        return bzrdir.format_registry.make_bzrdir('1.9')
2722
 
 
2723
 
    def _ignore_setting_bzrdir(self, format):
2724
 
        pass
2725
 
 
2726
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2727
 
 
2728
 
    def get_format_string(self):
2729
 
        """See RepositoryFormat.get_format_string()."""
2730
 
        return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2731
 
 
2732
 
    def get_format_description(self):
2733
 
        """See RepositoryFormat.get_format_description()."""
2734
 
        return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2735
 
 
2736
 
    def check_conversion_target(self, target_format):
2737
 
        pass
2738
 
 
2739
 
 
2740
 
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2741
 
    """A repository with rich roots, no subtrees, stacking and btree indexes.
2742
 
 
2743
 
    1.6-rich-root with B+Tree indices.
2744
 
    """
2745
 
 
2746
 
    repository_class = KnitPackRepository
2747
 
    _commit_builder_class = PackRootCommitBuilder
2748
 
    rich_root_data = True
2749
 
    supports_tree_reference = False # no subtrees
2750
 
    supports_external_lookups = True
2751
 
    # What index classes to use
2752
 
    index_builder_class = BTreeBuilder
2753
 
    index_class = BTreeGraphIndex
2754
 
 
2755
 
    @property
2756
 
    def _serializer(self):
2757
 
        return xml6.serializer_v6
2758
 
 
2759
 
    def _get_matching_bzrdir(self):
2760
 
        return bzrdir.format_registry.make_bzrdir(
2761
 
            '1.9-rich-root')
2762
 
 
2763
 
    def _ignore_setting_bzrdir(self, format):
2764
 
        pass
2765
 
 
2766
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2767
 
 
2768
 
    def check_conversion_target(self, target_format):
2769
 
        if not target_format.rich_root_data:
2770
 
            raise errors.BadConversionTarget(
2771
 
                'Does not support rich root data.', target_format)
2772
 
 
2773
 
    def get_format_string(self):
2774
 
        """See RepositoryFormat.get_format_string()."""
2775
 
        return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2776
 
 
2777
 
    def get_format_description(self):
2778
 
        return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2779
 
 
2780
 
 
2781
 
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2782
 
    """A subtrees development repository.
2783
 
 
2784
 
    This format should be retained until the second release after bzr 1.7.
2785
 
 
2786
 
    1.6.1-subtree[as it might have been] with B+Tree indices.
2787
 
 
2788
 
    This is [now] retained until we have a CHK based subtree format in
2789
 
    development.
2790
 
    """
2791
 
 
2792
 
    repository_class = KnitPackRepository
2793
 
    _commit_builder_class = PackRootCommitBuilder
2794
 
    rich_root_data = True
2795
 
    supports_tree_reference = True
2796
 
    supports_external_lookups = True
2797
 
    # What index classes to use
2798
 
    index_builder_class = BTreeBuilder
2799
 
    index_class = BTreeGraphIndex
2800
 
 
2801
 
    @property
2802
 
    def _serializer(self):
2803
 
        return xml7.serializer_v7
2804
 
 
2805
 
    def _get_matching_bzrdir(self):
2806
 
        return bzrdir.format_registry.make_bzrdir(
2807
 
            'development-subtree')
2808
 
 
2809
 
    def _ignore_setting_bzrdir(self, format):
2810
 
        pass
2811
 
 
2812
 
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2813
 
 
2814
 
    def check_conversion_target(self, target_format):
2815
 
        if not target_format.rich_root_data:
2816
 
            raise errors.BadConversionTarget(
2817
 
                'Does not support rich root data.', target_format)
2818
 
        if not getattr(target_format, 'supports_tree_reference', False):
2819
 
            raise errors.BadConversionTarget(
2820
 
                'Does not support nested trees', target_format)
2821
 
 
2822
 
    def get_format_string(self):
2823
 
        """See RepositoryFormat.get_format_string()."""
2824
 
        return ("Bazaar development format 2 with subtree support "
2825
 
            "(needs bzr.dev from before 1.8)\n")
2826
 
 
2827
 
    def get_format_description(self):
2828
 
        """See RepositoryFormat.get_format_description()."""
2829
 
        return ("Development repository format, currently the same as "
2830
 
            "1.6.1-subtree with B+Tree indices.\n")
 
1939
class RetryPackOperations(errors.RetryWithNewPacks):
 
1940
    """Raised when we are packing and we find a missing file.
 
1941
 
 
1942
    Meant as a signaling exception, to tell the RepositoryPackCollection.pack
 
1943
    code it should try again.
 
1944
    """
 
1945
 
 
1946
    internal_error = True
 
1947
 
 
1948
    _fmt = ("Pack files have changed, reload and try pack again."
 
1949
            " context: %(context)s %(orig_error)s")
 
1950
 
 
1951
 
 
1952
class _DirectPackAccess(object):
 
1953
    """Access to data in one or more packs with less translation."""
 
1954
 
 
1955
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
 
1956
        """Create a _DirectPackAccess object.
 
1957
 
 
1958
        :param index_to_packs: A dict mapping index objects to the transport
 
1959
            and file names for obtaining data.
 
1960
        :param reload_func: A function to call if we determine that the pack
 
1961
            files have moved and we need to reload our caches. See
 
1962
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
 
1963
        """
 
1964
        self._container_writer = None
 
1965
        self._write_index = None
 
1966
        self._indices = index_to_packs
 
1967
        self._reload_func = reload_func
 
1968
        self._flush_func = flush_func
 
1969
 
 
1970
    def add_raw_records(self, key_sizes, raw_data):
 
1971
        """Add raw knit bytes to a storage area.
 
1972
 
 
1973
        The data is spooled to the container writer in one bytes-record per
 
1974
        raw data item.
 
1975
 
 
1976
        :param sizes: An iterable of tuples containing the key and size of each
 
1977
            raw data segment.
 
1978
        :param raw_data: A bytestring containing the data.
 
1979
        :return: A list of memos to retrieve the record later. Each memo is an
 
1980
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
 
1981
            length), where the index field is the write_index object supplied
 
1982
            to the PackAccess object.
 
1983
        """
 
1984
        if type(raw_data) is not str:
 
1985
            raise AssertionError(
 
1986
                'data must be plain bytes was %s' % type(raw_data))
 
1987
        result = []
 
1988
        offset = 0
 
1989
        for key, size in key_sizes:
 
1990
            p_offset, p_length = self._container_writer.add_bytes_record(
 
1991
                raw_data[offset:offset+size], [])
 
1992
            offset += size
 
1993
            result.append((self._write_index, p_offset, p_length))
 
1994
        return result
 
1995
 
 
1996
    def flush(self):
 
1997
        """Flush pending writes on this access object.
 
1998
 
 
1999
        This will flush any buffered writes to a NewPack.
 
2000
        """
 
2001
        if self._flush_func is not None:
 
2002
            self._flush_func()
 
2003
 
 
2004
    def get_raw_records(self, memos_for_retrieval):
 
2005
        """Get the raw bytes for a records.
 
2006
 
 
2007
        :param memos_for_retrieval: An iterable containing the (index, pos,
 
2008
            length) memo for retrieving the bytes. The Pack access method
 
2009
            looks up the pack to use for a given record in its index_to_pack
 
2010
            map.
 
2011
        :return: An iterator over the bytes of the records.
 
2012
        """
 
2013
        # first pass, group into same-index requests
 
2014
        request_lists = []
 
2015
        current_index = None
 
2016
        for (index, offset, length) in memos_for_retrieval:
 
2017
            if current_index == index:
 
2018
                current_list.append((offset, length))
 
2019
            else:
 
2020
                if current_index is not None:
 
2021
                    request_lists.append((current_index, current_list))
 
2022
                current_index = index
 
2023
                current_list = [(offset, length)]
 
2024
        # handle the last entry
 
2025
        if current_index is not None:
 
2026
            request_lists.append((current_index, current_list))
 
2027
        for index, offsets in request_lists:
 
2028
            try:
 
2029
                transport, path = self._indices[index]
 
2030
            except KeyError:
 
2031
                # A KeyError here indicates that someone has triggered an index
 
2032
                # reload, and this index has gone missing, we need to start
 
2033
                # over.
 
2034
                if self._reload_func is None:
 
2035
                    # If we don't have a _reload_func there is nothing that can
 
2036
                    # be done
 
2037
                    raise
 
2038
                raise errors.RetryWithNewPacks(index,
 
2039
                                               reload_occurred=True,
 
2040
                                               exc_info=sys.exc_info())
 
2041
            try:
 
2042
                reader = pack.make_readv_reader(transport, path, offsets)
 
2043
                for names, read_func in reader.iter_records():
 
2044
                    yield read_func(None)
 
2045
            except errors.NoSuchFile:
 
2046
                # A NoSuchFile error indicates that a pack file has gone
 
2047
                # missing on disk, we need to trigger a reload, and start over.
 
2048
                if self._reload_func is None:
 
2049
                    raise
 
2050
                raise errors.RetryWithNewPacks(transport.abspath(path),
 
2051
                                               reload_occurred=False,
 
2052
                                               exc_info=sys.exc_info())
 
2053
 
 
2054
    def set_writer(self, writer, index, transport_packname):
 
2055
        """Set a writer to use for adding data."""
 
2056
        if index is not None:
 
2057
            self._indices[index] = transport_packname
 
2058
        self._container_writer = writer
 
2059
        self._write_index = index
 
2060
 
 
2061
    def reload_or_raise(self, retry_exc):
 
2062
        """Try calling the reload function, or re-raise the original exception.
 
2063
 
 
2064
        This should be called after _DirectPackAccess raises a
 
2065
        RetryWithNewPacks exception. This function will handle the common logic
 
2066
        of determining when the error is fatal versus being temporary.
 
2067
        It will also make sure that the original exception is raised, rather
 
2068
        than the RetryWithNewPacks exception.
 
2069
 
 
2070
        If this function returns, then the calling function should retry
 
2071
        whatever operation was being performed. Otherwise an exception will
 
2072
        be raised.
 
2073
 
 
2074
        :param retry_exc: A RetryWithNewPacks exception.
 
2075
        """
 
2076
        is_error = False
 
2077
        if self._reload_func is None:
 
2078
            is_error = True
 
2079
        elif not self._reload_func():
 
2080
            # The reload claimed that nothing changed
 
2081
            if not retry_exc.reload_occurred:
 
2082
                # If there wasn't an earlier reload, then we really were
 
2083
                # expecting to find changes. We didn't find them, so this is a
 
2084
                # hard error
 
2085
                is_error = True
 
2086
        if is_error:
 
2087
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
 
2088
            raise exc_class, exc_value, exc_traceback
 
2089
 
 
2090
 
2831
2091