256
199
return not self.__eq__(other)
258
201
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)
202
return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
203
id(self), self.pack_transport, self.name)
333
206
class NewPack(Pack):
334
207
"""An in memory proxy for a pack which is being created."""
336
def __init__(self, pack_collection, upload_suffix='', file_mode=None):
209
# A map of index 'type' to the file extension and position in the
211
index_definitions = {
212
'revision': ('.rix', 0),
213
'inventory': ('.iix', 1),
215
'signature': ('.six', 3),
218
def __init__(self, upload_transport, index_transport, pack_transport,
219
upload_suffix='', file_mode=None):
337
220
"""Create a NewPack instance.
339
:param pack_collection: A PackCollection into which this is being inserted.
222
:param upload_transport: A writable transport for the pack to be
223
incrementally uploaded to.
224
:param index_transport: A writable transport for the pack's indices to
225
be written to when the pack is finished.
226
:param pack_transport: A writable transport for the pack to be renamed
227
to when the upload is complete. This *must* be the same as
228
upload_transport.clone('../packs').
340
229
:param upload_suffix: An optional suffix to be given to any temporary
341
230
files created during the pack creation. e.g '.autopack'
342
:param file_mode: Unix permissions for newly created file.
231
:param file_mode: An optional file mode to create the new files with.
344
233
# The relative locations of the packs are constrained, but all are
345
234
# 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
235
Pack.__init__(self,
352
236
# Revisions: parents list, no text compression.
353
index_builder_class(reference_lists=1),
237
InMemoryGraphIndex(reference_lists=1),
354
238
# Inventory: We want to map compression only, but currently the
355
239
# knit code hasn't been updated enough to understand that, so we
356
240
# have a regular 2-list index giving parents and compression
358
index_builder_class(reference_lists=2),
242
InMemoryGraphIndex(reference_lists=2),
359
243
# Texts: compression and per file graph, for all fileids - so two
360
244
# reference lists and two elements in the key tuple.
361
index_builder_class(reference_lists=2, key_elements=2),
245
InMemoryGraphIndex(reference_lists=2, key_elements=2),
362
246
# 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.
248
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
250
# where should the new pack be opened
372
self.upload_transport = pack_collection._upload_transport
251
self.upload_transport = upload_transport
373
252
# where are indices written out to
374
self.index_transport = pack_collection._index_transport
253
self.index_transport = index_transport
375
254
# where is the pack renamed to when it is finished?
376
self.pack_transport = pack_collection._pack_transport
255
self.pack_transport = pack_transport
377
256
# What file mode to upload the pack and indices with.
378
257
self._file_mode = file_mode
379
258
# 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)
259
self._hash = md5.new()
260
# a four-tuple with the length in bytes of the indices, once the pack
261
# is finalised. (rev, inv, text, sigs)
383
262
self.index_sizes = None
384
263
# How much data to cache when writing packs. Note that this is not
385
264
# synchronised with reads, because it's not in the transport layer, so
741
626
Sets self._text_filter appropriately.
743
raise NotImplementedError(self._copy_inventory_texts)
628
# select inventory keys
629
inv_keys = self._revision_keys # currently the same keyspace, and note that
630
# querying for keys here could introduce a bug where an inventory item
631
# is missed, so do not change it to query separately without cross
632
# checking like the text key check below.
633
inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
634
self.packs, 'inventory_index')[0]
635
inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
636
# copy inventory keys and adjust values
637
# XXX: Should be a helper function to allow different inv representation
639
self.pb.update("Copying inventory texts", 2)
640
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
641
# Only grab the output lines if we will be processing them
642
output_lines = bool(self.revision_ids)
643
inv_lines = self._copy_nodes_graph(inventory_index_map,
644
self.new_pack._writer, self.new_pack.inventory_index,
645
readv_group_iter, total_items, output_lines=output_lines)
646
if self.revision_ids:
647
self._process_inventory_lines(inv_lines)
649
# eat the iterator to cause it to execute.
651
self._text_filter = None
652
if 'pack' in debug.debug_flags:
653
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
654
time.ctime(), self._pack_collection._upload_transport.base,
655
self.new_pack.random_name,
656
self.new_pack.inventory_index.key_count(),
657
time.time() - self.new_pack.start_time)
745
659
def _copy_text_texts(self):
746
raise NotImplementedError(self._copy_text_texts)
661
text_index_map, text_nodes = self._get_text_nodes()
662
if self._text_filter is not None:
663
# We could return the keys copied as part of the return value from
664
# _copy_nodes_graph but this doesn't work all that well with the
665
# need to get line output too, so we check separately, and as we're
666
# going to buffer everything anyway, we check beforehand, which
667
# saves reading knit data over the wire when we know there are
669
text_nodes = set(text_nodes)
670
present_text_keys = set(_node[1] for _node in text_nodes)
671
missing_text_keys = set(self._text_filter) - present_text_keys
672
if missing_text_keys:
673
# TODO: raise a specific error that can handle many missing
675
a_missing_key = missing_text_keys.pop()
676
raise errors.RevisionNotPresent(a_missing_key[1],
678
# copy text keys and adjust values
679
self.pb.update("Copying content texts", 3)
680
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
681
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
682
self.new_pack.text_index, readv_group_iter, total_items))
683
self._log_copied_texts()
685
def _check_references(self):
686
"""Make sure our external refereneces are present."""
687
external_refs = self.new_pack._external_compression_parents_of_texts()
689
index = self._pack_collection.text_index.combined_index
690
found_items = list(index.iter_entries(external_refs))
691
if len(found_items) != len(external_refs):
692
found_keys = set(k for idx, k, refs, value in found_items)
693
missing_items = external_refs - found_keys
694
missing_file_id, missing_revision_id = missing_items.pop()
695
raise errors.RevisionNotPresent(missing_revision_id,
748
698
def _create_pack_from_packs(self):
749
raise NotImplementedError(self._create_pack_from_packs)
699
self.pb.update("Opening pack", 0, 5)
700
self.new_pack = self.open_pack()
701
new_pack = self.new_pack
702
# buffer data - we won't be reading-back during the pack creation and
703
# this makes a significant difference on sftp pushes.
704
new_pack.set_write_cache_size(1024*1024)
705
if 'pack' in debug.debug_flags:
706
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
707
for a_pack in self.packs]
708
if self.revision_ids is not None:
709
rev_count = len(self.revision_ids)
712
mutter('%s: create_pack: creating pack from source packs: '
713
'%s%s %s revisions wanted %s t=0',
714
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
715
plain_pack_list, rev_count)
716
self._copy_revision_texts()
717
self._copy_inventory_texts()
718
self._copy_text_texts()
719
# select signature keys
720
signature_filter = self._revision_keys # same keyspace
721
signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
722
self.packs, 'signature_index')[0]
723
signature_nodes = self._pack_collection._index_contents(signature_index_map,
725
# copy signature keys and adjust values
726
self.pb.update("Copying signature texts", 4)
727
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
728
new_pack.signature_index)
729
if 'pack' in debug.debug_flags:
730
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
731
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
732
new_pack.signature_index.key_count(),
733
time.time() - new_pack.start_time)
734
self._check_references()
735
if not self._use_pack(new_pack):
738
self.pb.update("Finishing pack", 5)
740
self._pack_collection.allocate(new_pack)
743
def _copy_nodes(self, nodes, index_map, writer, write_index):
744
"""Copy knit nodes between packs with no graph references."""
745
pb = ui.ui_factory.nested_progress_bar()
747
return self._do_copy_nodes(nodes, index_map, writer,
752
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
753
# for record verification
754
knit = KnitVersionedFiles(None, None)
755
# plan a readv on each source pack:
757
nodes = sorted(nodes)
758
# how to map this into knit.py - or knit.py into this?
759
# we don't want the typical knit logic, we want grouping by pack
760
# at this point - perhaps a helper library for the following code
761
# duplication points?
763
for index, key, value in nodes:
764
if index not in request_groups:
765
request_groups[index] = []
766
request_groups[index].append((key, value))
768
pb.update("Copied record", record_index, len(nodes))
769
for index, items in request_groups.iteritems():
770
pack_readv_requests = []
771
for key, value in items:
772
# ---- KnitGraphIndex.get_position
773
bits = value[1:].split(' ')
774
offset, length = int(bits[0]), int(bits[1])
775
pack_readv_requests.append((offset, length, (key, value[0])))
776
# linear scan up the pack
777
pack_readv_requests.sort()
779
transport, path = index_map[index]
780
reader = pack.make_readv_reader(transport, path,
781
[offset[0:2] for offset in pack_readv_requests])
782
for (names, read_func), (_1, _2, (key, eol_flag)) in \
783
izip(reader.iter_records(), pack_readv_requests):
784
raw_data = read_func(None)
785
# check the header only
786
df, _ = knit._parse_record_header(key, raw_data)
788
pos, size = writer.add_bytes_record(raw_data, names)
789
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
790
pb.update("Copied record", record_index)
793
def _copy_nodes_graph(self, index_map, writer, write_index,
794
readv_group_iter, total_items, output_lines=False):
795
"""Copy knit nodes between packs.
797
:param output_lines: Return lines present in the copied data as
798
an iterator of line,version_id.
800
pb = ui.ui_factory.nested_progress_bar()
802
for result in self._do_copy_nodes_graph(index_map, writer,
803
write_index, output_lines, pb, readv_group_iter, total_items):
806
# Python 2.4 does not permit try:finally: in a generator.
812
def _do_copy_nodes_graph(self, index_map, writer, write_index,
813
output_lines, pb, readv_group_iter, total_items):
814
# for record verification
815
knit = KnitVersionedFiles(None, None)
816
# for line extraction when requested (inventories only)
818
factory = KnitPlainFactory()
820
pb.update("Copied record", record_index, total_items)
821
for index, readv_vector, node_vector in readv_group_iter:
823
transport, path = index_map[index]
824
reader = pack.make_readv_reader(transport, path, readv_vector)
825
for (names, read_func), (key, eol_flag, references) in \
826
izip(reader.iter_records(), node_vector):
827
raw_data = read_func(None)
829
# read the entire thing
830
content, _ = knit._parse_record(key[-1], raw_data)
831
if len(references[-1]) == 0:
832
line_iterator = factory.get_fulltext_content(content)
834
line_iterator = factory.get_linedelta_content(content)
835
for line in line_iterator:
838
# check the header only
839
df, _ = knit._parse_record_header(key, raw_data)
841
pos, size = writer.add_bytes_record(raw_data, names)
842
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
843
pb.update("Copied record", record_index)
846
def _get_text_nodes(self):
847
text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
848
self.packs, 'text_index')[0]
849
return text_index_map, self._pack_collection._index_contents(text_index_map,
852
def _least_readv_node_readv(self, nodes):
853
"""Generate request groups for nodes using the least readv's.
855
:param nodes: An iterable of graph index nodes.
856
:return: Total node count and an iterator of the data needed to perform
857
readvs to obtain the data for nodes. Each item yielded by the
858
iterator is a tuple with:
859
index, readv_vector, node_vector. readv_vector is a list ready to
860
hand to the transport readv method, and node_vector is a list of
861
(key, eol_flag, references) for the the node retrieved by the
862
matching readv_vector.
864
# group by pack so we do one readv per pack
865
nodes = sorted(nodes)
868
for index, key, value, references in nodes:
869
if index not in request_groups:
870
request_groups[index] = []
871
request_groups[index].append((key, value, references))
873
for index, items in request_groups.iteritems():
874
pack_readv_requests = []
875
for key, value, references in items:
876
# ---- KnitGraphIndex.get_position
877
bits = value[1:].split(' ')
878
offset, length = int(bits[0]), int(bits[1])
879
pack_readv_requests.append(
880
((offset, length), (key, value[0], references)))
881
# linear scan up the pack to maximum range combining.
882
pack_readv_requests.sort()
883
# split out the readv and the node data.
884
pack_readv = [readv for readv, node in pack_readv_requests]
885
node_vector = [node for readv, node in pack_readv_requests]
886
result.append((index, pack_readv, node_vector))
751
889
def _log_copied_texts(self):
752
890
if 'pack' in debug.debug_flags:
765
922
return new_pack.data_inserted()
925
class OptimisingPacker(Packer):
926
"""A packer which spends more time to create better disk layouts."""
928
def _revision_node_readv(self, revision_nodes):
929
"""Return the total revisions and the readv's to issue.
931
This sort places revisions in topological order with the ancestors
934
:param revision_nodes: The revision index contents for the packs being
935
incorporated into the new pack.
936
:return: As per _least_readv_node_readv.
938
# build an ancestors dict
941
for index, key, value, references in revision_nodes:
942
ancestors[key] = references[0]
943
by_key[key] = (index, value, references)
944
order = tsort.topo_sort(ancestors)
946
# Single IO is pathological, but it will work as a starting point.
948
for key in reversed(order):
949
index, value, references = by_key[key]
950
# ---- KnitGraphIndex.get_position
951
bits = value[1:].split(' ')
952
offset, length = int(bits[0]), int(bits[1])
954
(index, [(offset, length)], [(key, value[0], references)]))
955
# TODO: combine requests in the same index that are in ascending order.
956
return total, requests
959
class ReconcilePacker(Packer):
960
"""A packer which regenerates indices etc as it copies.
962
This is used by ``bzr reconcile`` to cause parent text pointers to be
966
def _extra_init(self):
967
self._data_changed = False
969
def _process_inventory_lines(self, inv_lines):
970
"""Generate a text key reference map rather for reconciling with."""
971
repo = self._pack_collection.repo
972
refs = repo._find_text_key_references_from_xml_inventory_lines(
974
self._text_refs = refs
975
# during reconcile we:
976
# - convert unreferenced texts to full texts
977
# - correct texts which reference a text not copied to be full texts
978
# - copy all others as-is but with corrected parents.
979
# - so at this point we don't know enough to decide what becomes a full
981
self._text_filter = None
983
def _copy_text_texts(self):
984
"""generate what texts we should have and then copy."""
985
self.pb.update("Copying content texts", 3)
986
# we have three major tasks here:
987
# 1) generate the ideal index
988
repo = self._pack_collection.repo
989
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
991
self.new_pack.revision_index.iter_all_entries()])
992
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
993
# 2) generate a text_nodes list that contains all the deltas that can
994
# be used as-is, with corrected parents.
998
NULL_REVISION = _mod_revision.NULL_REVISION
999
text_index_map, text_nodes = self._get_text_nodes()
1000
for node in text_nodes:
1006
ideal_parents = tuple(ideal_index[node[1]])
1008
discarded_nodes.append(node)
1009
self._data_changed = True
1011
if ideal_parents == (NULL_REVISION,):
1013
if ideal_parents == node[3][0]:
1015
ok_nodes.append(node)
1016
elif ideal_parents[0:1] == node[3][0][0:1]:
1017
# the left most parent is the same, or there are no parents
1018
# today. Either way, we can preserve the representation as
1019
# long as we change the refs to be inserted.
1020
self._data_changed = True
1021
ok_nodes.append((node[0], node[1], node[2],
1022
(ideal_parents, node[3][1])))
1023
self._data_changed = True
1025
# Reinsert this text completely
1026
bad_texts.append((node[1], ideal_parents))
1027
self._data_changed = True
1028
# we're finished with some data.
1031
# 3) bulk copy the ok data
1032
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1033
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1034
self.new_pack.text_index, readv_group_iter, total_items))
1035
# 4) adhoc copy all the other texts.
1036
# We have to topologically insert all texts otherwise we can fail to
1037
# reconcile when parts of a single delta chain are preserved intact,
1038
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1039
# reinserted, and if d3 has incorrect parents it will also be
1040
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1041
# copied), so we will try to delta, but d2 is not currently able to be
1042
# extracted because it's basis d1 is not present. Topologically sorting
1043
# addresses this. The following generates a sort for all the texts that
1044
# are being inserted without having to reference the entire text key
1045
# space (we only topo sort the revisions, which is smaller).
1046
topo_order = tsort.topo_sort(ancestors)
1047
rev_order = dict(zip(topo_order, range(len(topo_order))))
1048
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1049
transaction = repo.get_transaction()
1050
file_id_index = GraphIndexPrefixAdapter(
1051
self.new_pack.text_index,
1053
add_nodes_callback=self.new_pack.text_index.add_nodes)
1054
data_access = _DirectPackAccess(
1055
{self.new_pack.text_index:self.new_pack.access_tuple()})
1056
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1057
self.new_pack.access_tuple())
1058
output_texts = KnitVersionedFiles(
1059
_KnitGraphIndex(self.new_pack.text_index,
1060
add_callback=self.new_pack.text_index.add_nodes,
1061
deltas=True, parents=True, is_locked=repo.is_locked),
1062
data_access=data_access, max_delta_chain=200)
1063
for key, parent_keys in bad_texts:
1064
# We refer to the new pack to delta data being output.
1065
# A possible improvement would be to catch errors on short reads
1066
# and only flush then.
1067
self.new_pack.flush()
1069
for parent_key in parent_keys:
1070
if parent_key[0] != key[0]:
1071
# Graph parents must match the fileid
1072
raise errors.BzrError('Mismatched key parent %r:%r' %
1074
parents.append(parent_key[1])
1075
text_lines = split_lines(repo.texts.get_record_stream(
1076
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1077
output_texts.add_lines(key, parent_keys, text_lines,
1078
random_id=True, check_content=False)
1079
# 5) check that nothing inserted has a reference outside the keyspace.
1080
missing_text_keys = self.new_pack._external_compression_parents_of_texts()
1081
if missing_text_keys:
1082
raise errors.BzrError('Reference to missing compression parents %r'
1083
% (missing_text_keys,))
1084
self._log_copied_texts()
1086
def _use_pack(self, new_pack):
1087
"""Override _use_pack to check for reconcile having changed content."""
1088
# XXX: we might be better checking this at the copy time.
1089
original_inventory_keys = set()
1090
inv_index = self._pack_collection.inventory_index.combined_index
1091
for entry in inv_index.iter_all_entries():
1092
original_inventory_keys.add(entry[1])
1093
new_inventory_keys = set()
1094
for entry in new_pack.inventory_index.iter_all_entries():
1095
new_inventory_keys.add(entry[1])
1096
if new_inventory_keys != original_inventory_keys:
1097
self._data_changed = True
1098
return new_pack.data_inserted() and self._data_changed
768
1101
class RepositoryPackCollection(object):
769
1102
"""Management of packs within a repository.
771
1104
:ivar _names: map of {pack_name: (index_size,)}
775
resumed_pack_factory = None
776
normal_packer_class = None
777
optimising_packer_class = None
779
1107
def __init__(self, repo, transport, index_transport, upload_transport,
780
pack_transport, index_builder_class, index_class,
782
1109
"""Create a new RepositoryPackCollection.
784
:param transport: Addresses the repository base directory
1111
:param transport: Addresses the repository base directory
785
1112
(typically .bzr/repository/).
786
1113
:param index_transport: Addresses the directory containing indices.
787
1114
:param upload_transport: Addresses the directory into which packs are written
788
1115
while they're being created.
789
1116
: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
1118
self.repo = repo
796
1119
self.transport = transport
797
1120
self._index_transport = index_transport
798
1121
self._upload_transport = upload_transport
799
1122
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,
1123
self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
805
1125
# name:Pack mapping
807
1126
self._packs_by_name = {}
808
1127
# the previous pack-names content
809
1128
self._packs_at_load = None
810
1129
# when a pack is being created by this object, the state of that pack.
811
1130
self._new_pack = None
812
1131
# 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)
1132
self.revision_index = AggregateIndex()
1133
self.inventory_index = AggregateIndex()
1134
self.text_index = AggregateIndex()
1135
self.signature_index = AggregateIndex()
839
1137
def add_pack_to_memory(self, pack):
840
1138
"""Make a Pack object available to the repository to satisfy queries.
842
1140
:param pack: A Pack object.
844
1142
if pack.name in self._packs_by_name:
845
raise AssertionError(
846
'pack %s already in _packs_by_name' % (pack.name,))
1143
raise AssertionError()
847
1144
self.packs.append(pack)
848
1145
self._packs_by_name[pack.name] = pack
849
1146
self.revision_index.add_index(pack.revision_index, pack)
850
1147
self.inventory_index.add_index(pack.inventory_index, pack)
851
1148
self.text_index.add_index(pack.text_index, pack)
852
1149
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)
856
1151
def all_packs(self):
857
1152
"""Return a list of all the Pack objects this repository has.
908
1199
# group their data with the relevant commit, and that may
909
1200
# involve rewriting ancient history - which autopack tries to
910
1201
# avoid. Alternatively we could not group the data but treat
911
# each of these as having a single revision, and thus add
1202
# each of these as having a single revision, and thus add
912
1203
# one revision for each to the total revision count, to get
913
1204
# a matching distribution.
915
1206
existing_packs.append((revision_count, pack))
916
1207
pack_operations = self.plan_autopack_combinations(
917
1208
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)
1209
self._execute_pack_operations(pack_operations)
930
def _execute_pack_operations(self, pack_operations, packer_class,
1212
def _execute_pack_operations(self, pack_operations, _packer_class=Packer):
932
1213
"""Execute a series of pack operations.
934
1215
: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.
1216
:param _packer_class: The class of packer to use (default: Packer).
938
1219
for revision_count, packs in pack_operations:
939
1220
# we may have no-ops from the setup logic
940
1221
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()
1223
_packer_class(self, packs, '.autopack').pack()
956
1224
for pack in packs:
957
1225
self._remove_pack_from_memory(pack)
958
1226
# 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()
1228
self._save_pack_names(clear_obsolete_packs=True)
1229
# Move the old packs out of the way now they are no longer referenced.
1230
for revision_count, packs in pack_operations:
1231
self._obsolete_packs(packs)
971
1233
def lock_names(self):
972
1234
"""Acquire the mutex around the pack-names index.
974
1236
This cannot be used in the middle of a read-only transaction on the
977
1239
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
1242
"""Pack the pack collection totally."""
985
1243
self.ensure_loaded()
986
1244
total_packs = len(self._names)
987
if self._already_packed():
1246
# This is arguably wrong because we might not be optimal, but for
1247
# now lets leave it in. (e.g. reconcile -> one pack. But not
989
1250
total_revisions = self.revision_index.combined_index.key_count()
990
1251
# XXX: the following may want to be a class, to pack with a given
992
1253
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
1254
'containing %d revisions into 1 packs.', self, total_packs,
1009
1256
# determine which packs need changing
1257
pack_distribution = [1]
1010
1258
pack_operations = [[0, []]]
1011
1259
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)
1260
pack_operations[-1][0] += pack.get_revision_count()
1261
pack_operations[-1][1].append(pack)
1262
self._execute_pack_operations(pack_operations, OptimisingPacker)
1021
1264
def plan_autopack_combinations(self, existing_packs, pack_distribution):
1022
1265
"""Plan a pack operation.
1309
1468
self._packs_by_name = {}
1310
1469
self._packs_at_load = None
1471
def _make_index_map(self, index_suffix):
1472
"""Return information on existing indices.
1474
:param suffix: Index suffix added to pack name.
1476
:returns: (pack_map, indices) where indices is a list of GraphIndex
1477
objects, and pack_map is a mapping from those objects to the
1478
pack tuple they describe.
1480
# TODO: stop using this; it creates new indices unnecessarily.
1481
self.ensure_loaded()
1482
suffix_map = {'.rix': 'revision_index',
1483
'.six': 'signature_index',
1484
'.iix': 'inventory_index',
1485
'.tix': 'text_index',
1487
return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
1488
suffix_map[index_suffix])
1490
def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
1491
"""Convert a list of packs to an index pack map and index list.
1493
:param packs: The packs list to process.
1494
:param index_attribute: The attribute that the desired index is found
1496
:return: A tuple (map, list) where map contains the dict from
1497
index:pack_tuple, and lsit contains the indices in the same order
1503
index = getattr(pack, index_attribute)
1504
indices.append(index)
1505
pack_map[index] = (pack.pack_transport, pack.file_name())
1506
return pack_map, indices
1508
def _index_contents(self, pack_map, key_filter=None):
1509
"""Get an iterable of the index contents from a pack_map.
1511
:param pack_map: A map from indices to pack details.
1512
:param key_filter: An optional filter to limit the
1515
indices = [index for index in pack_map.iterkeys()]
1516
all_index = CombinedGraphIndex(indices)
1517
if key_filter is None:
1518
return all_index.iter_all_entries()
1520
return all_index.iter_entries(key_filter)
1312
1522
def _unlock_names(self):
1313
1523
"""Release the mutex around the pack-names index."""
1314
1524
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
1526
def _save_pack_names(self, clear_obsolete_packs=False):
1527
"""Save the list of packs.
1529
This will take out the mutex around the pack names list for the
1530
duration of the method call. If concurrent updates have been made, a
1531
three-way merge between the current list and the current in memory list
1534
:param clear_obsolete_packs: If True, clear out the contents of the
1535
obsolete_packs directory.
1539
builder = GraphIndexBuilder()
1540
# load the disk nodes across
1542
for index, key, value in self._iter_disk_pack_index():
1543
disk_nodes.add((key, value))
1544
# do a two-way diff against our original content
1545
current_nodes = set()
1546
for name, sizes in self._names.iteritems():
1548
((name, ), ' '.join(str(size) for size in sizes)))
1549
deleted_nodes = self._packs_at_load - current_nodes
1550
new_nodes = current_nodes - self._packs_at_load
1551
disk_nodes.difference_update(deleted_nodes)
1552
disk_nodes.update(new_nodes)
1553
# TODO: handle same-name, index-size-changes here -
1554
# e.g. use the value from disk, not ours, *unless* we're the one
1556
for key, value in disk_nodes:
1557
builder.add_node(key, value)
1558
self.transport.put_file('pack-names', builder.finish(),
1559
mode=self.repo.bzrdir._get_file_mode())
1560
# move the baseline forward
1561
self._packs_at_load = disk_nodes
1562
if clear_obsolete_packs:
1563
self._clear_obsolete_packs()
1565
self._unlock_names()
1566
# synchronise the memory packs list with what we just wrote:
1361
1567
new_names = dict(disk_nodes)
1362
1568
# drop no longer present nodes
1363
1569
for pack in self.all_packs():
1364
1570
if (pack.name,) not in new_names:
1365
removed.append(pack.name)
1366
1571
self._remove_pack_from_memory(pack)
1367
1572
# add new nodes/refresh existing ones
1368
1573
for key, value in disk_nodes:
1378
1583
# disk index because the set values are the same, unless
1379
1584
# the only index shows up as deleted by the set difference
1380
1585
# - which it may. Until there is a specific test for this,
1381
# assume it's broken. RBC 20071017.
1586
# assume its broken. RBC 20071017.
1382
1587
self._remove_pack_from_memory(self.get_pack_by_name(name))
1383
1588
self._names[name] = sizes
1384
1589
self.get_pack_by_name(name)
1385
modified.append(name)
1388
1592
self._names[name] = sizes
1389
1593
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):
1595
def _clear_obsolete_packs(self):
1488
1596
"""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
1598
obsolete_pack_transport = self.transport.clone('obsolete_packs')
1495
if preserve is None:
1497
1599
for filename in obsolete_pack_transport.list_dir('.'):
1498
name, ext = osutils.splitext(filename)
1501
if name in preserve:
1504
1601
obsolete_pack_transport.delete(filename)
1505
1602
except (errors.PathError, errors.TransportError), e:
1506
warning("couldn't delete obsolete pack, skipping it:\n%s"
1603
warning("couldn't delete obsolete pack, skipping it:\n%s" % (e,))
1510
1605
def _start_write_group(self):
1511
1606
# Do not permit preparation for writing if we're not in a 'write lock'.
1512
1607
if not self.repo.is_write_locked():
1513
1608
raise errors.NotWriteLocked(self)
1514
self._new_pack = self.pack_factory(self, upload_suffix='.pack',
1609
self._new_pack = NewPack(self._upload_transport, self._index_transport,
1610
self._pack_transport, upload_suffix='.pack',
1515
1611
file_mode=self.repo.bzrdir._get_file_mode())
1516
1612
# allow writing: queue writes to a new index
1517
1613
self.revision_index.add_writable_index(self._new_pack.revision_index,
1538
1628
# FIXME: just drop the transient index.
1539
1629
# forget what names there are
1540
1630
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
1631
self._new_pack.abort()
1632
self._remove_pack_indices(self._new_pack)
1633
self._new_pack = None
1634
self.repo._text_knit = None
1573
1636
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
1637
self._remove_pack_indices(self._new_pack)
1593
any_new_content = False
1594
1638
if self._new_pack.data_inserted():
1595
1639
# get all the data to disk and read to use
1596
1640
self._new_pack.finish()
1597
1641
self.allocate(self._new_pack)
1598
1642
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()
1643
if not self.autopack():
1615
1644
# 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
1646
self._save_pack_names()
1630
1648
self._new_pack.abort()
1631
1649
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):
1650
self.repo._text_knit = None
1653
class KnitPackRepository(KnitRepository):
1641
1654
"""Repository with knit objects stored inside pack containers.
1643
1656
The layering for a KnitPackRepository is:
1645
1658
Graph | HPSS | Repository public layer |
1646
1659
===================================================
1647
1660
Tuple based apis below, string based, and key based apis above
1648
1661
---------------------------------------------------
1650
1663
Provides .texts, .revisions etc
1651
1664
This adapts the N-tuple keys to physical knit records which only have a
1652
1665
single string identifier (for historical reasons), which in older formats
1659
1672
pack file. The GraphIndex layer works in N-tuples and is unaware of any
1660
1673
semantic value.
1661
1674
===================================================
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
1678
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
1680
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
1681
_commit_builder_class, _serializer)
1682
index_transport = self._transport.clone('indices')
1683
self._pack_collection = RepositoryPackCollection(self, self._transport,
1685
self._transport.clone('upload'),
1686
self._transport.clone('packs'))
1687
self.inventories = KnitVersionedFiles(
1688
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
1689
add_callback=self._pack_collection.inventory_index.add_callback,
1690
deltas=True, parents=True, is_locked=self.is_locked),
1691
data_access=self._pack_collection.inventory_index.data_access,
1692
max_delta_chain=200)
1693
self.revisions = KnitVersionedFiles(
1694
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
1695
add_callback=self._pack_collection.revision_index.add_callback,
1696
deltas=False, parents=True, is_locked=self.is_locked),
1697
data_access=self._pack_collection.revision_index.data_access,
1699
self.signatures = KnitVersionedFiles(
1700
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
1701
add_callback=self._pack_collection.signature_index.add_callback,
1702
deltas=False, parents=False, is_locked=self.is_locked),
1703
data_access=self._pack_collection.signature_index.data_access,
1705
self.texts = KnitVersionedFiles(
1706
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
1707
add_callback=self._pack_collection.text_index.add_callback,
1708
deltas=True, parents=True, is_locked=self.is_locked),
1709
data_access=self._pack_collection.text_index.data_access,
1710
max_delta_chain=200)
1711
# True when the repository object is 'write locked' (as opposed to the
1712
# physical lock only taken out around changes to the pack-names list.)
1713
# Another way to represent this would be a decorator around the control
1714
# files object that presents logical locks as physical ones - if this
1715
# gets ugly consider that alternative design. RBC 20071011
1716
self._write_lock_count = 0
1717
self._transaction = None
1719
self._reconcile_does_inventory_gc = True
1677
1720
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())
1682
self._unstacked_provider = graph.CachingParentsProvider(self)
1683
self._unstacked_provider.disable_cache()
1721
self._reconcile_backsup_inventory = False
1722
self._fetch_order = 'unordered'
1686
def _all_revision_ids(self):
1687
"""See Repository.all_revision_ids()."""
1688
return [key[0] for key in self.revisions.keys()]
1724
def _warn_if_deprecated(self):
1725
# This class isn't deprecated, but one sub-format is
1726
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
1727
from bzrlib import repository
1728
if repository._deprecation_warning_done:
1730
repository._deprecation_warning_done = True
1731
warning("Format %s for %s is deprecated - please use"
1732
" 'bzr upgrade --1.6.1-rich-root'"
1733
% (self._format, self.bzrdir.transport.base))
1690
1735
def _abort_write_group(self):
1691
self.revisions._index._key_dependencies.clear()
1692
1736
self._pack_collection._abort_write_group()
1738
def _find_inconsistent_revision_parents(self):
1739
"""Find revisions with incorrectly cached parents.
1741
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1742
parents-in-revision).
1744
if not self.is_locked():
1745
raise errors.ObjectNotLocked(self)
1746
pb = ui.ui_factory.nested_progress_bar()
1749
revision_nodes = self._pack_collection.revision_index \
1750
.combined_index.iter_all_entries()
1751
index_positions = []
1752
# Get the cached index values for all revisions, and also the location
1753
# in each index of the revision text so we can perform linear IO.
1754
for index, key, value, refs in revision_nodes:
1755
pos, length = value[1:].split(' ')
1756
index_positions.append((index, int(pos), key[0],
1757
tuple(parent[0] for parent in refs[0])))
1758
pb.update("Reading revision index.", 0, 0)
1759
index_positions.sort()
1760
batch_count = len(index_positions) / 1000 + 1
1761
pb.update("Checking cached revision graph.", 0, batch_count)
1762
for offset in xrange(batch_count):
1763
pb.update("Checking cached revision graph.", offset)
1764
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
1767
rev_ids = [item[2] for item in to_query]
1768
revs = self.get_revisions(rev_ids)
1769
for revision, item in zip(revs, to_query):
1770
index_parents = item[3]
1771
rev_parents = tuple(revision.parent_ids)
1772
if index_parents != rev_parents:
1773
result.append((revision.revision_id, index_parents, rev_parents))
1778
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
1779
def get_parents(self, revision_ids):
1780
"""See graph._StackedParentsProvider.get_parents."""
1781
parent_map = self.get_parent_map(revision_ids)
1782
return [parent_map.get(r, None) for r in revision_ids]
1694
1784
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))
1785
return graph.CachingParentsProvider(self)
1700
1787
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()
1788
if self._write_lock_count == 1 or (
1789
self.control_files._lock_count == 1 and
1790
self.control_files._lock_mode == 'r'):
1791
# forget what names there are
1792
self._pack_collection.reset()
1793
# XXX: Better to do an in-memory merge when acquiring a new lock -
1794
# factor out code from _save_pack_names.
1795
self._pack_collection.ensure_loaded()
1707
1797
def _start_write_group(self):
1708
1798
self._pack_collection._start_write_group()
1710
1800
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)
1801
return self._pack_collection._commit_write_group()
1736
1803
def get_transaction(self):
1737
1804
if self._write_lock_count:
1920
1947
_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
1950
class RepositoryFormatKnitPack1(RepositoryFormatPack):
1951
"""A no-subtrees parameterized Pack repository.
1953
This format was introduced in 0.92.
1956
repository_class = KnitPackRepository
1957
_commit_builder_class = PackCommitBuilder
1958
_serializer = xml5.serializer_v5
1960
def _get_matching_bzrdir(self):
1961
return bzrdir.format_registry.make_bzrdir('pack-0.92')
1963
def _ignore_setting_bzrdir(self, format):
1966
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
1968
def get_format_string(self):
1969
"""See RepositoryFormat.get_format_string()."""
1970
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
1972
def get_format_description(self):
1973
"""See RepositoryFormat.get_format_description()."""
1974
return "Packs containing knits without subtree support"
1976
def check_conversion_target(self, target_format):
1980
class RepositoryFormatKnitPack3(RepositoryFormatPack):
1981
"""A subtrees parameterized Pack repository.
1983
This repository format uses the xml7 serializer to get:
1984
- support for recording full info about the tree root
1985
- support for recording tree-references
1987
This format was introduced in 0.92.
1990
repository_class = KnitPackRepository
1991
_commit_builder_class = PackRootCommitBuilder
1992
rich_root_data = True
1993
supports_tree_reference = True
1994
_serializer = xml7.serializer_v7
1996
def _get_matching_bzrdir(self):
1997
return bzrdir.format_registry.make_bzrdir(
1998
'pack-0.92-subtree')
2000
def _ignore_setting_bzrdir(self, format):
2003
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2005
def check_conversion_target(self, target_format):
2006
if not target_format.rich_root_data:
2007
raise errors.BadConversionTarget(
2008
'Does not support rich root data.', target_format)
2009
if not getattr(target_format, 'supports_tree_reference', False):
2010
raise errors.BadConversionTarget(
2011
'Does not support nested trees', target_format)
2013
def get_format_string(self):
2014
"""See RepositoryFormat.get_format_string()."""
2015
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2017
def get_format_description(self):
2018
"""See RepositoryFormat.get_format_description()."""
2019
return "Packs containing knits with subtree support\n"
2022
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2023
"""A rich-root, no subtrees parameterized Pack repository.
2025
This repository format uses the xml6 serializer to get:
2026
- support for recording full info about the tree root
2028
This format was introduced in 1.0.
2031
repository_class = KnitPackRepository
2032
_commit_builder_class = PackRootCommitBuilder
2033
rich_root_data = True
2034
supports_tree_reference = False
2035
_serializer = xml6.serializer_v6
2037
def _get_matching_bzrdir(self):
2038
return bzrdir.format_registry.make_bzrdir(
2041
def _ignore_setting_bzrdir(self, format):
2044
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2046
def check_conversion_target(self, target_format):
2047
if not target_format.rich_root_data:
2048
raise errors.BadConversionTarget(
2049
'Does not support rich root data.', target_format)
2051
def get_format_string(self):
2052
"""See RepositoryFormat.get_format_string()."""
2053
return ("Bazaar pack repository format 1 with rich root"
2054
" (needs bzr 1.0)\n")
2056
def get_format_description(self):
2057
"""See RepositoryFormat.get_format_description()."""
2058
return "Packs containing knits with rich root support\n"
2061
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2062
"""Repository that supports external references to allow stacking.
2066
Supports external lookups, which results in non-truncated ghosts after
2067
reconcile compared to pack-0.92 formats.
2070
repository_class = KnitPackRepository
2071
_commit_builder_class = PackCommitBuilder
2072
_serializer = xml5.serializer_v5
2073
supports_external_lookups = True
2075
def _get_matching_bzrdir(self):
2076
return bzrdir.format_registry.make_bzrdir('development1')
2078
def _ignore_setting_bzrdir(self, format):
2081
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2083
def get_format_string(self):
2084
"""See RepositoryFormat.get_format_string()."""
2085
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2087
def get_format_description(self):
2088
"""See RepositoryFormat.get_format_description()."""
2089
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2091
def check_conversion_target(self, target_format):
2095
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2096
"""A repository with rich roots and stacking.
2098
New in release 1.6.1.
2100
Supports stacking on other repositories, allowing data to be accessed
2101
without being stored locally.
2104
repository_class = KnitPackRepository
2105
_commit_builder_class = PackRootCommitBuilder
2106
rich_root_data = True
2107
supports_tree_reference = False # no subtrees
2108
_serializer = xml6.serializer_v6
2109
supports_external_lookups = True
2111
def _get_matching_bzrdir(self):
2112
return bzrdir.format_registry.make_bzrdir(
2115
def _ignore_setting_bzrdir(self, format):
2118
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2120
def check_conversion_target(self, target_format):
2121
if not target_format.rich_root_data:
2122
raise errors.BadConversionTarget(
2123
'Does not support rich root data.', target_format)
2125
def get_format_string(self):
2126
"""See RepositoryFormat.get_format_string()."""
2127
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2129
def get_format_description(self):
2130
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2133
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2134
"""A repository with rich roots and external references.
2138
Supports external lookups, which results in non-truncated ghosts after
2139
reconcile compared to pack-0.92 formats.
2141
This format was deprecated because the serializer it uses accidentally
2142
supported subtrees, when the format was not intended to. This meant that
2143
someone could accidentally fetch from an incorrect repository.
2146
repository_class = KnitPackRepository
2147
_commit_builder_class = PackRootCommitBuilder
2148
rich_root_data = True
2149
supports_tree_reference = False # no subtrees
2150
_serializer = xml7.serializer_v7
2152
supports_external_lookups = True
2154
def _get_matching_bzrdir(self):
2155
return bzrdir.format_registry.make_bzrdir(
2156
'development1-subtree')
2158
def _ignore_setting_bzrdir(self, format):
2161
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2163
def check_conversion_target(self, target_format):
2164
if not target_format.rich_root_data:
2165
raise errors.BadConversionTarget(
2166
'Does not support rich root data.', target_format)
2168
def get_format_string(self):
2169
"""See RepositoryFormat.get_format_string()."""
2170
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2172
def get_format_description(self):
2173
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2177
class RepositoryFormatPackDevelopment1(RepositoryFormatPack):
2178
"""A no-subtrees development repository.
2180
This format should be retained until the second release after bzr 1.5.
2182
Supports external lookups, which results in non-truncated ghosts after
2183
reconcile compared to pack-0.92 formats.
2186
repository_class = KnitPackRepository
2187
_commit_builder_class = PackCommitBuilder
2188
_serializer = xml5.serializer_v5
2189
supports_external_lookups = True
2191
def _get_matching_bzrdir(self):
2192
return bzrdir.format_registry.make_bzrdir('development1')
2194
def _ignore_setting_bzrdir(self, format):
2197
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2199
def get_format_string(self):
2200
"""See RepositoryFormat.get_format_string()."""
2201
return "Bazaar development format 1 (needs bzr.dev from before 1.6)\n"
2203
def get_format_description(self):
2204
"""See RepositoryFormat.get_format_description()."""
2205
return ("Development repository format, currently the same as "
2206
"pack-0.92 with external reference support.\n")
2208
def check_conversion_target(self, target_format):
2212
class RepositoryFormatPackDevelopment1Subtree(RepositoryFormatPack):
2213
"""A subtrees development repository.
2215
This format should be retained until the second release after bzr 1.5.
2217
Supports external lookups, which results in non-truncated ghosts after
2218
reconcile compared to pack-0.92 formats.
2221
repository_class = KnitPackRepository
2222
_commit_builder_class = PackRootCommitBuilder
2223
rich_root_data = True
2224
supports_tree_reference = True
2225
_serializer = xml7.serializer_v7
2226
supports_external_lookups = True
2228
def _get_matching_bzrdir(self):
2229
return bzrdir.format_registry.make_bzrdir(
2230
'development1-subtree')
2232
def _ignore_setting_bzrdir(self, format):
2235
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2237
def check_conversion_target(self, target_format):
2238
if not target_format.rich_root_data:
2239
raise errors.BadConversionTarget(
2240
'Does not support rich root data.', target_format)
2241
if not getattr(target_format, 'supports_tree_reference', False):
2242
raise errors.BadConversionTarget(
2243
'Does not support nested trees', target_format)
2245
def get_format_string(self):
2246
"""See RepositoryFormat.get_format_string()."""
2247
return ("Bazaar development format 1 with subtree support "
2248
"(needs bzr.dev from before 1.6)\n")
2250
def get_format_description(self):
2251
"""See RepositoryFormat.get_format_description()."""
2252
return ("Development repository format, currently the same as "
2253
"pack-0.92-subtree with external reference support.\n")