732
804
Sets self._text_filter appropriately.
734
raise NotImplementedError(self._copy_inventory_texts)
806
# select inventory keys
807
inv_keys = self._revision_keys # currently the same keyspace, and note that
808
# querying for keys here could introduce a bug where an inventory item
809
# is missed, so do not change it to query separately without cross
810
# checking like the text key check below.
811
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
813
inv_nodes = self._index_contents(inventory_indices, inv_keys)
814
# copy inventory keys and adjust values
815
# XXX: Should be a helper function to allow different inv representation
817
self.pb.update("Copying inventory texts", 2)
818
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
819
# Only grab the output lines if we will be processing them
820
output_lines = bool(self.revision_ids)
821
inv_lines = self._copy_nodes_graph(inventory_index_map,
822
self.new_pack._writer, self.new_pack.inventory_index,
823
readv_group_iter, total_items, output_lines=output_lines)
824
if self.revision_ids:
825
self._process_inventory_lines(inv_lines)
827
# eat the iterator to cause it to execute.
829
self._text_filter = None
830
if 'pack' in debug.debug_flags:
831
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
832
time.ctime(), self._pack_collection._upload_transport.base,
833
self.new_pack.random_name,
834
self.new_pack.inventory_index.key_count(),
835
time.time() - self.new_pack.start_time)
736
837
def _copy_text_texts(self):
737
raise NotImplementedError(self._copy_text_texts)
839
text_index_map, text_nodes = self._get_text_nodes()
840
if self._text_filter is not None:
841
# We could return the keys copied as part of the return value from
842
# _copy_nodes_graph but this doesn't work all that well with the
843
# need to get line output too, so we check separately, and as we're
844
# going to buffer everything anyway, we check beforehand, which
845
# saves reading knit data over the wire when we know there are
847
text_nodes = set(text_nodes)
848
present_text_keys = set(_node[1] for _node in text_nodes)
849
missing_text_keys = set(self._text_filter) - present_text_keys
850
if missing_text_keys:
851
# TODO: raise a specific error that can handle many missing
853
mutter("missing keys during fetch: %r", missing_text_keys)
854
a_missing_key = missing_text_keys.pop()
855
raise errors.RevisionNotPresent(a_missing_key[1],
857
# copy text keys and adjust values
858
self.pb.update("Copying content texts", 3)
859
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
860
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
861
self.new_pack.text_index, readv_group_iter, total_items))
862
self._log_copied_texts()
739
864
def _create_pack_from_packs(self):
740
raise NotImplementedError(self._create_pack_from_packs)
865
self.pb.update("Opening pack", 0, 5)
866
self.new_pack = self.open_pack()
867
new_pack = self.new_pack
868
# buffer data - we won't be reading-back during the pack creation and
869
# this makes a significant difference on sftp pushes.
870
new_pack.set_write_cache_size(1024*1024)
871
if 'pack' in debug.debug_flags:
872
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
873
for a_pack in self.packs]
874
if self.revision_ids is not None:
875
rev_count = len(self.revision_ids)
878
mutter('%s: create_pack: creating pack from source packs: '
879
'%s%s %s revisions wanted %s t=0',
880
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
881
plain_pack_list, rev_count)
882
self._copy_revision_texts()
883
self._copy_inventory_texts()
884
self._copy_text_texts()
885
# select signature keys
886
signature_filter = self._revision_keys # same keyspace
887
signature_index_map, signature_indices = self._pack_map_and_index_list(
889
signature_nodes = self._index_contents(signature_indices,
891
# copy signature keys and adjust values
892
self.pb.update("Copying signature texts", 4)
893
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
894
new_pack.signature_index)
895
if 'pack' in debug.debug_flags:
896
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
897
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
898
new_pack.signature_index.key_count(),
899
time.time() - new_pack.start_time)
900
new_pack._check_references()
901
if not self._use_pack(new_pack):
904
self.pb.update("Finishing pack", 5)
906
self._pack_collection.allocate(new_pack)
909
def _copy_nodes(self, nodes, index_map, writer, write_index):
910
"""Copy knit nodes between packs with no graph references."""
911
pb = ui.ui_factory.nested_progress_bar()
913
return self._do_copy_nodes(nodes, index_map, writer,
918
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
919
# for record verification
920
knit = KnitVersionedFiles(None, None)
921
# plan a readv on each source pack:
923
nodes = sorted(nodes)
924
# how to map this into knit.py - or knit.py into this?
925
# we don't want the typical knit logic, we want grouping by pack
926
# at this point - perhaps a helper library for the following code
927
# duplication points?
929
for index, key, value in nodes:
930
if index not in request_groups:
931
request_groups[index] = []
932
request_groups[index].append((key, value))
934
pb.update("Copied record", record_index, len(nodes))
935
for index, items in request_groups.iteritems():
936
pack_readv_requests = []
937
for key, value in items:
938
# ---- KnitGraphIndex.get_position
939
bits = value[1:].split(' ')
940
offset, length = int(bits[0]), int(bits[1])
941
pack_readv_requests.append((offset, length, (key, value[0])))
942
# linear scan up the pack
943
pack_readv_requests.sort()
945
pack_obj = index_map[index]
946
transport, path = pack_obj.access_tuple()
948
reader = pack.make_readv_reader(transport, path,
949
[offset[0:2] for offset in pack_readv_requests])
950
except errors.NoSuchFile:
951
if self._reload_func is not None:
954
for (names, read_func), (_1, _2, (key, eol_flag)) in \
955
izip(reader.iter_records(), pack_readv_requests):
956
raw_data = read_func(None)
957
# check the header only
958
df, _ = knit._parse_record_header(key, raw_data)
960
pos, size = writer.add_bytes_record(raw_data, names)
961
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
962
pb.update("Copied record", record_index)
965
def _copy_nodes_graph(self, index_map, writer, write_index,
966
readv_group_iter, total_items, output_lines=False):
967
"""Copy knit nodes between packs.
969
:param output_lines: Return lines present in the copied data as
970
an iterator of line,version_id.
972
pb = ui.ui_factory.nested_progress_bar()
974
for result in self._do_copy_nodes_graph(index_map, writer,
975
write_index, output_lines, pb, readv_group_iter, total_items):
978
# Python 2.4 does not permit try:finally: in a generator.
984
def _do_copy_nodes_graph(self, index_map, writer, write_index,
985
output_lines, pb, readv_group_iter, total_items):
986
# for record verification
987
knit = KnitVersionedFiles(None, None)
988
# for line extraction when requested (inventories only)
990
factory = KnitPlainFactory()
992
pb.update("Copied record", record_index, total_items)
993
for index, readv_vector, node_vector in readv_group_iter:
995
pack_obj = index_map[index]
996
transport, path = pack_obj.access_tuple()
998
reader = pack.make_readv_reader(transport, path, readv_vector)
999
except errors.NoSuchFile:
1000
if self._reload_func is not None:
1003
for (names, read_func), (key, eol_flag, references) in \
1004
izip(reader.iter_records(), node_vector):
1005
raw_data = read_func(None)
1007
# read the entire thing
1008
content, _ = knit._parse_record(key[-1], raw_data)
1009
if len(references[-1]) == 0:
1010
line_iterator = factory.get_fulltext_content(content)
1012
line_iterator = factory.get_linedelta_content(content)
1013
for line in line_iterator:
1016
# check the header only
1017
df, _ = knit._parse_record_header(key, raw_data)
1019
pos, size = writer.add_bytes_record(raw_data, names)
1020
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1021
pb.update("Copied record", record_index)
1024
def _get_text_nodes(self):
1025
text_index_map, text_indices = self._pack_map_and_index_list(
1027
return text_index_map, self._index_contents(text_indices,
1030
def _least_readv_node_readv(self, nodes):
1031
"""Generate request groups for nodes using the least readv's.
1033
:param nodes: An iterable of graph index nodes.
1034
:return: Total node count and an iterator of the data needed to perform
1035
readvs to obtain the data for nodes. Each item yielded by the
1036
iterator is a tuple with:
1037
index, readv_vector, node_vector. readv_vector is a list ready to
1038
hand to the transport readv method, and node_vector is a list of
1039
(key, eol_flag, references) for the the node retrieved by the
1040
matching readv_vector.
1042
# group by pack so we do one readv per pack
1043
nodes = sorted(nodes)
1046
for index, key, value, references in nodes:
1047
if index not in request_groups:
1048
request_groups[index] = []
1049
request_groups[index].append((key, value, references))
1051
for index, items in request_groups.iteritems():
1052
pack_readv_requests = []
1053
for key, value, references in items:
1054
# ---- KnitGraphIndex.get_position
1055
bits = value[1:].split(' ')
1056
offset, length = int(bits[0]), int(bits[1])
1057
pack_readv_requests.append(
1058
((offset, length), (key, value[0], references)))
1059
# linear scan up the pack to maximum range combining.
1060
pack_readv_requests.sort()
1061
# split out the readv and the node data.
1062
pack_readv = [readv for readv, node in pack_readv_requests]
1063
node_vector = [node for readv, node in pack_readv_requests]
1064
result.append((index, pack_readv, node_vector))
1065
return total, result
742
1067
def _log_copied_texts(self):
743
1068
if 'pack' in debug.debug_flags:
756
1100
return new_pack.data_inserted()
1103
class OptimisingPacker(Packer):
1104
"""A packer which spends more time to create better disk layouts."""
1106
def _revision_node_readv(self, revision_nodes):
1107
"""Return the total revisions and the readv's to issue.
1109
This sort places revisions in topological order with the ancestors
1112
:param revision_nodes: The revision index contents for the packs being
1113
incorporated into the new pack.
1114
:return: As per _least_readv_node_readv.
1116
# build an ancestors dict
1119
for index, key, value, references in revision_nodes:
1120
ancestors[key] = references[0]
1121
by_key[key] = (index, value, references)
1122
order = tsort.topo_sort(ancestors)
1124
# Single IO is pathological, but it will work as a starting point.
1126
for key in reversed(order):
1127
index, value, references = by_key[key]
1128
# ---- KnitGraphIndex.get_position
1129
bits = value[1:].split(' ')
1130
offset, length = int(bits[0]), int(bits[1])
1132
(index, [(offset, length)], [(key, value[0], references)]))
1133
# TODO: combine requests in the same index that are in ascending order.
1134
return total, requests
1136
def open_pack(self):
1137
"""Open a pack for the pack we are creating."""
1138
new_pack = super(OptimisingPacker, self).open_pack()
1139
# Turn on the optimization flags for all the index builders.
1140
new_pack.revision_index.set_optimize(for_size=True)
1141
new_pack.inventory_index.set_optimize(for_size=True)
1142
new_pack.text_index.set_optimize(for_size=True)
1143
new_pack.signature_index.set_optimize(for_size=True)
1147
class ReconcilePacker(Packer):
1148
"""A packer which regenerates indices etc as it copies.
1150
This is used by ``bzr reconcile`` to cause parent text pointers to be
1154
def _extra_init(self):
1155
self._data_changed = False
1157
def _process_inventory_lines(self, inv_lines):
1158
"""Generate a text key reference map rather for reconciling with."""
1159
repo = self._pack_collection.repo
1160
refs = repo._find_text_key_references_from_xml_inventory_lines(
1162
self._text_refs = refs
1163
# during reconcile we:
1164
# - convert unreferenced texts to full texts
1165
# - correct texts which reference a text not copied to be full texts
1166
# - copy all others as-is but with corrected parents.
1167
# - so at this point we don't know enough to decide what becomes a full
1169
self._text_filter = None
1171
def _copy_text_texts(self):
1172
"""generate what texts we should have and then copy."""
1173
self.pb.update("Copying content texts", 3)
1174
# we have three major tasks here:
1175
# 1) generate the ideal index
1176
repo = self._pack_collection.repo
1177
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1178
_1, key, _2, refs in
1179
self.new_pack.revision_index.iter_all_entries()])
1180
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1181
# 2) generate a text_nodes list that contains all the deltas that can
1182
# be used as-is, with corrected parents.
1185
discarded_nodes = []
1186
NULL_REVISION = _mod_revision.NULL_REVISION
1187
text_index_map, text_nodes = self._get_text_nodes()
1188
for node in text_nodes:
1194
ideal_parents = tuple(ideal_index[node[1]])
1196
discarded_nodes.append(node)
1197
self._data_changed = True
1199
if ideal_parents == (NULL_REVISION,):
1201
if ideal_parents == node[3][0]:
1203
ok_nodes.append(node)
1204
elif ideal_parents[0:1] == node[3][0][0:1]:
1205
# the left most parent is the same, or there are no parents
1206
# today. Either way, we can preserve the representation as
1207
# long as we change the refs to be inserted.
1208
self._data_changed = True
1209
ok_nodes.append((node[0], node[1], node[2],
1210
(ideal_parents, node[3][1])))
1211
self._data_changed = True
1213
# Reinsert this text completely
1214
bad_texts.append((node[1], ideal_parents))
1215
self._data_changed = True
1216
# we're finished with some data.
1219
# 3) bulk copy the ok data
1220
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1221
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1222
self.new_pack.text_index, readv_group_iter, total_items))
1223
# 4) adhoc copy all the other texts.
1224
# We have to topologically insert all texts otherwise we can fail to
1225
# reconcile when parts of a single delta chain are preserved intact,
1226
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1227
# reinserted, and if d3 has incorrect parents it will also be
1228
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1229
# copied), so we will try to delta, but d2 is not currently able to be
1230
# extracted because it's basis d1 is not present. Topologically sorting
1231
# addresses this. The following generates a sort for all the texts that
1232
# are being inserted without having to reference the entire text key
1233
# space (we only topo sort the revisions, which is smaller).
1234
topo_order = tsort.topo_sort(ancestors)
1235
rev_order = dict(zip(topo_order, range(len(topo_order))))
1236
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1237
transaction = repo.get_transaction()
1238
file_id_index = GraphIndexPrefixAdapter(
1239
self.new_pack.text_index,
1241
add_nodes_callback=self.new_pack.text_index.add_nodes)
1242
data_access = _DirectPackAccess(
1243
{self.new_pack.text_index:self.new_pack.access_tuple()})
1244
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1245
self.new_pack.access_tuple())
1246
output_texts = KnitVersionedFiles(
1247
_KnitGraphIndex(self.new_pack.text_index,
1248
add_callback=self.new_pack.text_index.add_nodes,
1249
deltas=True, parents=True, is_locked=repo.is_locked),
1250
data_access=data_access, max_delta_chain=200)
1251
for key, parent_keys in bad_texts:
1252
# We refer to the new pack to delta data being output.
1253
# A possible improvement would be to catch errors on short reads
1254
# and only flush then.
1255
self.new_pack.flush()
1257
for parent_key in parent_keys:
1258
if parent_key[0] != key[0]:
1259
# Graph parents must match the fileid
1260
raise errors.BzrError('Mismatched key parent %r:%r' %
1262
parents.append(parent_key[1])
1263
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1264
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1265
output_texts.add_lines(key, parent_keys, text_lines,
1266
random_id=True, check_content=False)
1267
# 5) check that nothing inserted has a reference outside the keyspace.
1268
missing_text_keys = self.new_pack.text_index._external_references()
1269
if missing_text_keys:
1270
raise errors.BzrCheckError('Reference to missing compression parents %r'
1271
% (missing_text_keys,))
1272
self._log_copied_texts()
1274
def _use_pack(self, new_pack):
1275
"""Override _use_pack to check for reconcile having changed content."""
1276
# XXX: we might be better checking this at the copy time.
1277
original_inventory_keys = set()
1278
inv_index = self._pack_collection.inventory_index.combined_index
1279
for entry in inv_index.iter_all_entries():
1280
original_inventory_keys.add(entry[1])
1281
new_inventory_keys = set()
1282
for entry in new_pack.inventory_index.iter_all_entries():
1283
new_inventory_keys.add(entry[1])
1284
if new_inventory_keys != original_inventory_keys:
1285
self._data_changed = True
1286
return new_pack.data_inserted() and self._data_changed
759
1289
class RepositoryPackCollection(object):
760
1290
"""Management of packs within a repository.
762
1292
:ivar _names: map of {pack_name: (index_size,)}
766
resumed_pack_factory = None
767
normal_packer_class = None
768
optimising_packer_class = None
770
1295
def __init__(self, repo, transport, index_transport, upload_transport,
771
pack_transport, index_builder_class, index_class,
1296
pack_transport, index_builder_class, index_class):
773
1297
"""Create a new RepositoryPackCollection.
775
1299
:param transport: Addresses the repository base directory
1655
# These attributes are inherited from the Repository base class. Setting
1656
# them to None ensures that if the constructor is changed to not initialize
1657
# them, or a subclass fails to call the constructor, that an error will
1658
# occur rather than the system working but generating incorrect data.
1659
_commit_builder_class = None
1662
2039
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1664
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1665
self._commit_builder_class = _commit_builder_class
1666
self._serializer = _serializer
2041
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2042
_commit_builder_class, _serializer)
2043
index_transport = self._transport.clone('indices')
2044
self._pack_collection = RepositoryPackCollection(self, self._transport,
2046
self._transport.clone('upload'),
2047
self._transport.clone('packs'),
2048
_format.index_builder_class,
2049
_format.index_class)
2050
self.inventories = KnitVersionedFiles(
2051
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2052
add_callback=self._pack_collection.inventory_index.add_callback,
2053
deltas=True, parents=True, is_locked=self.is_locked),
2054
data_access=self._pack_collection.inventory_index.data_access,
2055
max_delta_chain=200)
2056
self.revisions = KnitVersionedFiles(
2057
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2058
add_callback=self._pack_collection.revision_index.add_callback,
2059
deltas=False, parents=True, is_locked=self.is_locked),
2060
data_access=self._pack_collection.revision_index.data_access,
2062
self.signatures = KnitVersionedFiles(
2063
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2064
add_callback=self._pack_collection.signature_index.add_callback,
2065
deltas=False, parents=False, is_locked=self.is_locked),
2066
data_access=self._pack_collection.signature_index.data_access,
2068
self.texts = KnitVersionedFiles(
2069
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2070
add_callback=self._pack_collection.text_index.add_callback,
2071
deltas=True, parents=True, is_locked=self.is_locked),
2072
data_access=self._pack_collection.text_index.data_access,
2073
max_delta_chain=200)
2074
# True when the repository object is 'write locked' (as opposed to the
2075
# physical lock only taken out around changes to the pack-names list.)
2076
# Another way to represent this would be a decorator around the control
2077
# files object that presents logical locks as physical ones - if this
2078
# gets ugly consider that alternative design. RBC 20071011
2079
self._write_lock_count = 0
2080
self._transaction = None
2082
self._reconcile_does_inventory_gc = True
1667
2083
self._reconcile_fixes_text_parents = True
1668
if self._format.supports_external_lookups:
1669
self._unstacked_provider = graph.CachingParentsProvider(
1670
self._make_parents_provider_unstacked())
1672
self._unstacked_provider = graph.CachingParentsProvider(self)
1673
self._unstacked_provider.disable_cache()
2084
self._reconcile_backsup_inventory = False
1676
def _all_revision_ids(self):
1677
"""See Repository.all_revision_ids()."""
1678
return [key[0] for key in self.revisions.keys()]
2086
def _warn_if_deprecated(self):
2087
# This class isn't deprecated, but one sub-format is
2088
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2089
from bzrlib import repository
2090
if repository._deprecation_warning_done:
2092
repository._deprecation_warning_done = True
2093
warning("Format %s for %s is deprecated - please use"
2094
" 'bzr upgrade --1.6.1-rich-root'"
2095
% (self._format, self.bzrdir.transport.base))
1680
2097
def _abort_write_group(self):
1681
self.revisions._index._key_dependencies.clear()
1682
2098
self._pack_collection._abort_write_group()
2100
def _find_inconsistent_revision_parents(self):
2101
"""Find revisions with incorrectly cached parents.
2103
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2104
parents-in-revision).
2106
if not self.is_locked():
2107
raise errors.ObjectNotLocked(self)
2108
pb = ui.ui_factory.nested_progress_bar()
2111
revision_nodes = self._pack_collection.revision_index \
2112
.combined_index.iter_all_entries()
2113
index_positions = []
2114
# Get the cached index values for all revisions, and also the location
2115
# in each index of the revision text so we can perform linear IO.
2116
for index, key, value, refs in revision_nodes:
2117
pos, length = value[1:].split(' ')
2118
index_positions.append((index, int(pos), key[0],
2119
tuple(parent[0] for parent in refs[0])))
2120
pb.update("Reading revision index", 0, 0)
2121
index_positions.sort()
2122
batch_count = len(index_positions) / 1000 + 1
2123
pb.update("Checking cached revision graph", 0, batch_count)
2124
for offset in xrange(batch_count):
2125
pb.update("Checking cached revision graph", offset)
2126
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
2129
rev_ids = [item[2] for item in to_query]
2130
revs = self.get_revisions(rev_ids)
2131
for revision, item in zip(revs, to_query):
2132
index_parents = item[3]
2133
rev_parents = tuple(revision.parent_ids)
2134
if index_parents != rev_parents:
2135
result.append((revision.revision_id, index_parents, rev_parents))
1684
2140
def _make_parents_provider(self):
1685
if not self._format.supports_external_lookups:
1686
return self._unstacked_provider
1687
return graph.StackedParentsProvider(_LazyListJoin(
1688
[self._unstacked_provider], self._fallback_repositories))
2141
return graph.CachingParentsProvider(self)
1690
2143
def _refresh_data(self):
1691
2144
if not self.is_locked():
1693
2146
self._pack_collection.reload_pack_names()
1694
self._unstacked_provider.disable_cache()
1695
self._unstacked_provider.enable_cache()
1697
2148
def _start_write_group(self):
1698
2149
self._pack_collection._start_write_group()
1700
2151
def _commit_write_group(self):
1701
hint = self._pack_collection._commit_write_group()
1702
self.revisions._index._key_dependencies.clear()
1703
# The commit may have added keys that were previously cached as
1704
# missing, so reset the cache.
1705
self._unstacked_provider.disable_cache()
1706
self._unstacked_provider.enable_cache()
2152
return self._pack_collection._commit_write_group()
1709
2154
def suspend_write_group(self):
1710
2155
# XXX check self._write_group is self.get_transaction()?
1711
2156
tokens = self._pack_collection._suspend_write_group()
1712
self.revisions._index._key_dependencies.clear()
1713
2157
self._write_group = None
1716
2160
def _resume_write_group(self, tokens):
1717
2161
self._start_write_group()
1719
self._pack_collection._resume_write_group(tokens)
1720
except errors.UnresumableWriteGroup:
1721
self._abort_write_group()
1723
for pack in self._pack_collection._resumed_packs:
1724
self.revisions._index.scan_unvalidated_index(pack.revision_index)
2162
self._pack_collection._resume_write_group(tokens)
1726
2164
def get_transaction(self):
1727
2165
if self._write_lock_count:
1910
2319
_serializer=self._serializer)
1913
class RetryPackOperations(errors.RetryWithNewPacks):
1914
"""Raised when we are packing and we find a missing file.
1916
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1917
code it should try again.
1920
internal_error = True
1922
_fmt = ("Pack files have changed, reload and try pack again."
1923
" context: %(context)s %(orig_error)s")
1926
class _DirectPackAccess(object):
1927
"""Access to data in one or more packs with less translation."""
1929
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1930
"""Create a _DirectPackAccess object.
1932
:param index_to_packs: A dict mapping index objects to the transport
1933
and file names for obtaining data.
1934
:param reload_func: A function to call if we determine that the pack
1935
files have moved and we need to reload our caches. See
1936
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1938
self._container_writer = None
1939
self._write_index = None
1940
self._indices = index_to_packs
1941
self._reload_func = reload_func
1942
self._flush_func = flush_func
1944
def add_raw_records(self, key_sizes, raw_data):
1945
"""Add raw knit bytes to a storage area.
1947
The data is spooled to the container writer in one bytes-record per
1950
:param sizes: An iterable of tuples containing the key and size of each
1952
:param raw_data: A bytestring containing the data.
1953
:return: A list of memos to retrieve the record later. Each memo is an
1954
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1955
length), where the index field is the write_index object supplied
1956
to the PackAccess object.
1958
if type(raw_data) is not str:
1959
raise AssertionError(
1960
'data must be plain bytes was %s' % type(raw_data))
1963
for key, size in key_sizes:
1964
p_offset, p_length = self._container_writer.add_bytes_record(
1965
raw_data[offset:offset+size], [])
1967
result.append((self._write_index, p_offset, p_length))
1971
"""Flush pending writes on this access object.
1973
This will flush any buffered writes to a NewPack.
1975
if self._flush_func is not None:
1978
def get_raw_records(self, memos_for_retrieval):
1979
"""Get the raw bytes for a records.
1981
:param memos_for_retrieval: An iterable containing the (index, pos,
1982
length) memo for retrieving the bytes. The Pack access method
1983
looks up the pack to use for a given record in its index_to_pack
1985
:return: An iterator over the bytes of the records.
1987
# first pass, group into same-index requests
1989
current_index = None
1990
for (index, offset, length) in memos_for_retrieval:
1991
if current_index == index:
1992
current_list.append((offset, length))
1994
if current_index is not None:
1995
request_lists.append((current_index, current_list))
1996
current_index = index
1997
current_list = [(offset, length)]
1998
# handle the last entry
1999
if current_index is not None:
2000
request_lists.append((current_index, current_list))
2001
for index, offsets in request_lists:
2003
transport, path = self._indices[index]
2005
# A KeyError here indicates that someone has triggered an index
2006
# reload, and this index has gone missing, we need to start
2008
if self._reload_func is None:
2009
# If we don't have a _reload_func there is nothing that can
2012
raise errors.RetryWithNewPacks(index,
2013
reload_occurred=True,
2014
exc_info=sys.exc_info())
2016
reader = pack.make_readv_reader(transport, path, offsets)
2017
for names, read_func in reader.iter_records():
2018
yield read_func(None)
2019
except errors.NoSuchFile:
2020
# A NoSuchFile error indicates that a pack file has gone
2021
# missing on disk, we need to trigger a reload, and start over.
2022
if self._reload_func is None:
2024
raise errors.RetryWithNewPacks(transport.abspath(path),
2025
reload_occurred=False,
2026
exc_info=sys.exc_info())
2028
def set_writer(self, writer, index, transport_packname):
2029
"""Set a writer to use for adding data."""
2030
if index is not None:
2031
self._indices[index] = transport_packname
2032
self._container_writer = writer
2033
self._write_index = index
2035
def reload_or_raise(self, retry_exc):
2036
"""Try calling the reload function, or re-raise the original exception.
2038
This should be called after _DirectPackAccess raises a
2039
RetryWithNewPacks exception. This function will handle the common logic
2040
of determining when the error is fatal versus being temporary.
2041
It will also make sure that the original exception is raised, rather
2042
than the RetryWithNewPacks exception.
2044
If this function returns, then the calling function should retry
2045
whatever operation was being performed. Otherwise an exception will
2048
:param retry_exc: A RetryWithNewPacks exception.
2051
if self._reload_func is None:
2053
elif not self._reload_func():
2054
# The reload claimed that nothing changed
2055
if not retry_exc.reload_occurred:
2056
# If there wasn't an earlier reload, then we really were
2057
# expecting to find changes. We didn't find them, so this is a
2061
exc_class, exc_value, exc_traceback = retry_exc.exc_info
2062
raise exc_class, exc_value, exc_traceback
2322
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2323
"""A no-subtrees parameterized Pack repository.
2325
This format was introduced in 0.92.
2328
repository_class = KnitPackRepository
2329
_commit_builder_class = PackCommitBuilder
2331
def _serializer(self):
2332
return xml5.serializer_v5
2333
# What index classes to use
2334
index_builder_class = InMemoryGraphIndex
2335
index_class = GraphIndex
2337
def _get_matching_bzrdir(self):
2338
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2340
def _ignore_setting_bzrdir(self, format):
2343
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2345
def get_format_string(self):
2346
"""See RepositoryFormat.get_format_string()."""
2347
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2349
def get_format_description(self):
2350
"""See RepositoryFormat.get_format_description()."""
2351
return "Packs containing knits without subtree support"
2353
def check_conversion_target(self, target_format):
2357
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2358
"""A subtrees parameterized Pack repository.
2360
This repository format uses the xml7 serializer to get:
2361
- support for recording full info about the tree root
2362
- support for recording tree-references
2364
This format was introduced in 0.92.
2367
repository_class = KnitPackRepository
2368
_commit_builder_class = PackRootCommitBuilder
2369
rich_root_data = True
2370
supports_tree_reference = True
2372
def _serializer(self):
2373
return xml7.serializer_v7
2374
# What index classes to use
2375
index_builder_class = InMemoryGraphIndex
2376
index_class = GraphIndex
2378
def _get_matching_bzrdir(self):
2379
return bzrdir.format_registry.make_bzrdir(
2380
'pack-0.92-subtree')
2382
def _ignore_setting_bzrdir(self, format):
2385
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2387
def check_conversion_target(self, target_format):
2388
if not target_format.rich_root_data:
2389
raise errors.BadConversionTarget(
2390
'Does not support rich root data.', target_format)
2391
if not getattr(target_format, 'supports_tree_reference', False):
2392
raise errors.BadConversionTarget(
2393
'Does not support nested trees', target_format)
2395
def get_format_string(self):
2396
"""See RepositoryFormat.get_format_string()."""
2397
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2399
def get_format_description(self):
2400
"""See RepositoryFormat.get_format_description()."""
2401
return "Packs containing knits with subtree support\n"
2404
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2405
"""A rich-root, no subtrees parameterized Pack repository.
2407
This repository format uses the xml6 serializer to get:
2408
- support for recording full info about the tree root
2410
This format was introduced in 1.0.
2413
repository_class = KnitPackRepository
2414
_commit_builder_class = PackRootCommitBuilder
2415
rich_root_data = True
2416
supports_tree_reference = False
2418
def _serializer(self):
2419
return xml6.serializer_v6
2420
# What index classes to use
2421
index_builder_class = InMemoryGraphIndex
2422
index_class = GraphIndex
2424
def _get_matching_bzrdir(self):
2425
return bzrdir.format_registry.make_bzrdir(
2428
def _ignore_setting_bzrdir(self, format):
2431
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2433
def check_conversion_target(self, target_format):
2434
if not target_format.rich_root_data:
2435
raise errors.BadConversionTarget(
2436
'Does not support rich root data.', target_format)
2438
def get_format_string(self):
2439
"""See RepositoryFormat.get_format_string()."""
2440
return ("Bazaar pack repository format 1 with rich root"
2441
" (needs bzr 1.0)\n")
2443
def get_format_description(self):
2444
"""See RepositoryFormat.get_format_description()."""
2445
return "Packs containing knits with rich root support\n"
2448
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2449
"""Repository that supports external references to allow stacking.
2453
Supports external lookups, which results in non-truncated ghosts after
2454
reconcile compared to pack-0.92 formats.
2457
repository_class = KnitPackRepository
2458
_commit_builder_class = PackCommitBuilder
2459
supports_external_lookups = True
2460
# What index classes to use
2461
index_builder_class = InMemoryGraphIndex
2462
index_class = GraphIndex
2465
def _serializer(self):
2466
return xml5.serializer_v5
2468
def _get_matching_bzrdir(self):
2469
return bzrdir.format_registry.make_bzrdir('1.6')
2471
def _ignore_setting_bzrdir(self, format):
2474
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2476
def get_format_string(self):
2477
"""See RepositoryFormat.get_format_string()."""
2478
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2480
def get_format_description(self):
2481
"""See RepositoryFormat.get_format_description()."""
2482
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2484
def check_conversion_target(self, target_format):
2488
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2489
"""A repository with rich roots and stacking.
2491
New in release 1.6.1.
2493
Supports stacking on other repositories, allowing data to be accessed
2494
without being stored locally.
2497
repository_class = KnitPackRepository
2498
_commit_builder_class = PackRootCommitBuilder
2499
rich_root_data = True
2500
supports_tree_reference = False # no subtrees
2501
supports_external_lookups = True
2502
# What index classes to use
2503
index_builder_class = InMemoryGraphIndex
2504
index_class = GraphIndex
2507
def _serializer(self):
2508
return xml6.serializer_v6
2510
def _get_matching_bzrdir(self):
2511
return bzrdir.format_registry.make_bzrdir(
2514
def _ignore_setting_bzrdir(self, format):
2517
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2519
def check_conversion_target(self, target_format):
2520
if not target_format.rich_root_data:
2521
raise errors.BadConversionTarget(
2522
'Does not support rich root data.', target_format)
2524
def get_format_string(self):
2525
"""See RepositoryFormat.get_format_string()."""
2526
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2528
def get_format_description(self):
2529
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2532
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2533
"""A repository with rich roots and external references.
2537
Supports external lookups, which results in non-truncated ghosts after
2538
reconcile compared to pack-0.92 formats.
2540
This format was deprecated because the serializer it uses accidentally
2541
supported subtrees, when the format was not intended to. This meant that
2542
someone could accidentally fetch from an incorrect repository.
2545
repository_class = KnitPackRepository
2546
_commit_builder_class = PackRootCommitBuilder
2547
rich_root_data = True
2548
supports_tree_reference = False # no subtrees
2550
supports_external_lookups = True
2551
# What index classes to use
2552
index_builder_class = InMemoryGraphIndex
2553
index_class = GraphIndex
2556
def _serializer(self):
2557
return xml7.serializer_v7
2559
def _get_matching_bzrdir(self):
2560
matching = bzrdir.format_registry.make_bzrdir(
2562
matching.repository_format = self
2565
def _ignore_setting_bzrdir(self, format):
2568
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2570
def check_conversion_target(self, target_format):
2571
if not target_format.rich_root_data:
2572
raise errors.BadConversionTarget(
2573
'Does not support rich root data.', target_format)
2575
def get_format_string(self):
2576
"""See RepositoryFormat.get_format_string()."""
2577
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2579
def get_format_description(self):
2580
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2584
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2585
"""A repository with stacking and btree indexes,
2586
without rich roots or subtrees.
2588
This is equivalent to pack-1.6 with B+Tree indices.
2591
repository_class = KnitPackRepository
2592
_commit_builder_class = PackCommitBuilder
2593
supports_external_lookups = True
2594
# What index classes to use
2595
index_builder_class = BTreeBuilder
2596
index_class = BTreeGraphIndex
2599
def _serializer(self):
2600
return xml5.serializer_v5
2602
def _get_matching_bzrdir(self):
2603
return bzrdir.format_registry.make_bzrdir('1.9')
2605
def _ignore_setting_bzrdir(self, format):
2608
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2610
def get_format_string(self):
2611
"""See RepositoryFormat.get_format_string()."""
2612
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2614
def get_format_description(self):
2615
"""See RepositoryFormat.get_format_description()."""
2616
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2618
def check_conversion_target(self, target_format):
2622
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2623
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2625
1.6-rich-root with B+Tree indices.
2628
repository_class = KnitPackRepository
2629
_commit_builder_class = PackRootCommitBuilder
2630
rich_root_data = True
2631
supports_tree_reference = False # no subtrees
2632
supports_external_lookups = True
2633
# What index classes to use
2634
index_builder_class = BTreeBuilder
2635
index_class = BTreeGraphIndex
2638
def _serializer(self):
2639
return xml6.serializer_v6
2641
def _get_matching_bzrdir(self):
2642
return bzrdir.format_registry.make_bzrdir(
2645
def _ignore_setting_bzrdir(self, format):
2648
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2650
def check_conversion_target(self, target_format):
2651
if not target_format.rich_root_data:
2652
raise errors.BadConversionTarget(
2653
'Does not support rich root data.', target_format)
2655
def get_format_string(self):
2656
"""See RepositoryFormat.get_format_string()."""
2657
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2659
def get_format_description(self):
2660
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2663
class RepositoryFormatPackDevelopment2(RepositoryFormatPack):
2664
"""A no-subtrees development repository.
2666
This format should be retained until the second release after bzr 1.7.
2668
This is pack-1.6.1 with B+Tree indices.
2671
repository_class = KnitPackRepository
2672
_commit_builder_class = PackCommitBuilder
2673
supports_external_lookups = True
2674
# What index classes to use
2675
index_builder_class = BTreeBuilder
2676
index_class = BTreeGraphIndex
2677
# Set to true to get the fast-commit code path tested until a really fast
2678
# format lands in trunk. Not actually fast in this format.
2682
def _serializer(self):
2683
return xml5.serializer_v5
2685
def _get_matching_bzrdir(self):
2686
return bzrdir.format_registry.make_bzrdir('development2')
2688
def _ignore_setting_bzrdir(self, format):
2691
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2693
def get_format_string(self):
2694
"""See RepositoryFormat.get_format_string()."""
2695
return "Bazaar development format 2 (needs bzr.dev from before 1.8)\n"
2697
def get_format_description(self):
2698
"""See RepositoryFormat.get_format_description()."""
2699
return ("Development repository format, currently the same as "
2700
"1.6.1 with B+Trees.\n")
2702
def check_conversion_target(self, target_format):
2706
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2707
"""A subtrees development repository.
2709
This format should be retained until the second release after bzr 1.7.
2711
1.6.1-subtree[as it might have been] with B+Tree indices.
2714
repository_class = KnitPackRepository
2715
_commit_builder_class = PackRootCommitBuilder
2716
rich_root_data = True
2717
supports_tree_reference = True
2718
supports_external_lookups = True
2719
# What index classes to use
2720
index_builder_class = BTreeBuilder
2721
index_class = BTreeGraphIndex
2724
def _serializer(self):
2725
return xml7.serializer_v7
2727
def _get_matching_bzrdir(self):
2728
return bzrdir.format_registry.make_bzrdir(
2729
'development2-subtree')
2731
def _ignore_setting_bzrdir(self, format):
2734
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2736
def check_conversion_target(self, target_format):
2737
if not target_format.rich_root_data:
2738
raise errors.BadConversionTarget(
2739
'Does not support rich root data.', target_format)
2740
if not getattr(target_format, 'supports_tree_reference', False):
2741
raise errors.BadConversionTarget(
2742
'Does not support nested trees', target_format)
2744
def get_format_string(self):
2745
"""See RepositoryFormat.get_format_string()."""
2746
return ("Bazaar development format 2 with subtree support "
2747
"(needs bzr.dev from before 1.8)\n")
2749
def get_format_description(self):
2750
"""See RepositoryFormat.get_format_description()."""
2751
return ("Development repository format, currently the same as "
2752
"1.6.1-subtree with B+Tree indices.\n")