13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
17
from bzrlib.lazy_import import lazy_import
21
18
lazy_import(globals(), """
22
19
from itertools import izip
25
24
from bzrlib import (
37
30
from bzrlib.index import (
38
34
CombinedGraphIndex,
39
35
GraphIndexPrefixAdapter,
37
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
38
from bzrlib.osutils import rand_chars
39
from bzrlib.pack import ContainerWriter
40
from bzrlib.store import revision
41
from bzrlib import tsort
42
43
from bzrlib import (
49
from bzrlib.decorators import (
54
from bzrlib.lock import LogicalLockResult
58
from bzrlib.decorators import needs_read_lock, needs_write_lock
59
from bzrlib.repofmt.knitrepo import KnitRepository
55
60
from bzrlib.repository import (
59
RepositoryWriteLockResult,
61
from bzrlib.vf_repository import (
62
MetaDirVersionedFileRepository,
63
MetaDirVersionedFileRepositoryFormat,
64
VersionedFileCommitBuilder,
65
VersionedFileRootCommitBuilder,
67
from bzrlib.trace import (
74
class PackCommitBuilder(VersionedFileCommitBuilder):
75
"""Subclass of VersionedFileCommitBuilder to add texts with pack semantics.
63
MetaDirRepositoryFormat,
66
import bzrlib.revision as _mod_revision
67
from bzrlib.store.revision.knit import KnitRevisionStore
68
from bzrlib.store.versioned import VersionedFileStore
69
from bzrlib.trace import mutter, note, warning
72
class PackCommitBuilder(CommitBuilder):
73
"""A subclass of CommitBuilder to add texts with pack semantics.
77
75
Specifically this uses one knit object rather than one knit object per
78
76
added text, reducing memory and object pressure.
81
79
def __init__(self, repository, parents, config, timestamp=None,
82
80
timezone=None, committer=None, revprops=None,
83
revision_id=None, lossy=False):
84
VersionedFileCommitBuilder.__init__(self, repository, parents, config,
82
CommitBuilder.__init__(self, repository, parents, config,
85
83
timestamp=timestamp, timezone=timezone, committer=committer,
86
revprops=revprops, revision_id=revision_id, lossy=lossy)
84
revprops=revprops, revision_id=revision_id)
87
85
self._file_graph = graph.Graph(
88
86
repository._pack_collection.text_index.combined_index)
88
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
89
return self.repository._pack_collection._add_text_to_weave(file_id,
90
self._new_revision_id, new_lines, parents, nostore_sha,
90
93
def _heads(self, file_id, revision_ids):
91
94
keys = [(file_id, revision_id) for revision_id in revision_ids]
92
95
return set([key[1] for key in self._file_graph.heads(keys)])
95
class PackRootCommitBuilder(VersionedFileRootCommitBuilder):
98
class PackRootCommitBuilder(RootCommitBuilder):
96
99
"""A subclass of RootCommitBuilder to add texts with pack semantics.
98
101
Specifically this uses one knit object rather than one knit object per
99
102
added text, reducing memory and object pressure.
102
105
def __init__(self, repository, parents, config, timestamp=None,
103
106
timezone=None, committer=None, revprops=None,
104
revision_id=None, lossy=False):
105
super(PackRootCommitBuilder, self).__init__(repository, parents,
106
config, timestamp=timestamp, timezone=timezone,
107
committer=committer, revprops=revprops, revision_id=revision_id,
108
CommitBuilder.__init__(self, repository, parents, config,
109
timestamp=timestamp, timezone=timezone, committer=committer,
110
revprops=revprops, revision_id=revision_id)
109
111
self._file_graph = graph.Graph(
110
112
repository._pack_collection.text_index.combined_index)
114
def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
115
return self.repository._pack_collection._add_text_to_weave(file_id,
116
self._new_revision_id, new_lines, parents, nostore_sha,
112
119
def _heads(self, file_id, revision_ids):
113
120
keys = [(file_id, revision_id) for revision_id in revision_ids]
114
121
return set([key[1] for key in self._file_graph.heads(keys)])
256
208
return not self.__eq__(other)
258
210
def __repr__(self):
259
return "<%s.%s object at 0x%x, %s, %s" % (
260
self.__class__.__module__, self.__class__.__name__, id(self),
261
self.pack_transport, self.name)
264
class ResumedPack(ExistingPack):
266
def __init__(self, name, revision_index, inventory_index, text_index,
267
signature_index, upload_transport, pack_transport, index_transport,
268
pack_collection, chk_index=None):
269
"""Create a ResumedPack object."""
270
ExistingPack.__init__(self, pack_transport, name, revision_index,
271
inventory_index, text_index, signature_index,
273
self.upload_transport = upload_transport
274
self.index_transport = index_transport
275
self.index_sizes = [None, None, None, None]
277
('revision', revision_index),
278
('inventory', inventory_index),
279
('text', text_index),
280
('signature', signature_index),
282
if chk_index is not None:
283
indices.append(('chk', chk_index))
284
self.index_sizes.append(None)
285
for index_type, index in indices:
286
offset = self.index_offset(index_type)
287
self.index_sizes[offset] = index._size
288
self.index_class = pack_collection._index_class
289
self._pack_collection = pack_collection
290
self._state = 'resumed'
291
# XXX: perhaps check that the .pack file exists?
293
def access_tuple(self):
294
if self._state == 'finished':
295
return Pack.access_tuple(self)
296
elif self._state == 'resumed':
297
return self.upload_transport, self.file_name()
299
raise AssertionError(self._state)
302
self.upload_transport.delete(self.file_name())
303
indices = [self.revision_index, self.inventory_index, self.text_index,
304
self.signature_index]
305
if self.chk_index is not None:
306
indices.append(self.chk_index)
307
for index in indices:
308
index._transport.delete(index._name)
311
self._check_references()
312
index_types = ['revision', 'inventory', 'text', 'signature']
313
if self.chk_index is not None:
314
index_types.append('chk')
315
for index_type in index_types:
316
old_name = self.index_name(index_type, self.name)
317
new_name = '../indices/' + old_name
318
self.upload_transport.move(old_name, new_name)
319
self._replace_index_with_readonly(index_type)
320
new_name = '../packs/' + self.file_name()
321
self.upload_transport.move(self.file_name(), new_name)
322
self._state = 'finished'
324
def _get_external_refs(self, index):
325
"""Return compression parents for this index that are not present.
327
This returns any compression parents that are referenced by this index,
328
which are not contained *in* this index. They may be present elsewhere.
330
return index.external_references(1)
211
return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
212
id(self), self.transport, self.name)
333
215
class NewPack(Pack):
334
216
"""An in memory proxy for a pack which is being created."""
336
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
218
# A map of index 'type' to the file extension and position in the
220
index_definitions = {
221
'revision': ('.rix', 0),
222
'inventory': ('.iix', 1),
224
'signature': ('.six', 3),
227
def __init__(self, upload_transport, index_transport, pack_transport,
228
upload_suffix='', file_mode=None):
337
229
"""Create a NewPack instance.
339
:param pack_collection: A PackCollection into which this is being inserted.
231
:param upload_transport: A writable transport for the pack to be
232
incrementally uploaded to.
233
:param index_transport: A writable transport for the pack's indices to
234
be written to when the pack is finished.
235
:param pack_transport: A writable transport for the pack to be renamed
236
to when the upload is complete. This *must* be the same as
237
upload_transport.clone('../packs').
340
238
:param upload_suffix: An optional suffix to be given to any temporary
341
239
files created during the pack creation. e.g '.autopack'
342
:param file_mode: Unix permissions for newly created file.
240
:param file_mode: An optional file mode to create the new files with.
344
242
# The relative locations of the packs are constrained, but all are
345
243
# passed in because the caller has them, so as to avoid object churn.
346
index_builder_class = pack_collection._index_builder_class
347
if pack_collection.chk_index is not None:
348
chk_index = index_builder_class(reference_lists=0)
351
244
Pack.__init__(self,
352
245
# Revisions: parents list, no text compression.
353
index_builder_class(reference_lists=1),
246
InMemoryGraphIndex(reference_lists=1),
354
247
# Inventory: We want to map compression only, but currently the
355
248
# knit code hasn't been updated enough to understand that, so we
356
249
# have a regular 2-list index giving parents and compression
358
index_builder_class(reference_lists=2),
251
InMemoryGraphIndex(reference_lists=2),
359
252
# Texts: compression and per file graph, for all fileids - so two
360
253
# reference lists and two elements in the key tuple.
361
index_builder_class(reference_lists=2, key_elements=2),
254
InMemoryGraphIndex(reference_lists=2, key_elements=2),
362
255
# Signatures: Just blobs to store, no compression, no parents
364
index_builder_class(reference_lists=0),
365
# CHK based storage - just blobs, no compression or parents.
257
InMemoryGraphIndex(reference_lists=0),
368
self._pack_collection = pack_collection
369
# When we make readonly indices, we need this.
370
self.index_class = pack_collection._index_class
371
259
# where should the new pack be opened
372
self.upload_transport = pack_collection._upload_transport
260
self.upload_transport = upload_transport
373
261
# where are indices written out to
374
self.index_transport = pack_collection._index_transport
262
self.index_transport = index_transport
375
263
# where is the pack renamed to when it is finished?
376
self.pack_transport = pack_collection._pack_transport
264
self.pack_transport = pack_transport
377
265
# What file mode to upload the pack and indices with.
378
266
self._file_mode = file_mode
379
267
# tracks the content written to the .pack file.
380
self._hash = osutils.md5()
381
# a tuple with the length in bytes of the indices, once the pack
382
# is finalised. (rev, inv, text, sigs, chk_if_in_use)
268
self._hash = md5.new()
269
# a four-tuple with the length in bytes of the indices, once the pack
270
# is finalised. (rev, inv, text, sigs)
383
271
self.index_sizes = None
384
272
# How much data to cache when writing packs. Note that this is not
385
273
# synchronised with reads, because it's not in the transport layer, so
741
630
Sets self._text_filter appropriately.
743
raise NotImplementedError(self._copy_inventory_texts)
632
# select inventory keys
633
inv_keys = self._revision_keys # currently the same keyspace, and note that
634
# querying for keys here could introduce a bug where an inventory item
635
# is missed, so do not change it to query separately without cross
636
# checking like the text key check below.
637
inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
638
self.packs, 'inventory_index')[0]
639
inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
640
# copy inventory keys and adjust values
641
# XXX: Should be a helper function to allow different inv representation
643
self.pb.update("Copying inventory texts", 2)
644
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
645
# Only grab the output lines if we will be processing them
646
output_lines = bool(self.revision_ids)
647
inv_lines = self._copy_nodes_graph(inventory_index_map,
648
self.new_pack._writer, self.new_pack.inventory_index,
649
readv_group_iter, total_items, output_lines=output_lines)
650
if self.revision_ids:
651
self._process_inventory_lines(inv_lines)
653
# eat the iterator to cause it to execute.
655
self._text_filter = None
656
if 'pack' in debug.debug_flags:
657
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
658
time.ctime(), self._pack_collection._upload_transport.base,
659
self.new_pack.random_name,
660
self.new_pack.inventory_index.key_count(),
661
time.time() - self.new_pack.start_time)
745
663
def _copy_text_texts(self):
746
raise NotImplementedError(self._copy_text_texts)
665
text_index_map, text_nodes = self._get_text_nodes()
666
if self._text_filter is not None:
667
# We could return the keys copied as part of the return value from
668
# _copy_nodes_graph but this doesn't work all that well with the
669
# need to get line output too, so we check separately, and as we're
670
# going to buffer everything anyway, we check beforehand, which
671
# saves reading knit data over the wire when we know there are
673
text_nodes = set(text_nodes)
674
present_text_keys = set(_node[1] for _node in text_nodes)
675
missing_text_keys = set(self._text_filter) - present_text_keys
676
if missing_text_keys:
677
# TODO: raise a specific error that can handle many missing
679
a_missing_key = missing_text_keys.pop()
680
raise errors.RevisionNotPresent(a_missing_key[1],
682
# copy text keys and adjust values
683
self.pb.update("Copying content texts", 3)
684
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
685
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
686
self.new_pack.text_index, readv_group_iter, total_items))
687
self._log_copied_texts()
689
def _check_references(self):
690
"""Make sure our external refereneces are present."""
691
external_refs = self.new_pack._external_compression_parents_of_texts()
693
index = self._pack_collection.text_index.combined_index
694
found_items = list(index.iter_entries(external_refs))
695
if len(found_items) != len(external_refs):
696
found_keys = set(k for idx, k, refs, value in found_items)
697
missing_items = external_refs - found_keys
698
missing_file_id, missing_revision_id = missing_items.pop()
699
raise errors.RevisionNotPresent(missing_revision_id,
748
702
def _create_pack_from_packs(self):
749
raise NotImplementedError(self._create_pack_from_packs)
703
self.pb.update("Opening pack", 0, 5)
704
self.new_pack = self.open_pack()
705
new_pack = self.new_pack
706
# buffer data - we won't be reading-back during the pack creation and
707
# this makes a significant difference on sftp pushes.
708
new_pack.set_write_cache_size(1024*1024)
709
if 'pack' in debug.debug_flags:
710
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
711
for a_pack in self.packs]
712
if self.revision_ids is not None:
713
rev_count = len(self.revision_ids)
716
mutter('%s: create_pack: creating pack from source packs: '
717
'%s%s %s revisions wanted %s t=0',
718
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
719
plain_pack_list, rev_count)
720
self._copy_revision_texts()
721
self._copy_inventory_texts()
722
self._copy_text_texts()
723
# select signature keys
724
signature_filter = self._revision_keys # same keyspace
725
signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
726
self.packs, 'signature_index')[0]
727
signature_nodes = self._pack_collection._index_contents(signature_index_map,
729
# copy signature keys and adjust values
730
self.pb.update("Copying signature texts", 4)
731
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
732
new_pack.signature_index)
733
if 'pack' in debug.debug_flags:
734
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
735
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
736
new_pack.signature_index.key_count(),
737
time.time() - new_pack.start_time)
738
self._check_references()
739
if not self._use_pack(new_pack):
742
self.pb.update("Finishing pack", 5)
744
self._pack_collection.allocate(new_pack)
747
def _copy_nodes(self, nodes, index_map, writer, write_index):
748
"""Copy knit nodes between packs with no graph references."""
749
pb = ui.ui_factory.nested_progress_bar()
751
return self._do_copy_nodes(nodes, index_map, writer,
756
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
757
# for record verification
758
knit_data = _KnitData(None)
759
# plan a readv on each source pack:
761
nodes = sorted(nodes)
762
# how to map this into knit.py - or knit.py into this?
763
# we don't want the typical knit logic, we want grouping by pack
764
# at this point - perhaps a helper library for the following code
765
# duplication points?
767
for index, key, value in nodes:
768
if index not in request_groups:
769
request_groups[index] = []
770
request_groups[index].append((key, value))
772
pb.update("Copied record", record_index, len(nodes))
773
for index, items in request_groups.iteritems():
774
pack_readv_requests = []
775
for key, value in items:
776
# ---- KnitGraphIndex.get_position
777
bits = value[1:].split(' ')
778
offset, length = int(bits[0]), int(bits[1])
779
pack_readv_requests.append((offset, length, (key, value[0])))
780
# linear scan up the pack
781
pack_readv_requests.sort()
783
transport, path = index_map[index]
784
reader = pack.make_readv_reader(transport, path,
785
[offset[0:2] for offset in pack_readv_requests])
786
for (names, read_func), (_1, _2, (key, eol_flag)) in \
787
izip(reader.iter_records(), pack_readv_requests):
788
raw_data = read_func(None)
789
# check the header only
790
df, _ = knit_data._parse_record_header(key[-1], raw_data)
792
pos, size = writer.add_bytes_record(raw_data, names)
793
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
794
pb.update("Copied record", record_index)
797
def _copy_nodes_graph(self, index_map, writer, write_index,
798
readv_group_iter, total_items, output_lines=False):
799
"""Copy knit nodes between packs.
801
:param output_lines: Return lines present in the copied data as
802
an iterator of line,version_id.
804
pb = ui.ui_factory.nested_progress_bar()
806
for result in self._do_copy_nodes_graph(index_map, writer,
807
write_index, output_lines, pb, readv_group_iter, total_items):
810
# Python 2.4 does not permit try:finally: in a generator.
816
def _do_copy_nodes_graph(self, index_map, writer, write_index,
817
output_lines, pb, readv_group_iter, total_items):
818
# for record verification
819
knit_data = _KnitData(None)
820
# for line extraction when requested (inventories only)
822
factory = knit.KnitPlainFactory()
824
pb.update("Copied record", record_index, total_items)
825
for index, readv_vector, node_vector in readv_group_iter:
827
transport, path = index_map[index]
828
reader = pack.make_readv_reader(transport, path, readv_vector)
829
for (names, read_func), (key, eol_flag, references) in \
830
izip(reader.iter_records(), node_vector):
831
raw_data = read_func(None)
834
# read the entire thing
835
content, _ = knit_data._parse_record(version_id, raw_data)
836
if len(references[-1]) == 0:
837
line_iterator = factory.get_fulltext_content(content)
839
line_iterator = factory.get_linedelta_content(content)
840
for line in line_iterator:
841
yield line, version_id
843
# check the header only
844
df, _ = knit_data._parse_record_header(version_id, raw_data)
846
pos, size = writer.add_bytes_record(raw_data, names)
847
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
848
pb.update("Copied record", record_index)
851
def _get_text_nodes(self):
852
text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
853
self.packs, 'text_index')[0]
854
return text_index_map, self._pack_collection._index_contents(text_index_map,
857
def _least_readv_node_readv(self, nodes):
858
"""Generate request groups for nodes using the least readv's.
860
:param nodes: An iterable of graph index nodes.
861
:return: Total node count and an iterator of the data needed to perform
862
readvs to obtain the data for nodes. Each item yielded by the
863
iterator is a tuple with:
864
index, readv_vector, node_vector. readv_vector is a list ready to
865
hand to the transport readv method, and node_vector is a list of
866
(key, eol_flag, references) for the the node retrieved by the
867
matching readv_vector.
869
# group by pack so we do one readv per pack
870
nodes = sorted(nodes)
873
for index, key, value, references in nodes:
874
if index not in request_groups:
875
request_groups[index] = []
876
request_groups[index].append((key, value, references))
878
for index, items in request_groups.iteritems():
879
pack_readv_requests = []
880
for key, value, references in items:
881
# ---- KnitGraphIndex.get_position
882
bits = value[1:].split(' ')
883
offset, length = int(bits[0]), int(bits[1])
884
pack_readv_requests.append(
885
((offset, length), (key, value[0], references)))
886
# linear scan up the pack to maximum range combining.
887
pack_readv_requests.sort()
888
# split out the readv and the node data.
889
pack_readv = [readv for readv, node in pack_readv_requests]
890
node_vector = [node for readv, node in pack_readv_requests]
891
result.append((index, pack_readv, node_vector))
751
894
def _log_copied_texts(self):
752
895
if 'pack' in debug.debug_flags:
765
927
return new_pack.data_inserted()
930
class OptimisingPacker(Packer):
931
"""A packer which spends more time to create better disk layouts."""
933
def _revision_node_readv(self, revision_nodes):
934
"""Return the total revisions and the readv's to issue.
936
This sort places revisions in topological order with the ancestors
939
:param revision_nodes: The revision index contents for the packs being
940
incorporated into the new pack.
941
:return: As per _least_readv_node_readv.
943
# build an ancestors dict
946
for index, key, value, references in revision_nodes:
947
ancestors[key] = references[0]
948
by_key[key] = (index, value, references)
949
order = tsort.topo_sort(ancestors)
951
# Single IO is pathological, but it will work as a starting point.
953
for key in reversed(order):
954
index, value, references = by_key[key]
955
# ---- KnitGraphIndex.get_position
956
bits = value[1:].split(' ')
957
offset, length = int(bits[0]), int(bits[1])
959
(index, [(offset, length)], [(key, value[0], references)]))
960
# TODO: combine requests in the same index that are in ascending order.
961
return total, requests
964
class ReconcilePacker(Packer):
965
"""A packer which regenerates indices etc as it copies.
967
This is used by ``bzr reconcile`` to cause parent text pointers to be
971
def _extra_init(self):
972
self._data_changed = False
974
def _process_inventory_lines(self, inv_lines):
975
"""Generate a text key reference map rather for reconciling with."""
976
repo = self._pack_collection.repo
977
refs = repo._find_text_key_references_from_xml_inventory_lines(
979
self._text_refs = refs
980
# during reconcile we:
981
# - convert unreferenced texts to full texts
982
# - correct texts which reference a text not copied to be full texts
983
# - copy all others as-is but with corrected parents.
984
# - so at this point we don't know enough to decide what becomes a full
986
self._text_filter = None
988
def _copy_text_texts(self):
989
"""generate what texts we should have and then copy."""
990
self.pb.update("Copying content texts", 3)
991
# we have three major tasks here:
992
# 1) generate the ideal index
993
repo = self._pack_collection.repo
994
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
996
self.new_pack.revision_index.iter_all_entries()])
997
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
998
# 2) generate a text_nodes list that contains all the deltas that can
999
# be used as-is, with corrected parents.
1002
discarded_nodes = []
1003
NULL_REVISION = _mod_revision.NULL_REVISION
1004
text_index_map, text_nodes = self._get_text_nodes()
1005
for node in text_nodes:
1011
ideal_parents = tuple(ideal_index[node[1]])
1013
discarded_nodes.append(node)
1014
self._data_changed = True
1016
if ideal_parents == (NULL_REVISION,):
1018
if ideal_parents == node[3][0]:
1020
ok_nodes.append(node)
1021
elif ideal_parents[0:1] == node[3][0][0:1]:
1022
# the left most parent is the same, or there are no parents
1023
# today. Either way, we can preserve the representation as
1024
# long as we change the refs to be inserted.
1025
self._data_changed = True
1026
ok_nodes.append((node[0], node[1], node[2],
1027
(ideal_parents, node[3][1])))
1028
self._data_changed = True
1030
# Reinsert this text completely
1031
bad_texts.append((node[1], ideal_parents))
1032
self._data_changed = True
1033
# we're finished with some data.
1036
# 3) bulk copy the ok data
1037
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1038
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1039
self.new_pack.text_index, readv_group_iter, total_items))
1040
# 4) adhoc copy all the other texts.
1041
# We have to topologically insert all texts otherwise we can fail to
1042
# reconcile when parts of a single delta chain are preserved intact,
1043
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1044
# reinserted, and if d3 has incorrect parents it will also be
1045
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1046
# copied), so we will try to delta, but d2 is not currently able to be
1047
# extracted because it's basis d1 is not present. Topologically sorting
1048
# addresses this. The following generates a sort for all the texts that
1049
# are being inserted without having to reference the entire text key
1050
# space (we only topo sort the revisions, which is smaller).
1051
topo_order = tsort.topo_sort(ancestors)
1052
rev_order = dict(zip(topo_order, range(len(topo_order))))
1053
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1054
transaction = repo.get_transaction()
1055
file_id_index = GraphIndexPrefixAdapter(
1056
self.new_pack.text_index,
1058
add_nodes_callback=self.new_pack.text_index.add_nodes)
1059
knit_index = KnitGraphIndex(file_id_index,
1060
add_callback=file_id_index.add_nodes,
1061
deltas=True, parents=True)
1062
output_knit = knit.KnitVersionedFile('reconcile-texts',
1063
self._pack_collection.transport,
1066
access_method=_PackAccess(
1067
{self.new_pack.text_index:self.new_pack.access_tuple()},
1068
(self.new_pack._writer, self.new_pack.text_index)),
1069
factory=knit.KnitPlainFactory())
1070
for key, parent_keys in bad_texts:
1071
# We refer to the new pack to delta data being output.
1072
# A possible improvement would be to catch errors on short reads
1073
# and only flush then.
1074
self.new_pack.flush()
1076
for parent_key in parent_keys:
1077
if parent_key[0] != key[0]:
1078
# Graph parents must match the fileid
1079
raise errors.BzrError('Mismatched key parent %r:%r' %
1081
parents.append(parent_key[1])
1082
source_weave = repo.weave_store.get_weave(key[0], transaction)
1083
text_lines = source_weave.get_lines(key[1])
1084
# adapt the 'knit' to the current file_id.
1085
file_id_index = GraphIndexPrefixAdapter(
1086
self.new_pack.text_index,
1088
add_nodes_callback=self.new_pack.text_index.add_nodes)
1089
knit_index._graph_index = file_id_index
1090
knit_index._add_callback = file_id_index.add_nodes
1091
output_knit.add_lines_with_ghosts(
1092
key[1], parents, text_lines, random_id=True, check_content=False)
1093
# 5) check that nothing inserted has a reference outside the keyspace.
1094
missing_text_keys = self.new_pack._external_compression_parents_of_texts()
1095
if missing_text_keys:
1096
raise errors.BzrError('Reference to missing compression parents %r'
1098
self._log_copied_texts()
1100
def _use_pack(self, new_pack):
1101
"""Override _use_pack to check for reconcile having changed content."""
1102
# XXX: we might be better checking this at the copy time.
1103
original_inventory_keys = set()
1104
inv_index = self._pack_collection.inventory_index.combined_index
1105
for entry in inv_index.iter_all_entries():
1106
original_inventory_keys.add(entry[1])
1107
new_inventory_keys = set()
1108
for entry in new_pack.inventory_index.iter_all_entries():
1109
new_inventory_keys.add(entry[1])
1110
if new_inventory_keys != original_inventory_keys:
1111
self._data_changed = True
1112
return new_pack.data_inserted() and self._data_changed
768
1115
class RepositoryPackCollection(object):
769
"""Management of packs within a repository.
771
:ivar _names: map of {pack_name: (index_size,)}
775
resumed_pack_factory = None
776
normal_packer_class = None
777
optimising_packer_class = None
1116
"""Management of packs within a repository."""
779
1118
def __init__(self, repo, transport, index_transport, upload_transport,
780
pack_transport, index_builder_class, index_class,
782
1120
"""Create a new RepositoryPackCollection.
784
:param transport: Addresses the repository base directory
1122
:param transport: Addresses the repository base directory
785
1123
(typically .bzr/repository/).
786
1124
:param index_transport: Addresses the directory containing indices.
787
1125
:param upload_transport: Addresses the directory into which packs are written
788
1126
while they're being created.
789
1127
:param pack_transport: Addresses the directory of existing complete packs.
790
:param index_builder_class: The index builder class to use.
791
:param index_class: The index class to use.
792
:param use_chk_index: Whether to setup and manage a CHK index.
794
# XXX: This should call self.reset()
795
1129
self.repo = repo
796
1130
self.transport = transport
797
1131
self._index_transport = index_transport
798
1132
self._upload_transport = upload_transport
799
1133
self._pack_transport = pack_transport
800
self._index_builder_class = index_builder_class
801
self._index_class = index_class
802
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3,
1134
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
805
1136
# name:Pack mapping
807
1137
self._packs_by_name = {}
808
1138
# the previous pack-names content
809
1139
self._packs_at_load = None
810
1140
# when a pack is being created by this object, the state of that pack.
811
1141
self._new_pack = None
812
1142
# aggregated revision index data
813
flush = self._flush_new_pack
814
self.revision_index = AggregateIndex(self.reload_pack_names, flush)
815
self.inventory_index = AggregateIndex(self.reload_pack_names, flush)
816
self.text_index = AggregateIndex(self.reload_pack_names, flush)
817
self.signature_index = AggregateIndex(self.reload_pack_names, flush)
818
all_indices = [self.revision_index, self.inventory_index,
819
self.text_index, self.signature_index]
821
self.chk_index = AggregateIndex(self.reload_pack_names, flush)
822
all_indices.append(self.chk_index)
824
# used to determine if we're using a chk_index elsewhere.
825
self.chk_index = None
826
# Tell all the CombinedGraphIndex objects about each other, so they can
827
# share hints about which pack names to search first.
828
all_combined = [agg_idx.combined_index for agg_idx in all_indices]
829
for combined_idx in all_combined:
830
combined_idx.set_sibling_indices(
831
set(all_combined).difference([combined_idx]))
833
self._resumed_packs = []
834
self.config_stack = config.LocationStack(self.transport.base)
837
return '%s(%r)' % (self.__class__.__name__, self.repo)
1143
self.revision_index = AggregateIndex()
1144
self.inventory_index = AggregateIndex()
1145
self.text_index = AggregateIndex()
1146
self.signature_index = AggregateIndex()
839
1148
def add_pack_to_memory(self, pack):
840
1149
"""Make a Pack object available to the repository to satisfy queries.
842
1151
:param pack: A Pack object.
844
if pack.name in self._packs_by_name:
845
raise AssertionError(
846
'pack %s already in _packs_by_name' % (pack.name,))
1153
assert pack.name not in self._packs_by_name
847
1154
self.packs.append(pack)
848
1155
self._packs_by_name[pack.name] = pack
849
1156
self.revision_index.add_index(pack.revision_index, pack)
850
1157
self.inventory_index.add_index(pack.inventory_index, pack)
851
1158
self.text_index.add_index(pack.text_index, pack)
852
1159
self.signature_index.add_index(pack.signature_index, pack)
853
if self.chk_index is not None:
854
self.chk_index.add_index(pack.chk_index, pack)
1161
def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
1162
nostore_sha, random_revid):
1163
file_id_index = GraphIndexPrefixAdapter(
1164
self.text_index.combined_index,
1166
add_nodes_callback=self.text_index.add_callback)
1167
self.repo._text_knit._index._graph_index = file_id_index
1168
self.repo._text_knit._index._add_callback = file_id_index.add_nodes
1169
return self.repo._text_knit.add_lines_with_ghosts(
1170
revision_id, parents, new_lines, nostore_sha=nostore_sha,
1171
random_id=random_revid, check_content=False)[0:2]
856
1173
def all_packs(self):
857
1174
"""Return a list of all the Pack objects this repository has.
908
1221
# group their data with the relevant commit, and that may
909
1222
# involve rewriting ancient history - which autopack tries to
910
1223
# avoid. Alternatively we could not group the data but treat
911
# each of these as having a single revision, and thus add
1224
# each of these as having a single revision, and thus add
912
1225
# one revision for each to the total revision count, to get
913
1226
# a matching distribution.
915
1228
existing_packs.append((revision_count, pack))
916
1229
pack_operations = self.plan_autopack_combinations(
917
1230
existing_packs, pack_distribution)
918
num_new_packs = len(pack_operations)
919
num_old_packs = sum([len(po[1]) for po in pack_operations])
920
num_revs_affected = sum([po[0] for po in pack_operations])
921
mutter('Auto-packing repository %s, which has %d pack files, '
922
'containing %d revisions. Packing %d files into %d affecting %d'
923
' revisions', self, total_packs, total_revisions, num_old_packs,
924
num_new_packs, num_revs_affected)
925
result = self._execute_pack_operations(pack_operations, packer_class=self.normal_packer_class,
926
reload_func=self._restart_autopack)
927
mutter('Auto-packing repository %s completed', self)
1231
self._execute_pack_operations(pack_operations)
930
def _execute_pack_operations(self, pack_operations, packer_class,
1234
def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
932
1235
"""Execute a series of pack operations.
934
1237
:param pack_operations: A list of [revision_count, packs_to_combine].
935
:param packer_class: The class of packer to use
936
:return: The new pack names.
1238
:param _packer_class: The class of packer to use (default: Packer).
938
1241
for revision_count, packs in pack_operations:
939
1242
# we may have no-ops from the setup logic
940
1243
if len(packs) == 0:
942
packer = packer_class(self, packs, '.autopack',
943
reload_func=reload_func)
945
result = packer.pack()
946
except errors.RetryWithNewPacks:
947
# An exception is propagating out of this context, make sure
948
# this packer has cleaned up. Packer() doesn't set its new_pack
949
# state into the RepositoryPackCollection object, so we only
950
# have access to it directly here.
951
if packer.new_pack is not None:
952
packer.new_pack.abort()
1245
_packer_class(self, packs, '.autopack').pack()
956
1246
for pack in packs:
957
1247
self._remove_pack_from_memory(pack)
958
1248
# record the newly available packs and stop advertising the old
961
for _, packs in pack_operations:
962
to_be_obsoleted.extend(packs)
963
result = self._save_pack_names(clear_obsolete_packs=True,
964
obsolete_packs=to_be_obsoleted)
967
def _flush_new_pack(self):
968
if self._new_pack is not None:
969
self._new_pack.flush()
1250
self._save_pack_names(clear_obsolete_packs=True)
1251
# Move the old packs out of the way now they are no longer referenced.
1252
for revision_count, packs in pack_operations:
1253
self._obsolete_packs(packs)
971
1255
def lock_names(self):
972
1256
"""Acquire the mutex around the pack-names index.
974
1258
This cannot be used in the middle of a read-only transaction on the
977
1261
self.repo.control_files.lock_write()
979
def _already_packed(self):
980
"""Is the collection already packed?"""
981
return not (self.repo._format.pack_compresses or (len(self._names) > 1))
983
def pack(self, hint=None, clean_obsolete_packs=False):
984
1264
"""Pack the pack collection totally."""
985
1265
self.ensure_loaded()
986
1266
total_packs = len(self._names)
987
if self._already_packed():
1268
# This is arguably wrong because we might not be optimal, but for
1269
# now lets leave it in. (e.g. reconcile -> one pack. But not
989
1272
total_revisions = self.revision_index.combined_index.key_count()
990
1273
# XXX: the following may want to be a class, to pack with a given
992
1275
mutter('Packing repository %s, which has %d pack files, '
993
'containing %d revisions with hint %r.', self, total_packs,
994
total_revisions, hint)
997
self._try_pack_operations(hint)
998
except RetryPackOperations:
1002
if clean_obsolete_packs:
1003
self._clear_obsolete_packs()
1005
def _try_pack_operations(self, hint):
1006
"""Calculate the pack operations based on the hint (if any), and
1276
'containing %d revisions into 1 packs.', self, total_packs,
1009
1278
# determine which packs need changing
1279
pack_distribution = [1]
1010
1280
pack_operations = [[0, []]]
1011
1281
for pack in self.all_packs():
1012
if hint is None or pack.name in hint:
1013
# Either no hint was provided (so we are packing everything),
1014
# or this pack was included in the hint.
1015
pack_operations[-1][0] += pack.get_revision_count()
1016
pack_operations[-1][1].append(pack)
1017
self._execute_pack_operations(pack_operations,
1018
packer_class=self.optimising_packer_class,
1019
reload_func=self._restart_pack_operations)
1282
pack_operations[-1][0] += pack.get_revision_count()
1283
pack_operations[-1][1].append(pack)
1284
self._execute_pack_operations(pack_operations, OptimisingPacker)
1021
1286
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1022
1287
"""Plan a pack operation.
1309
1490
self._packs_by_name = {}
1310
1491
self._packs_at_load = None
1493
def _make_index_map(self, index_suffix):
1494
"""Return information on existing indices.
1496
:param suffix: Index suffix added to pack name.
1498
:returns: (pack_map, indices) where indices is a list of GraphIndex
1499
objects, and pack_map is a mapping from those objects to the
1500
pack tuple they describe.
1502
# TODO: stop using this; it creates new indices unnecessarily.
1503
self.ensure_loaded()
1504
suffix_map = {'.rix': 'revision_index',
1505
'.six': 'signature_index',
1506
'.iix': 'inventory_index',
1507
'.tix': 'text_index',
1509
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1510
suffix_map[index_suffix])
1512
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1513
"""Convert a list of packs to an index pack map and index list.
1515
:param packs: The packs list to process.
1516
:param index_attribute: The attribute that the desired index is found
1518
:return: A tuple (map, list) where map contains the dict from
1519
index:pack_tuple, and lsit contains the indices in the same order
1525
index = getattr(pack, index_attribute)
1526
indices.append(index)
1527
pack_map[index] = (pack.pack_transport, pack.file_name())
1528
return pack_map, indices
1530
def _index_contents(self, pack_map, key_filter=None):
1531
"""Get an iterable of the index contents from a pack_map.
1533
:param pack_map: A map from indices to pack details.
1534
:param key_filter: An optional filter to limit the
1537
indices = [index for index in pack_map.iterkeys()]
1538
all_index = CombinedGraphIndex(indices)
1539
if key_filter is None:
1540
return all_index.iter_all_entries()
1542
return all_index.iter_entries(key_filter)
1312
1544
def _unlock_names(self):
1313
1545
"""Release the mutex around the pack-names index."""
1314
1546
self.repo.control_files.unlock()
1316
def _diff_pack_names(self):
1317
"""Read the pack names from disk, and compare it to the one in memory.
1319
:return: (disk_nodes, deleted_nodes, new_nodes)
1320
disk_nodes The final set of nodes that should be referenced
1321
deleted_nodes Nodes which have been removed from when we started
1322
new_nodes Nodes that are newly introduced
1324
# load the disk nodes across
1326
for index, key, value in self._iter_disk_pack_index():
1327
disk_nodes.add((key, value))
1328
orig_disk_nodes = set(disk_nodes)
1330
# do a two-way diff against our original content
1331
current_nodes = set()
1332
for name, sizes in self._names.iteritems():
1334
((name, ), ' '.join(str(size) for size in sizes)))
1336
# Packs no longer present in the repository, which were present when we
1337
# locked the repository
1338
deleted_nodes = self._packs_at_load - current_nodes
1339
# Packs which this process is adding
1340
new_nodes = current_nodes - self._packs_at_load
1342
# Update the disk_nodes set to include the ones we are adding, and
1343
# remove the ones which were removed by someone else
1344
disk_nodes.difference_update(deleted_nodes)
1345
disk_nodes.update(new_nodes)
1347
return disk_nodes, deleted_nodes, new_nodes, orig_disk_nodes
1349
def _syncronize_pack_names_from_disk_nodes(self, disk_nodes):
1350
"""Given the correct set of pack files, update our saved info.
1352
:return: (removed, added, modified)
1353
removed pack names removed from self._names
1354
added pack names added to self._names
1355
modified pack names that had changed value
1360
## self._packs_at_load = disk_nodes
1548
def _save_pack_names(self, clear_obsolete_packs=False):
1549
"""Save the list of packs.
1551
This will take out the mutex around the pack names list for the
1552
duration of the method call. If concurrent updates have been made, a
1553
three-way merge between the current list and the current in memory list
1556
:param clear_obsolete_packs: If True, clear out the contents of the
1557
obsolete_packs directory.
1561
builder = GraphIndexBuilder()
1562
# load the disk nodes across
1564
for index, key, value in self._iter_disk_pack_index():
1565
disk_nodes.add((key, value))
1566
# do a two-way diff against our original content
1567
current_nodes = set()
1568
for name, sizes in self._names.iteritems():
1570
((name, ), ' '.join(str(size) for size in sizes)))
1571
deleted_nodes = self._packs_at_load - current_nodes
1572
new_nodes = current_nodes - self._packs_at_load
1573
disk_nodes.difference_update(deleted_nodes)
1574
disk_nodes.update(new_nodes)
1575
# TODO: handle same-name, index-size-changes here -
1576
# e.g. use the value from disk, not ours, *unless* we're the one
1578
for key, value in disk_nodes:
1579
builder.add_node(key, value)
1580
self.transport.put_file('pack-names', builder.finish(),
1581
mode=self.repo.control_files._file_mode)
1582
# move the baseline forward
1583
self._packs_at_load = disk_nodes
1584
# now clear out the obsolete packs directory
1585
if clear_obsolete_packs:
1586
self.transport.clone('obsolete_packs').delete_multi(
1587
self.transport.list_dir('obsolete_packs'))
1589
self._unlock_names()
1590
# synchronise the memory packs list with what we just wrote:
1361
1591
new_names = dict(disk_nodes)
1362
1592
# drop no longer present nodes
1363
1593
for pack in self.all_packs():
1364
1594
if (pack.name,) not in new_names:
1365
removed.append(pack.name)
1366
1595
self._remove_pack_from_memory(pack)
1367
1596
# add new nodes/refresh existing ones
1368
1597
for key, value in disk_nodes:
1378
1607
# disk index because the set values are the same, unless
1379
1608
# the only index shows up as deleted by the set difference
1380
1609
# - which it may. Until there is a specific test for this,
1381
# assume it's broken. RBC 20071017.
1610
# assume its broken. RBC 20071017.
1382
1611
self._remove_pack_from_memory(self.get_pack_by_name(name))
1383
1612
self._names[name] = sizes
1384
1613
self.get_pack_by_name(name)
1385
modified.append(name)
1388
1616
self._names[name] = sizes
1389
1617
self.get_pack_by_name(name)
1391
return removed, added, modified
1393
def _save_pack_names(self, clear_obsolete_packs=False, obsolete_packs=None):
1394
"""Save the list of packs.
1396
This will take out the mutex around the pack names list for the
1397
duration of the method call. If concurrent updates have been made, a
1398
three-way merge between the current list and the current in memory list
1401
:param clear_obsolete_packs: If True, clear out the contents of the
1402
obsolete_packs directory.
1403
:param obsolete_packs: Packs that are obsolete once the new pack-names
1404
file has been written.
1405
:return: A list of the names saved that were not previously on disk.
1407
already_obsolete = []
1410
builder = self._index_builder_class()
1411
(disk_nodes, deleted_nodes, new_nodes,
1412
orig_disk_nodes) = self._diff_pack_names()
1413
# TODO: handle same-name, index-size-changes here -
1414
# e.g. use the value from disk, not ours, *unless* we're the one
1416
for key, value in disk_nodes:
1417
builder.add_node(key, value)
1418
self.transport.put_file('pack-names', builder.finish(),
1419
mode=self.repo.bzrdir._get_file_mode())
1420
self._packs_at_load = disk_nodes
1421
if clear_obsolete_packs:
1424
to_preserve = set([o.name for o in obsolete_packs])
1425
already_obsolete = self._clear_obsolete_packs(to_preserve)
1427
self._unlock_names()
1428
# synchronise the memory packs list with what we just wrote:
1429
self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1431
# TODO: We could add one more condition here. "if o.name not in
1432
# orig_disk_nodes and o != the new_pack we haven't written to
1433
# disk yet. However, the new pack object is not easily
1434
# accessible here (it would have to be passed through the
1435
# autopacking code, etc.)
1436
obsolete_packs = [o for o in obsolete_packs
1437
if o.name not in already_obsolete]
1438
self._obsolete_packs(obsolete_packs)
1439
return [new_node[0][0] for new_node in new_nodes]
1441
def reload_pack_names(self):
1442
"""Sync our pack listing with what is present in the repository.
1444
This should be called when we find out that something we thought was
1445
present is now missing. This happens when another process re-packs the
1448
:return: True if the in-memory list of packs has been altered at all.
1450
# The ensure_loaded call is to handle the case where the first call
1451
# made involving the collection was to reload_pack_names, where we
1452
# don't have a view of disk contents. It's a bit of a bandaid, and
1453
# causes two reads of pack-names, but it's a rare corner case not
1454
# struck with regular push/pull etc.
1455
first_read = self.ensure_loaded()
1458
# out the new value.
1459
(disk_nodes, deleted_nodes, new_nodes,
1460
orig_disk_nodes) = self._diff_pack_names()
1461
# _packs_at_load is meant to be the explicit list of names in
1462
# 'pack-names' at then start. As such, it should not contain any
1463
# pending names that haven't been written out yet.
1464
self._packs_at_load = orig_disk_nodes
1466
modified) = self._syncronize_pack_names_from_disk_nodes(disk_nodes)
1467
if removed or added or modified:
1471
def _restart_autopack(self):
1472
"""Reload the pack names list, and restart the autopack code."""
1473
if not self.reload_pack_names():
1474
# Re-raise the original exception, because something went missing
1475
# and a restart didn't find it
1477
raise errors.RetryAutopack(self.repo, False, sys.exc_info())
1479
def _restart_pack_operations(self):
1480
"""Reload the pack names list, and restart the autopack code."""
1481
if not self.reload_pack_names():
1482
# Re-raise the original exception, because something went missing
1483
# and a restart didn't find it
1485
raise RetryPackOperations(self.repo, False, sys.exc_info())
1487
def _clear_obsolete_packs(self, preserve=None):
1488
"""Delete everything from the obsolete-packs directory.
1490
:return: A list of pack identifiers (the filename without '.pack') that
1491
were found in obsolete_packs.
1494
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1495
if preserve is None:
1497
for filename in obsolete_pack_transport.list_dir('.'):
1498
name, ext = osutils.splitext(filename)
1501
if name in preserve:
1504
obsolete_pack_transport.delete(filename)
1505
except (errors.PathError, errors.TransportError), e:
1506
warning("couldn't delete obsolete pack, skipping it:\n%s"
1510
1619
def _start_write_group(self):
1511
1620
# Do not permit preparation for writing if we're not in a 'write lock'.
1512
1621
if not self.repo.is_write_locked():
1513
1622
raise errors.NotWriteLocked(self)
1514
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
1515
file_mode=self.repo.bzrdir._get_file_mode())
1623
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1624
self._pack_transport, upload_suffix='.pack',
1625
file_mode=self.repo.control_files._file_mode)
1516
1626
# allow writing: queue writes to a new index
1517
1627
self.revision_index.add_writable_index(self._new_pack.revision_index,
1518
1628
self._new_pack)
1520
1630
self._new_pack)
1521
1631
self.text_index.add_writable_index(self._new_pack.text_index,
1522
1632
self._new_pack)
1523
self._new_pack.text_index.set_optimize(combine_backing_indices=False)
1524
1633
self.signature_index.add_writable_index(self._new_pack.signature_index,
1525
1634
self._new_pack)
1526
if self.chk_index is not None:
1527
self.chk_index.add_writable_index(self._new_pack.chk_index,
1529
self.repo.chk_bytes._index._add_callback = self.chk_index.add_callback
1530
self._new_pack.chk_index.set_optimize(combine_backing_indices=False)
1532
self.repo.inventories._index._add_callback = self.inventory_index.add_callback
1533
self.repo.revisions._index._add_callback = self.revision_index.add_callback
1534
self.repo.signatures._index._add_callback = self.signature_index.add_callback
1535
self.repo.texts._index._add_callback = self.text_index.add_callback
1636
# reused revision and signature knits may need updating
1638
# "Hysterical raisins. client code in bzrlib grabs those knits outside
1639
# of write groups and then mutates it inside the write group."
1640
if self.repo._revision_knit is not None:
1641
self.repo._revision_knit._index._add_callback = \
1642
self.revision_index.add_callback
1643
if self.repo._signature_knit is not None:
1644
self.repo._signature_knit._index._add_callback = \
1645
self.signature_index.add_callback
1646
# create a reused knit object for text addition in commit.
1647
self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
1537
1650
def _abort_write_group(self):
1538
1651
# FIXME: just drop the transient index.
1539
1652
# forget what names there are
1540
1653
if self._new_pack is not None:
1541
operation = cleanup.OperationWithCleanups(self._new_pack.abort)
1542
operation.add_cleanup(setattr, self, '_new_pack', None)
1543
# If we aborted while in the middle of finishing the write
1544
# group, _remove_pack_indices could fail because the indexes are
1545
# already gone. But they're not there we shouldn't fail in this
1546
# case, so we pass ignore_missing=True.
1547
operation.add_cleanup(self._remove_pack_indices, self._new_pack,
1548
ignore_missing=True)
1549
operation.run_simple()
1550
for resumed_pack in self._resumed_packs:
1551
operation = cleanup.OperationWithCleanups(resumed_pack.abort)
1552
# See comment in previous finally block.
1553
operation.add_cleanup(self._remove_pack_indices, resumed_pack,
1554
ignore_missing=True)
1555
operation.run_simple()
1556
del self._resumed_packs[:]
1558
def _remove_resumed_pack_indices(self):
1559
for resumed_pack in self._resumed_packs:
1560
self._remove_pack_indices(resumed_pack)
1561
del self._resumed_packs[:]
1563
def _check_new_inventories(self):
1564
"""Detect missing inventories in this write group.
1566
:returns: list of strs, summarising any problems found. If the list is
1567
empty no problems were found.
1569
# The base implementation does no checks. GCRepositoryPackCollection
1654
self._new_pack.abort()
1655
self._remove_pack_indices(self._new_pack)
1656
self._new_pack = None
1657
self.repo._text_knit = None
1573
1659
def _commit_write_group(self):
1575
for prefix, versioned_file in (
1576
('revisions', self.repo.revisions),
1577
('inventories', self.repo.inventories),
1578
('texts', self.repo.texts),
1579
('signatures', self.repo.signatures),
1581
missing = versioned_file.get_missing_compression_parent_keys()
1582
all_missing.update([(prefix,) + key for key in missing])
1584
raise errors.BzrCheckError(
1585
"Repository %s has missing compression parent(s) %r "
1586
% (self.repo, sorted(all_missing)))
1587
problems = self._check_new_inventories()
1589
problems_summary = '\n'.join(problems)
1590
raise errors.BzrCheckError(
1591
"Cannot add revision(s) to repository: " + problems_summary)
1592
1660
self._remove_pack_indices(self._new_pack)
1593
any_new_content = False
1594
1661
if self._new_pack.data_inserted():
1595
1662
# get all the data to disk and read to use
1596
1663
self._new_pack.finish()
1597
1664
self.allocate(self._new_pack)
1598
1665
self._new_pack = None
1599
any_new_content = True
1601
self._new_pack.abort()
1602
self._new_pack = None
1603
for resumed_pack in self._resumed_packs:
1604
# XXX: this is a pretty ugly way to turn the resumed pack into a
1605
# properly committed pack.
1606
self._names[resumed_pack.name] = None
1607
self._remove_pack_from_memory(resumed_pack)
1608
resumed_pack.finish()
1609
self.allocate(resumed_pack)
1610
any_new_content = True
1611
del self._resumed_packs[:]
1613
result = self.autopack()
1666
if not self.autopack():
1615
1667
# when autopack takes no steps, the names list is still
1617
return self._save_pack_names()
1621
def _suspend_write_group(self):
1622
tokens = [pack.name for pack in self._resumed_packs]
1623
self._remove_pack_indices(self._new_pack)
1624
if self._new_pack.data_inserted():
1625
# get all the data to disk and read to use
1626
self._new_pack.finish(suspend=True)
1627
tokens.append(self._new_pack.name)
1628
self._new_pack = None
1669
self._save_pack_names()
1630
1671
self._new_pack.abort()
1631
1672
self._new_pack = None
1632
self._remove_resumed_pack_indices()
1635
def _resume_write_group(self, tokens):
1636
for token in tokens:
1637
self._resume_pack(token)
1640
class PackRepository(MetaDirVersionedFileRepository):
1641
"""Repository with knit objects stored inside pack containers.
1643
The layering for a KnitPackRepository is:
1645
Graph | HPSS | Repository public layer |
1646
===================================================
1647
Tuple based apis below, string based, and key based apis above
1648
---------------------------------------------------
1650
Provides .texts, .revisions etc
1651
This adapts the N-tuple keys to physical knit records which only have a
1652
single string identifier (for historical reasons), which in older formats
1653
was always the revision_id, and in the mapped code for packs is always
1654
the last element of key tuples.
1655
---------------------------------------------------
1657
A separate GraphIndex is used for each of the
1658
texts/inventories/revisions/signatures contained within each individual
1659
pack file. The GraphIndex layer works in N-tuples and is unaware of any
1661
===================================================
1665
# These attributes are inherited from the Repository base class. Setting
1666
# them to None ensures that if the constructor is changed to not initialize
1667
# them, or a subclass fails to call the constructor, that an error will
1668
# occur rather than the system working but generating incorrect data.
1669
_commit_builder_class = None
1672
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1674
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1675
self._commit_builder_class = _commit_builder_class
1676
self._serializer = _serializer
1673
self.repo._text_knit = None
1676
class KnitPackRevisionStore(KnitRevisionStore):
1677
"""An object to adapt access from RevisionStore's to use KnitPacks.
1679
This class works by replacing the original RevisionStore.
1680
We need to do this because the KnitPackRevisionStore is less
1681
isolated in its layering - it uses services from the repo.
1684
def __init__(self, repo, transport, revisionstore):
1685
"""Create a KnitPackRevisionStore on repo with revisionstore.
1687
This will store its state in the Repository, use the
1688
indices to provide a KnitGraphIndex,
1689
and at the end of transactions write new indices.
1691
KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
1693
self._serializer = revisionstore._serializer
1694
self.transport = transport
1696
def get_revision_file(self, transaction):
1697
"""Get the revision versioned file object."""
1698
if getattr(self.repo, '_revision_knit', None) is not None:
1699
return self.repo._revision_knit
1700
self.repo._pack_collection.ensure_loaded()
1701
add_callback = self.repo._pack_collection.revision_index.add_callback
1702
# setup knit specific objects
1703
knit_index = KnitGraphIndex(
1704
self.repo._pack_collection.revision_index.combined_index,
1705
add_callback=add_callback)
1706
self.repo._revision_knit = knit.KnitVersionedFile(
1707
'revisions', self.transport.clone('..'),
1708
self.repo.control_files._file_mode,
1709
create=False, access_mode=self.repo._access_mode(),
1710
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1711
access_method=self.repo._pack_collection.revision_index.knit_access)
1712
return self.repo._revision_knit
1714
def get_signature_file(self, transaction):
1715
"""Get the signature versioned file object."""
1716
if getattr(self.repo, '_signature_knit', None) is not None:
1717
return self.repo._signature_knit
1718
self.repo._pack_collection.ensure_loaded()
1719
add_callback = self.repo._pack_collection.signature_index.add_callback
1720
# setup knit specific objects
1721
knit_index = KnitGraphIndex(
1722
self.repo._pack_collection.signature_index.combined_index,
1723
add_callback=add_callback, parents=False)
1724
self.repo._signature_knit = knit.KnitVersionedFile(
1725
'signatures', self.transport.clone('..'),
1726
self.repo.control_files._file_mode,
1727
create=False, access_mode=self.repo._access_mode(),
1728
index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
1729
access_method=self.repo._pack_collection.signature_index.knit_access)
1730
return self.repo._signature_knit
1733
class KnitPackTextStore(VersionedFileStore):
1734
"""Presents a TextStore abstraction on top of packs.
1736
This class works by replacing the original VersionedFileStore.
1737
We need to do this because the KnitPackRevisionStore is less
1738
isolated in its layering - it uses services from the repo and shares them
1739
with all the data written in a single write group.
1742
def __init__(self, repo, transport, weavestore):
1743
"""Create a KnitPackTextStore on repo with weavestore.
1745
This will store its state in the Repository, use the
1746
indices FileNames to provide a KnitGraphIndex,
1747
and at the end of transactions write new indices.
1749
# don't call base class constructor - it's not suitable.
1750
# no transient data stored in the transaction
1752
self._precious = False
1754
self.transport = transport
1755
self.weavestore = weavestore
1756
# XXX for check() which isn't updated yet
1757
self._transport = weavestore._transport
1759
def get_weave_or_empty(self, file_id, transaction):
1760
"""Get a 'Knit' backed by the .tix indices.
1762
The transaction parameter is ignored.
1764
self.repo._pack_collection.ensure_loaded()
1765
add_callback = self.repo._pack_collection.text_index.add_callback
1766
# setup knit specific objects
1767
file_id_index = GraphIndexPrefixAdapter(
1768
self.repo._pack_collection.text_index.combined_index,
1769
(file_id, ), 1, add_nodes_callback=add_callback)
1770
knit_index = KnitGraphIndex(file_id_index,
1771
add_callback=file_id_index.add_nodes,
1772
deltas=True, parents=True)
1773
return knit.KnitVersionedFile('text:' + file_id,
1774
self.transport.clone('..'),
1777
access_method=self.repo._pack_collection.text_index.knit_access,
1778
factory=knit.KnitPlainFactory())
1780
get_weave = get_weave_or_empty
1783
"""Generate a list of the fileids inserted, for use by check."""
1784
self.repo._pack_collection.ensure_loaded()
1786
for index, key, value, refs in \
1787
self.repo._pack_collection.text_index.combined_index.iter_all_entries():
1792
class InventoryKnitThunk(object):
1793
"""An object to manage thunking get_inventory_weave to pack based knits."""
1795
def __init__(self, repo, transport):
1796
"""Create an InventoryKnitThunk for repo at transport.
1798
This will store its state in the Repository, use the
1799
indices FileNames to provide a KnitGraphIndex,
1800
and at the end of transactions write a new index..
1803
self.transport = transport
1805
def get_weave(self):
1806
"""Get a 'Knit' that contains inventory data."""
1807
self.repo._pack_collection.ensure_loaded()
1808
add_callback = self.repo._pack_collection.inventory_index.add_callback
1809
# setup knit specific objects
1810
knit_index = KnitGraphIndex(
1811
self.repo._pack_collection.inventory_index.combined_index,
1812
add_callback=add_callback, deltas=True, parents=True)
1813
return knit.KnitVersionedFile(
1814
'inventory', self.transport.clone('..'),
1815
self.repo.control_files._file_mode,
1816
create=False, access_mode=self.repo._access_mode(),
1817
index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
1818
access_method=self.repo._pack_collection.inventory_index.knit_access)
1821
class KnitPackRepository(KnitRepository):
1822
"""Experimental graph-knit using repository."""
1824
def __init__(self, _format, a_bzrdir, control_files, _revision_store,
1825
control_store, text_store, _commit_builder_class, _serializer):
1826
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1827
_revision_store, control_store, text_store, _commit_builder_class,
1829
index_transport = control_files._transport.clone('indices')
1830
self._pack_collection = RepositoryPackCollection(self, control_files._transport,
1832
control_files._transport.clone('upload'),
1833
control_files._transport.clone('packs'))
1834
self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
1835
self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
1836
self._inv_thunk = InventoryKnitThunk(self, index_transport)
1837
# True when the repository object is 'write locked' (as opposed to the
1838
# physical lock only taken out around changes to the pack-names list.)
1839
# Another way to represent this would be a decorator around the control
1840
# files object that presents logical locks as physical ones - if this
1841
# gets ugly consider that alternative design. RBC 20071011
1842
self._write_lock_count = 0
1843
self._transaction = None
1845
self._reconcile_does_inventory_gc = True
1677
1846
self._reconcile_fixes_text_parents = True
1678
if self._format.supports_external_lookups:
1679
self._unstacked_provider = graph.CachingParentsProvider(
1680
self._make_parents_provider_unstacked())
1847
self._reconcile_backsup_inventory = False
1849
def _abort_write_group(self):
1850
self._pack_collection._abort_write_group()
1852
def _access_mode(self):
1853
"""Return 'w' or 'r' for depending on whether a write lock is active.
1855
This method is a helper for the Knit-thunking support objects.
1857
if self.is_write_locked():
1861
def _find_inconsistent_revision_parents(self):
1862
"""Find revisions with incorrectly cached parents.
1864
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1865
parents-in-revision).
1867
if not self.is_locked():
1868
raise errors.ObjectNotLocked(self)
1869
pb = ui.ui_factory.nested_progress_bar()
1872
revision_nodes = self._pack_collection.revision_index \
1873
.combined_index.iter_all_entries()
1874
index_positions = []
1875
# Get the cached index values for all revisions, and also the location
1876
# in each index of the revision text so we can perform linear IO.
1877
for index, key, value, refs in revision_nodes:
1878
pos, length = value[1:].split(' ')
1879
index_positions.append((index, int(pos), key[0],
1880
tuple(parent[0] for parent in refs[0])))
1881
pb.update("Reading revision index.", 0, 0)
1882
index_positions.sort()
1883
batch_count = len(index_positions) / 1000 + 1
1884
pb.update("Checking cached revision graph.", 0, batch_count)
1885
for offset in xrange(batch_count):
1886
pb.update("Checking cached revision graph.", offset)
1887
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1890
rev_ids = [item[2] for item in to_query]
1891
revs = self.get_revisions(rev_ids)
1892
for revision, item in zip(revs, to_query):
1893
index_parents = item[3]
1894
rev_parents = tuple(revision.parent_ids)
1895
if index_parents != rev_parents:
1896
result.append((revision.revision_id, index_parents, rev_parents))
1901
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
1902
def get_parents(self, revision_ids):
1903
"""See graph._StackedParentsProvider.get_parents."""
1904
parent_map = self.get_parent_map(revision_ids)
1905
return [parent_map.get(r, None) for r in revision_ids]
1907
def get_parent_map(self, keys):
1908
"""See graph._StackedParentsProvider.get_parent_map
1910
This implementation accesses the combined revision index to provide
1913
self._pack_collection.ensure_loaded()
1914
index = self._pack_collection.revision_index.combined_index
1916
if _mod_revision.NULL_REVISION in keys:
1917
keys.discard(_mod_revision.NULL_REVISION)
1918
found_parents = {_mod_revision.NULL_REVISION:()}
1682
self._unstacked_provider = graph.CachingParentsProvider(self)
1683
self._unstacked_provider.disable_cache()
1921
search_keys = set((revision_id,) for revision_id in keys)
1922
for index, key, value, refs in index.iter_entries(search_keys):
1925
parents = (_mod_revision.NULL_REVISION,)
1927
parents = tuple(parent[0] for parent in parents)
1928
found_parents[key[0]] = parents
1929
return found_parents
1685
1931
@needs_read_lock
1686
def _all_revision_ids(self):
1687
"""See Repository.all_revision_ids()."""
1688
return [key[0] for key in self.revisions.keys()]
1690
def _abort_write_group(self):
1691
self.revisions._index._key_dependencies.clear()
1692
self._pack_collection._abort_write_group()
1932
def get_revision_graph(self, revision_id=None):
1933
"""Return a dictionary containing the revision graph.
1935
:param revision_id: The revision_id to get a graph from. If None, then
1936
the entire revision graph is returned. This is a deprecated mode of
1937
operation and will be removed in the future.
1938
:return: a dictionary of revision_id->revision_parents_list.
1940
if 'evil' in debug.debug_flags:
1942
"get_revision_graph scales with size of history.")
1943
# special case NULL_REVISION
1944
if revision_id == _mod_revision.NULL_REVISION:
1946
if revision_id is None:
1947
revision_vf = self._get_revision_vf()
1948
return revision_vf.get_graph()
1949
g = self.get_graph()
1950
first = g.get_parent_map([revision_id])
1951
if revision_id not in first:
1952
raise errors.NoSuchRevision(self, revision_id)
1956
NULL_REVISION = _mod_revision.NULL_REVISION
1957
ghosts = set([NULL_REVISION])
1958
for rev_id, parent_ids in g.iter_ancestry([revision_id]):
1959
if parent_ids is None: # This is a ghost
1962
ancestry[rev_id] = parent_ids
1963
for p in parent_ids:
1965
children[p].append(rev_id)
1967
children[p] = [rev_id]
1969
if NULL_REVISION in ancestry:
1970
del ancestry[NULL_REVISION]
1972
# Find all nodes that reference a ghost, and filter the ghosts out
1973
# of their parent lists. To preserve the order of parents, and
1974
# avoid double filtering nodes, we just find all children first,
1976
children_of_ghosts = set()
1977
for ghost in ghosts:
1978
children_of_ghosts.update(children[ghost])
1980
for child in children_of_ghosts:
1981
ancestry[child] = tuple(p for p in ancestry[child]
1985
def has_revisions(self, revision_ids):
1986
"""See Repository.has_revisions()."""
1987
revision_ids = set(revision_ids)
1988
result = revision_ids.intersection(
1989
set([None, _mod_revision.NULL_REVISION]))
1990
revision_ids.difference_update(result)
1991
index = self._pack_collection.revision_index.combined_index
1992
keys = [(revision_id,) for revision_id in revision_ids]
1993
result.update(node[1][0] for node in index.iter_entries(keys))
1694
1996
def _make_parents_provider(self):
1695
if not self._format.supports_external_lookups:
1696
return self._unstacked_provider
1697
return graph.StackedParentsProvider(_LazyListJoin(
1698
[self._unstacked_provider], self._fallback_repositories))
1997
return graph.CachingParentsProvider(self)
1700
1999
def _refresh_data(self):
1701
if not self.is_locked():
1703
self._pack_collection.reload_pack_names()
1704
self._unstacked_provider.disable_cache()
1705
self._unstacked_provider.enable_cache()
2000
if self._write_lock_count == 1 or (
2001
self.control_files._lock_count == 1 and
2002
self.control_files._lock_mode == 'r'):
2003
# forget what names there are
2004
self._pack_collection.reset()
2005
# XXX: Better to do an in-memory merge when acquiring a new lock -
2006
# factor out code from _save_pack_names.
2007
self._pack_collection.ensure_loaded()
1707
2009
def _start_write_group(self):
1708
2010
self._pack_collection._start_write_group()
1710
2012
def _commit_write_group(self):
1711
hint = self._pack_collection._commit_write_group()
1712
self.revisions._index._key_dependencies.clear()
1713
# The commit may have added keys that were previously cached as
1714
# missing, so reset the cache.
1715
self._unstacked_provider.disable_cache()
1716
self._unstacked_provider.enable_cache()
1719
def suspend_write_group(self):
1720
# XXX check self._write_group is self.get_transaction()?
1721
tokens = self._pack_collection._suspend_write_group()
1722
self.revisions._index._key_dependencies.clear()
1723
self._write_group = None
1726
def _resume_write_group(self, tokens):
1727
self._start_write_group()
1729
self._pack_collection._resume_write_group(tokens)
1730
except errors.UnresumableWriteGroup:
1731
self._abort_write_group()
1733
for pack in self._pack_collection._resumed_packs:
1734
self.revisions._index.scan_unvalidated_index(pack.revision_index)
2013
return self._pack_collection._commit_write_group()
2015
def get_inventory_weave(self):
2016
return self._inv_thunk.get_weave()
1736
2018
def get_transaction(self):
1737
2019
if self._write_lock_count:
1890
2163
mutter('creating repository in %s.', a_bzrdir.transport.base)
1891
2164
dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
1892
builder = self.index_builder_class()
2165
builder = GraphIndexBuilder()
1893
2166
files = [('pack-names', builder.finish())]
1894
2167
utf8_files = [('format', self.get_format_string())]
1896
2169
self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
1897
repository = self.open(a_bzrdir=a_bzrdir, _found=True)
1898
self._run_post_repo_init_hooks(repository, a_bzrdir, shared)
2170
return self.open(a_bzrdir=a_bzrdir, _found=True)
1901
2172
def open(self, a_bzrdir, _found=False, _override_transport=None):
1902
2173
"""See RepositoryFormat.open().
1904
2175
:param _override_transport: INTERNAL USE ONLY. Allows opening the
1905
2176
repository at a slightly different url
1906
2177
than normal. I.e. during 'upgrade'.
1909
2180
format = RepositoryFormat.find_format(a_bzrdir)
2181
assert format.__class__ == self.__class__
1910
2182
if _override_transport is not None:
1911
2183
repo_transport = _override_transport
1913
2185
repo_transport = a_bzrdir.get_repository_transport(None)
1914
2186
control_files = lockable_files.LockableFiles(repo_transport,
1915
2187
'lock', lockdir.LockDir)
2188
text_store = self._get_text_store(repo_transport, control_files)
2189
control_store = self._get_control_store(repo_transport, control_files)
2190
_revision_store = self._get_revision_store(repo_transport, control_files)
1916
2191
return self.repository_class(_format=self,
1917
2192
a_bzrdir=a_bzrdir,
1918
2193
control_files=control_files,
2194
_revision_store=_revision_store,
2195
control_store=control_store,
2196
text_store=text_store,
1919
2197
_commit_builder_class=self._commit_builder_class,
1920
2198
_serializer=self._serializer)
1923
class RetryPackOperations(errors.RetryWithNewPacks):
1924
"""Raised when we are packing and we find a missing file.
1926
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1927
code it should try again.
1930
internal_error = True
1932
_fmt = ("Pack files have changed, reload and try pack again."
1933
" context: %(context)s %(orig_error)s")
1936
class _DirectPackAccess(object):
1937
"""Access to data in one or more packs with less translation."""
1939
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1940
"""Create a _DirectPackAccess object.
1942
:param index_to_packs: A dict mapping index objects to the transport
1943
and file names for obtaining data.
1944
:param reload_func: A function to call if we determine that the pack
1945
files have moved and we need to reload our caches. See
1946
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1948
self._container_writer = None
1949
self._write_index = None
1950
self._indices = index_to_packs
1951
self._reload_func = reload_func
1952
self._flush_func = flush_func
1954
def add_raw_records(self, key_sizes, raw_data):
1955
"""Add raw knit bytes to a storage area.
1957
The data is spooled to the container writer in one bytes-record per
1960
:param sizes: An iterable of tuples containing the key and size of each
1962
:param raw_data: A bytestring containing the data.
1963
:return: A list of memos to retrieve the record later. Each memo is an
1964
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1965
length), where the index field is the write_index object supplied
1966
to the PackAccess object.
1968
if type(raw_data) is not str:
1969
raise AssertionError(
1970
'data must be plain bytes was %s' % type(raw_data))
1973
for key, size in key_sizes:
1974
p_offset, p_length = self._container_writer.add_bytes_record(
1975
raw_data[offset:offset+size], [])
1977
result.append((self._write_index, p_offset, p_length))
1981
"""Flush pending writes on this access object.
1983
This will flush any buffered writes to a NewPack.
1985
if self._flush_func is not None:
1988
def get_raw_records(self, memos_for_retrieval):
1989
"""Get the raw bytes for a records.
1991
:param memos_for_retrieval: An iterable containing the (index, pos,
1992
length) memo for retrieving the bytes. The Pack access method
1993
looks up the pack to use for a given record in its index_to_pack
1995
:return: An iterator over the bytes of the records.
1997
# first pass, group into same-index requests
1999
current_index = None
2000
for (index, offset, length) in memos_for_retrieval:
2001
if current_index == index:
2002
current_list.append((offset, length))
2004
if current_index is not None:
2005
request_lists.append((current_index, current_list))
2006
current_index = index
2007
current_list = [(offset, length)]
2008
# handle the last entry
2009
if current_index is not None:
2010
request_lists.append((current_index, current_list))
2011
for index, offsets in request_lists:
2013
transport, path = self._indices[index]
2015
# A KeyError here indicates that someone has triggered an index
2016
# reload, and this index has gone missing, we need to start
2018
if self._reload_func is None:
2019
# If we don't have a _reload_func there is nothing that can
2022
raise errors.RetryWithNewPacks(index,
2023
reload_occurred=True,
2024
exc_info=sys.exc_info())
2026
reader = pack.make_readv_reader(transport, path, offsets)
2027
for names, read_func in reader.iter_records():
2028
yield read_func(None)
2029
except errors.NoSuchFile:
2030
# A NoSuchFile error indicates that a pack file has gone
2031
# missing on disk, we need to trigger a reload, and start over.
2032
if self._reload_func is None:
2034
raise errors.RetryWithNewPacks(transport.abspath(path),
2035
reload_occurred=False,
2036
exc_info=sys.exc_info())
2038
def set_writer(self, writer, index, transport_packname):
2039
"""Set a writer to use for adding data."""
2040
if index is not None:
2041
self._indices[index] = transport_packname
2042
self._container_writer = writer
2043
self._write_index = index
2045
def reload_or_raise(self, retry_exc):
2046
"""Try calling the reload function, or re-raise the original exception.
2048
This should be called after _DirectPackAccess raises a
2049
RetryWithNewPacks exception. This function will handle the common logic
2050
of determining when the error is fatal versus being temporary.
2051
It will also make sure that the original exception is raised, rather
2052
than the RetryWithNewPacks exception.
2054
If this function returns, then the calling function should retry
2055
whatever operation was being performed. Otherwise an exception will
2058
:param retry_exc: A RetryWithNewPacks exception.
2061
if self._reload_func is None:
2063
elif not self._reload_func():
2064
# The reload claimed that nothing changed
2065
if not retry_exc.reload_occurred:
2066
# If there wasn't an earlier reload, then we really were
2067
# expecting to find changes. We didn't find them, so this is a
2071
exc_class, exc_value, exc_traceback = retry_exc.exc_info
2072
raise exc_class, exc_value, exc_traceback
2201
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2202
"""A no-subtrees parameterized Pack repository.
2204
This format was introduced in 0.92.
2207
repository_class = KnitPackRepository
2208
_commit_builder_class = PackCommitBuilder
2209
_serializer = xml5.serializer_v5
2211
def _get_matching_bzrdir(self):
2212
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2214
def _ignore_setting_bzrdir(self, format):
2217
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2219
def get_format_string(self):
2220
"""See RepositoryFormat.get_format_string()."""
2221
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2223
def get_format_description(self):
2224
"""See RepositoryFormat.get_format_description()."""
2225
return "Packs containing knits without subtree support"
2227
def check_conversion_target(self, target_format):
2231
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2232
"""A subtrees parameterized Pack repository.
2234
This repository format uses the xml7 serializer to get:
2235
- support for recording full info about the tree root
2236
- support for recording tree-references
2238
This format was introduced in 0.92.
2241
repository_class = KnitPackRepository
2242
_commit_builder_class = PackRootCommitBuilder
2243
rich_root_data = True
2244
supports_tree_reference = True
2245
_serializer = xml7.serializer_v7
2247
def _get_matching_bzrdir(self):
2248
return bzrdir.format_registry.make_bzrdir(
2249
'pack-0.92-subtree')
2251
def _ignore_setting_bzrdir(self, format):
2254
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2256
def check_conversion_target(self, target_format):
2257
if not target_format.rich_root_data:
2258
raise errors.BadConversionTarget(
2259
'Does not support rich root data.', target_format)
2260
if not getattr(target_format, 'supports_tree_reference', False):
2261
raise errors.BadConversionTarget(
2262
'Does not support nested trees', target_format)
2264
def get_format_string(self):
2265
"""See RepositoryFormat.get_format_string()."""
2266
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2268
def get_format_description(self):
2269
"""See RepositoryFormat.get_format_description()."""
2270
return "Packs containing knits with subtree support\n"
2273
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2274
"""A rich-root, no subtrees parameterized Pack repository.
2276
This repository format uses the xml6 serializer to get:
2277
- support for recording full info about the tree root
2279
This format was introduced in 1.0.
2282
repository_class = KnitPackRepository
2283
_commit_builder_class = PackRootCommitBuilder
2284
rich_root_data = True
2285
supports_tree_reference = False
2286
_serializer = xml6.serializer_v6
2288
def _get_matching_bzrdir(self):
2289
return bzrdir.format_registry.make_bzrdir(
2292
def _ignore_setting_bzrdir(self, format):
2295
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2297
def check_conversion_target(self, target_format):
2298
if not target_format.rich_root_data:
2299
raise errors.BadConversionTarget(
2300
'Does not support rich root data.', target_format)
2302
def get_format_string(self):
2303
"""See RepositoryFormat.get_format_string()."""
2304
return ("Bazaar pack repository format 1 with rich root"
2305
" (needs bzr 1.0)\n")
2307
def get_format_description(self):
2308
"""See RepositoryFormat.get_format_description()."""
2309
return "Packs containing knits with rich root support\n"
2312
class RepositoryFormatPackDevelopment0(RepositoryFormatPack):
2313
"""A no-subtrees development repository.
2315
This format should be retained until the second release after bzr 1.0.
2317
No changes to the disk behaviour from pack-0.92.
2320
repository_class = KnitPackRepository
2321
_commit_builder_class = PackCommitBuilder
2322
_serializer = xml5.serializer_v5
2324
def _get_matching_bzrdir(self):
2325
return bzrdir.format_registry.make_bzrdir('development0')
2327
def _ignore_setting_bzrdir(self, format):
2330
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2332
def get_format_string(self):
2333
"""See RepositoryFormat.get_format_string()."""
2334
return "Bazaar development format 0 (needs bzr.dev from before 1.3)\n"
2336
def get_format_description(self):
2337
"""See RepositoryFormat.get_format_description()."""
2338
return ("Development repository format, currently the same as "
2341
def check_conversion_target(self, target_format):
2345
class RepositoryFormatPackDevelopment0Subtree(RepositoryFormatPack):
2346
"""A subtrees development repository.
2348
This format should be retained until the second release after bzr 1.0.
2350
No changes to the disk behaviour from pack-0.92-subtree.
2353
repository_class = KnitPackRepository
2354
_commit_builder_class = PackRootCommitBuilder
2355
rich_root_data = True
2356
supports_tree_reference = True
2357
_serializer = xml7.serializer_v7
2359
def _get_matching_bzrdir(self):
2360
return bzrdir.format_registry.make_bzrdir(
2361
'development0-subtree')
2363
def _ignore_setting_bzrdir(self, format):
2366
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2368
def check_conversion_target(self, target_format):
2369
if not target_format.rich_root_data:
2370
raise errors.BadConversionTarget(
2371
'Does not support rich root data.', target_format)
2372
if not getattr(target_format, 'supports_tree_reference', False):
2373
raise errors.BadConversionTarget(
2374
'Does not support nested trees', target_format)
2376
def get_format_string(self):
2377
"""See RepositoryFormat.get_format_string()."""
2378
return ("Bazaar development format 0 with subtree support "
2379
"(needs bzr.dev from before 1.3)\n")
2381
def get_format_description(self):
2382
"""See RepositoryFormat.get_format_description()."""
2383
return ("Development repository format, currently the same as "
2384
"pack-0.92-subtree\n")