827
743
Sets self._text_filter appropriately.
829
# select inventory keys
830
inv_keys = self._revision_keys # currently the same keyspace, and note that
831
# querying for keys here could introduce a bug where an inventory item
832
# is missed, so do not change it to query separately without cross
833
# checking like the text key check below.
834
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
836
inv_nodes = self._index_contents(inventory_indices, inv_keys)
837
# copy inventory keys and adjust values
838
# XXX: Should be a helper function to allow different inv representation
840
self.pb.update("Copying inventory texts", 2)
841
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
842
# Only grab the output lines if we will be processing them
843
output_lines = bool(self.revision_ids)
844
inv_lines = self._copy_nodes_graph(inventory_index_map,
845
self.new_pack._writer, self.new_pack.inventory_index,
846
readv_group_iter, total_items, output_lines=output_lines)
847
if self.revision_ids:
848
self._process_inventory_lines(inv_lines)
850
# eat the iterator to cause it to execute.
852
self._text_filter = None
853
if 'pack' in debug.debug_flags:
854
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
855
time.ctime(), self._pack_collection._upload_transport.base,
856
self.new_pack.random_name,
857
self.new_pack.inventory_index.key_count(),
858
time.time() - self.new_pack.start_time)
745
raise NotImplementedError(self._copy_inventory_texts)
860
747
def _copy_text_texts(self):
862
text_index_map, text_nodes = self._get_text_nodes()
863
if self._text_filter is not None:
864
# We could return the keys copied as part of the return value from
865
# _copy_nodes_graph but this doesn't work all that well with the
866
# need to get line output too, so we check separately, and as we're
867
# going to buffer everything anyway, we check beforehand, which
868
# saves reading knit data over the wire when we know there are
870
text_nodes = set(text_nodes)
871
present_text_keys = set(_node[1] for _node in text_nodes)
872
missing_text_keys = set(self._text_filter) - present_text_keys
873
if missing_text_keys:
874
# TODO: raise a specific error that can handle many missing
876
mutter("missing keys during fetch: %r", missing_text_keys)
877
a_missing_key = missing_text_keys.pop()
878
raise errors.RevisionNotPresent(a_missing_key[1],
880
# copy text keys and adjust values
881
self.pb.update("Copying content texts", 3)
882
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
883
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
884
self.new_pack.text_index, readv_group_iter, total_items))
885
self._log_copied_texts()
748
raise NotImplementedError(self._copy_text_texts)
887
750
def _create_pack_from_packs(self):
888
self.pb.update("Opening pack", 0, 5)
889
self.new_pack = self.open_pack()
890
new_pack = self.new_pack
891
# buffer data - we won't be reading-back during the pack creation and
892
# this makes a significant difference on sftp pushes.
893
new_pack.set_write_cache_size(1024*1024)
894
if 'pack' in debug.debug_flags:
895
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
896
for a_pack in self.packs]
897
if self.revision_ids is not None:
898
rev_count = len(self.revision_ids)
901
mutter('%s: create_pack: creating pack from source packs: '
902
'%s%s %s revisions wanted %s t=0',
903
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
904
plain_pack_list, rev_count)
905
self._copy_revision_texts()
906
self._copy_inventory_texts()
907
self._copy_text_texts()
908
# select signature keys
909
signature_filter = self._revision_keys # same keyspace
910
signature_index_map, signature_indices = self._pack_map_and_index_list(
912
signature_nodes = self._index_contents(signature_indices,
914
# copy signature keys and adjust values
915
self.pb.update("Copying signature texts", 4)
916
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
917
new_pack.signature_index)
918
if 'pack' in debug.debug_flags:
919
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
920
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
921
new_pack.signature_index.key_count(),
922
time.time() - new_pack.start_time)
924
# NB XXX: how to check CHK references are present? perhaps by yielding
925
# the items? How should that interact with stacked repos?
926
if new_pack.chk_index is not None:
928
if 'pack' in debug.debug_flags:
929
mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
930
time.ctime(), self._pack_collection._upload_transport.base,
931
new_pack.random_name,
932
new_pack.chk_index.key_count(),
933
time.time() - new_pack.start_time)
934
new_pack._check_references()
935
if not self._use_pack(new_pack):
938
self.pb.update("Finishing pack", 5)
940
self._pack_collection.allocate(new_pack)
943
def _copy_chks(self, refs=None):
944
# XXX: Todo, recursive follow-pointers facility when fetching some
946
chk_index_map, chk_indices = self._pack_map_and_index_list(
948
chk_nodes = self._index_contents(chk_indices, refs)
950
# TODO: This isn't strictly tasteful as we are accessing some private
951
# variables (_serializer). Perhaps a better way would be to have
952
# Repository._deserialise_chk_node()
953
search_key_func = chk_map.search_key_registry.get(
954
self._pack_collection.repo._serializer.search_key_name)
955
def accumlate_refs(lines):
956
# XXX: move to a generic location
958
bytes = ''.join(lines)
959
node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
960
new_refs.update(node.refs())
961
self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
962
self.new_pack.chk_index, output_lines=accumlate_refs)
965
def _copy_nodes(self, nodes, index_map, writer, write_index,
967
"""Copy knit nodes between packs with no graph references.
969
:param output_lines: Output full texts of copied items.
971
pb = ui.ui_factory.nested_progress_bar()
973
return self._do_copy_nodes(nodes, index_map, writer,
974
write_index, pb, output_lines=output_lines)
978
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
980
# for record verification
981
knit = KnitVersionedFiles(None, None)
982
# plan a readv on each source pack:
984
nodes = sorted(nodes)
985
# how to map this into knit.py - or knit.py into this?
986
# we don't want the typical knit logic, we want grouping by pack
987
# at this point - perhaps a helper library for the following code
988
# duplication points?
990
for index, key, value in nodes:
991
if index not in request_groups:
992
request_groups[index] = []
993
request_groups[index].append((key, value))
995
pb.update("Copied record", record_index, len(nodes))
996
for index, items in request_groups.iteritems():
997
pack_readv_requests = []
998
for key, value in items:
999
# ---- KnitGraphIndex.get_position
1000
bits = value[1:].split(' ')
1001
offset, length = int(bits[0]), int(bits[1])
1002
pack_readv_requests.append((offset, length, (key, value[0])))
1003
# linear scan up the pack
1004
pack_readv_requests.sort()
1006
pack_obj = index_map[index]
1007
transport, path = pack_obj.access_tuple()
1009
reader = pack.make_readv_reader(transport, path,
1010
[offset[0:2] for offset in pack_readv_requests])
1011
except errors.NoSuchFile:
1012
if self._reload_func is not None:
1015
for (names, read_func), (_1, _2, (key, eol_flag)) in \
1016
izip(reader.iter_records(), pack_readv_requests):
1017
raw_data = read_func(None)
1018
# check the header only
1019
if output_lines is not None:
1020
output_lines(knit._parse_record(key[-1], raw_data)[0])
1022
df, _ = knit._parse_record_header(key, raw_data)
1024
pos, size = writer.add_bytes_record(raw_data, names)
1025
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1026
pb.update("Copied record", record_index)
1029
def _copy_nodes_graph(self, index_map, writer, write_index,
1030
readv_group_iter, total_items, output_lines=False):
1031
"""Copy knit nodes between packs.
1033
:param output_lines: Return lines present in the copied data as
1034
an iterator of line,version_id.
1036
pb = ui.ui_factory.nested_progress_bar()
1038
for result in self._do_copy_nodes_graph(index_map, writer,
1039
write_index, output_lines, pb, readv_group_iter, total_items):
1042
# Python 2.4 does not permit try:finally: in a generator.
1048
def _do_copy_nodes_graph(self, index_map, writer, write_index,
1049
output_lines, pb, readv_group_iter, total_items):
1050
# for record verification
1051
knit = KnitVersionedFiles(None, None)
1052
# for line extraction when requested (inventories only)
1054
factory = KnitPlainFactory()
1056
pb.update("Copied record", record_index, total_items)
1057
for index, readv_vector, node_vector in readv_group_iter:
1059
pack_obj = index_map[index]
1060
transport, path = pack_obj.access_tuple()
1062
reader = pack.make_readv_reader(transport, path, readv_vector)
1063
except errors.NoSuchFile:
1064
if self._reload_func is not None:
1067
for (names, read_func), (key, eol_flag, references) in \
1068
izip(reader.iter_records(), node_vector):
1069
raw_data = read_func(None)
1071
# read the entire thing
1072
content, _ = knit._parse_record(key[-1], raw_data)
1073
if len(references[-1]) == 0:
1074
line_iterator = factory.get_fulltext_content(content)
1076
line_iterator = factory.get_linedelta_content(content)
1077
for line in line_iterator:
1080
# check the header only
1081
df, _ = knit._parse_record_header(key, raw_data)
1083
pos, size = writer.add_bytes_record(raw_data, names)
1084
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1085
pb.update("Copied record", record_index)
1088
def _get_text_nodes(self):
1089
text_index_map, text_indices = self._pack_map_and_index_list(
1091
return text_index_map, self._index_contents(text_indices,
1094
def _least_readv_node_readv(self, nodes):
1095
"""Generate request groups for nodes using the least readv's.
1097
:param nodes: An iterable of graph index nodes.
1098
:return: Total node count and an iterator of the data needed to perform
1099
readvs to obtain the data for nodes. Each item yielded by the
1100
iterator is a tuple with:
1101
index, readv_vector, node_vector. readv_vector is a list ready to
1102
hand to the transport readv method, and node_vector is a list of
1103
(key, eol_flag, references) for the node retrieved by the
1104
matching readv_vector.
1106
# group by pack so we do one readv per pack
1107
nodes = sorted(nodes)
1110
for index, key, value, references in nodes:
1111
if index not in request_groups:
1112
request_groups[index] = []
1113
request_groups[index].append((key, value, references))
1115
for index, items in request_groups.iteritems():
1116
pack_readv_requests = []
1117
for key, value, references in items:
1118
# ---- KnitGraphIndex.get_position
1119
bits = value[1:].split(' ')
1120
offset, length = int(bits[0]), int(bits[1])
1121
pack_readv_requests.append(
1122
((offset, length), (key, value[0], references)))
1123
# linear scan up the pack to maximum range combining.
1124
pack_readv_requests.sort()
1125
# split out the readv and the node data.
1126
pack_readv = [readv for readv, node in pack_readv_requests]
1127
node_vector = [node for readv, node in pack_readv_requests]
1128
result.append((index, pack_readv, node_vector))
1129
return total, result
751
raise NotImplementedError(self._create_pack_from_packs)
1131
753
def _log_copied_texts(self):
1132
754
if 'pack' in debug.debug_flags:
1164
767
return new_pack.data_inserted()
1167
class OptimisingPacker(Packer):
1168
"""A packer which spends more time to create better disk layouts."""
1170
def _revision_node_readv(self, revision_nodes):
1171
"""Return the total revisions and the readv's to issue.
1173
This sort places revisions in topological order with the ancestors
1176
:param revision_nodes: The revision index contents for the packs being
1177
incorporated into the new pack.
1178
:return: As per _least_readv_node_readv.
1180
# build an ancestors dict
1183
for index, key, value, references in revision_nodes:
1184
ancestors[key] = references[0]
1185
by_key[key] = (index, value, references)
1186
order = tsort.topo_sort(ancestors)
1188
# Single IO is pathological, but it will work as a starting point.
1190
for key in reversed(order):
1191
index, value, references = by_key[key]
1192
# ---- KnitGraphIndex.get_position
1193
bits = value[1:].split(' ')
1194
offset, length = int(bits[0]), int(bits[1])
1196
(index, [(offset, length)], [(key, value[0], references)]))
1197
# TODO: combine requests in the same index that are in ascending order.
1198
return total, requests
1200
def open_pack(self):
1201
"""Open a pack for the pack we are creating."""
1202
new_pack = super(OptimisingPacker, self).open_pack()
1203
# Turn on the optimization flags for all the index builders.
1204
new_pack.revision_index.set_optimize(for_size=True)
1205
new_pack.inventory_index.set_optimize(for_size=True)
1206
new_pack.text_index.set_optimize(for_size=True)
1207
new_pack.signature_index.set_optimize(for_size=True)
1211
class ReconcilePacker(Packer):
1212
"""A packer which regenerates indices etc as it copies.
1214
This is used by ``bzr reconcile`` to cause parent text pointers to be
1218
def _extra_init(self):
1219
self._data_changed = False
1221
def _process_inventory_lines(self, inv_lines):
1222
"""Generate a text key reference map rather for reconciling with."""
1223
repo = self._pack_collection.repo
1224
refs = repo._find_text_key_references_from_xml_inventory_lines(
1226
self._text_refs = refs
1227
# during reconcile we:
1228
# - convert unreferenced texts to full texts
1229
# - correct texts which reference a text not copied to be full texts
1230
# - copy all others as-is but with corrected parents.
1231
# - so at this point we don't know enough to decide what becomes a full
1233
self._text_filter = None
1235
def _copy_text_texts(self):
1236
"""generate what texts we should have and then copy."""
1237
self.pb.update("Copying content texts", 3)
1238
# we have three major tasks here:
1239
# 1) generate the ideal index
1240
repo = self._pack_collection.repo
1241
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1242
_1, key, _2, refs in
1243
self.new_pack.revision_index.iter_all_entries()])
1244
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1245
# 2) generate a text_nodes list that contains all the deltas that can
1246
# be used as-is, with corrected parents.
1249
discarded_nodes = []
1250
NULL_REVISION = _mod_revision.NULL_REVISION
1251
text_index_map, text_nodes = self._get_text_nodes()
1252
for node in text_nodes:
1258
ideal_parents = tuple(ideal_index[node[1]])
1260
discarded_nodes.append(node)
1261
self._data_changed = True
1263
if ideal_parents == (NULL_REVISION,):
1265
if ideal_parents == node[3][0]:
1267
ok_nodes.append(node)
1268
elif ideal_parents[0:1] == node[3][0][0:1]:
1269
# the left most parent is the same, or there are no parents
1270
# today. Either way, we can preserve the representation as
1271
# long as we change the refs to be inserted.
1272
self._data_changed = True
1273
ok_nodes.append((node[0], node[1], node[2],
1274
(ideal_parents, node[3][1])))
1275
self._data_changed = True
1277
# Reinsert this text completely
1278
bad_texts.append((node[1], ideal_parents))
1279
self._data_changed = True
1280
# we're finished with some data.
1283
# 3) bulk copy the ok data
1284
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1285
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1286
self.new_pack.text_index, readv_group_iter, total_items))
1287
# 4) adhoc copy all the other texts.
1288
# We have to topologically insert all texts otherwise we can fail to
1289
# reconcile when parts of a single delta chain are preserved intact,
1290
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1291
# reinserted, and if d3 has incorrect parents it will also be
1292
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1293
# copied), so we will try to delta, but d2 is not currently able to be
1294
# extracted because it's basis d1 is not present. Topologically sorting
1295
# addresses this. The following generates a sort for all the texts that
1296
# are being inserted without having to reference the entire text key
1297
# space (we only topo sort the revisions, which is smaller).
1298
topo_order = tsort.topo_sort(ancestors)
1299
rev_order = dict(zip(topo_order, range(len(topo_order))))
1300
bad_texts.sort(key=lambda key:rev_order.get(key[0][1], 0))
1301
transaction = repo.get_transaction()
1302
file_id_index = GraphIndexPrefixAdapter(
1303
self.new_pack.text_index,
1305
add_nodes_callback=self.new_pack.text_index.add_nodes)
1306
data_access = _DirectPackAccess(
1307
{self.new_pack.text_index:self.new_pack.access_tuple()})
1308
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1309
self.new_pack.access_tuple())
1310
output_texts = KnitVersionedFiles(
1311
_KnitGraphIndex(self.new_pack.text_index,
1312
add_callback=self.new_pack.text_index.add_nodes,
1313
deltas=True, parents=True, is_locked=repo.is_locked),
1314
data_access=data_access, max_delta_chain=200)
1315
for key, parent_keys in bad_texts:
1316
# We refer to the new pack to delta data being output.
1317
# A possible improvement would be to catch errors on short reads
1318
# and only flush then.
1319
self.new_pack.flush()
1321
for parent_key in parent_keys:
1322
if parent_key[0] != key[0]:
1323
# Graph parents must match the fileid
1324
raise errors.BzrError('Mismatched key parent %r:%r' %
1326
parents.append(parent_key[1])
1327
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1328
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1329
output_texts.add_lines(key, parent_keys, text_lines,
1330
random_id=True, check_content=False)
1331
# 5) check that nothing inserted has a reference outside the keyspace.
1332
missing_text_keys = self.new_pack.text_index._external_references()
1333
if missing_text_keys:
1334
raise errors.BzrCheckError('Reference to missing compression parents %r'
1335
% (missing_text_keys,))
1336
self._log_copied_texts()
1338
def _use_pack(self, new_pack):
1339
"""Override _use_pack to check for reconcile having changed content."""
1340
# XXX: we might be better checking this at the copy time.
1341
original_inventory_keys = set()
1342
inv_index = self._pack_collection.inventory_index.combined_index
1343
for entry in inv_index.iter_all_entries():
1344
original_inventory_keys.add(entry[1])
1345
new_inventory_keys = set()
1346
for entry in new_pack.inventory_index.iter_all_entries():
1347
new_inventory_keys.add(entry[1])
1348
if new_inventory_keys != original_inventory_keys:
1349
self._data_changed = True
1350
return new_pack.data_inserted() and self._data_changed
1353
770
class RepositoryPackCollection(object):
1354
771
"""Management of packs within a repository.
1356
773
:ivar _names: map of {pack_name: (index_size,)}
1359
pack_factory = NewPack
1360
resumed_pack_factory = ResumedPack
777
resumed_pack_factory = None
778
normal_packer_class = None
779
optimising_packer_class = None
1362
781
def __init__(self, repo, transport, index_transport, upload_transport,
1363
782
pack_transport, index_builder_class, index_class,
1681
# These attributes are inherited from the Repository base class. Setting
1682
# them to None ensures that if the constructor is changed to not initialize
1683
# them, or a subclass fails to call the constructor, that an error will
1684
# occur rather than the system working but generating incorrect data.
1685
_commit_builder_class = None
2218
1688
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2220
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2221
_commit_builder_class, _serializer)
2222
index_transport = self._transport.clone('indices')
2223
self._pack_collection = RepositoryPackCollection(self, self._transport,
2225
self._transport.clone('upload'),
2226
self._transport.clone('packs'),
2227
_format.index_builder_class,
2228
_format.index_class,
2229
use_chk_index=self._format.supports_chks,
2231
self.inventories = KnitVersionedFiles(
2232
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2233
add_callback=self._pack_collection.inventory_index.add_callback,
2234
deltas=True, parents=True, is_locked=self.is_locked),
2235
data_access=self._pack_collection.inventory_index.data_access,
2236
max_delta_chain=200)
2237
self.revisions = KnitVersionedFiles(
2238
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2239
add_callback=self._pack_collection.revision_index.add_callback,
2240
deltas=False, parents=True, is_locked=self.is_locked,
2241
track_external_parent_refs=True),
2242
data_access=self._pack_collection.revision_index.data_access,
2244
self.signatures = KnitVersionedFiles(
2245
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2246
add_callback=self._pack_collection.signature_index.add_callback,
2247
deltas=False, parents=False, is_locked=self.is_locked),
2248
data_access=self._pack_collection.signature_index.data_access,
2250
self.texts = KnitVersionedFiles(
2251
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2252
add_callback=self._pack_collection.text_index.add_callback,
2253
deltas=True, parents=True, is_locked=self.is_locked),
2254
data_access=self._pack_collection.text_index.data_access,
2255
max_delta_chain=200)
2256
if _format.supports_chks:
2257
# No graph, no compression:- references from chks are between
2258
# different objects not temporal versions of the same; and without
2259
# some sort of temporal structure knit compression will just fail.
2260
self.chk_bytes = KnitVersionedFiles(
2261
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2262
add_callback=self._pack_collection.chk_index.add_callback,
2263
deltas=False, parents=False, is_locked=self.is_locked),
2264
data_access=self._pack_collection.chk_index.data_access,
2267
self.chk_bytes = None
2268
# True when the repository object is 'write locked' (as opposed to the
2269
# physical lock only taken out around changes to the pack-names list.)
2270
# Another way to represent this would be a decorator around the control
2271
# files object that presents logical locks as physical ones - if this
2272
# gets ugly consider that alternative design. RBC 20071011
2273
self._write_lock_count = 0
2274
self._transaction = None
2276
self._reconcile_does_inventory_gc = True
1690
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1691
self._commit_builder_class = _commit_builder_class
1692
self._serializer = _serializer
2277
1693
self._reconcile_fixes_text_parents = True
2278
self._reconcile_backsup_inventory = False
1694
if self._format.supports_external_lookups:
1695
self._unstacked_provider = graph.CachingParentsProvider(
1696
self._make_parents_provider_unstacked())
1698
self._unstacked_provider = graph.CachingParentsProvider(self)
1699
self._unstacked_provider.disable_cache()
2280
def _warn_if_deprecated(self, branch=None):
2281
# This class isn't deprecated, but one sub-format is
2282
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2283
super(KnitPackRepository, self)._warn_if_deprecated(branch)
1702
def _all_revision_ids(self):
1703
"""See Repository.all_revision_ids()."""
1704
return [key[0] for key in self.revisions.keys()]
2285
1706
def _abort_write_group(self):
2286
1707
self.revisions._index._key_dependencies.clear()
2287
1708
self._pack_collection._abort_write_group()
2289
def _get_source(self, to_format):
2290
if to_format.network_name() == self._format.network_name():
2291
return KnitPackStreamSource(self, to_format)
2292
return super(KnitPackRepository, self)._get_source(to_format)
2294
1710
def _make_parents_provider(self):
2295
return graph.CachingParentsProvider(self)
1711
if not self._format.supports_external_lookups:
1712
return self._unstacked_provider
1713
return graph.StackedParentsProvider(_LazyListJoin(
1714
[self._unstacked_provider], self._fallback_repositories))
2297
1716
def _refresh_data(self):
2298
1717
if not self.is_locked():
2300
1719
self._pack_collection.reload_pack_names()
1720
self._unstacked_provider.disable_cache()
1721
self._unstacked_provider.enable_cache()
2302
1723
def _start_write_group(self):
2303
1724
self._pack_collection._start_write_group()
2414
1851
self.control_files.unlock()
2416
1853
if not self.is_locked():
1854
self._unstacked_provider.disable_cache()
2417
1855
for repo in self._fallback_repositories:
2421
class KnitPackStreamSource(StreamSource):
2422
"""A StreamSource used to transfer data between same-format KnitPack repos.
2424
This source assumes:
2425
1) Same serialization format for all objects
2426
2) Same root information
2427
3) XML format inventories
2428
4) Atomic inserts (so we can stream inventory texts before text
2433
def __init__(self, from_repository, to_format):
2434
super(KnitPackStreamSource, self).__init__(from_repository, to_format)
2435
self._text_keys = None
2436
self._text_fetch_order = 'unordered'
2438
def _get_filtered_inv_stream(self, revision_ids):
2439
from_repo = self.from_repository
2440
parent_ids = from_repo._find_parent_ids_of_revisions(revision_ids)
2441
parent_keys = [(p,) for p in parent_ids]
2442
find_text_keys = from_repo._find_text_key_references_from_xml_inventory_lines
2443
parent_text_keys = set(find_text_keys(
2444
from_repo._inventory_xml_lines_for_keys(parent_keys)))
2445
content_text_keys = set()
2446
knit = KnitVersionedFiles(None, None)
2447
factory = KnitPlainFactory()
2448
def find_text_keys_from_content(record):
2449
if record.storage_kind not in ('knit-delta-gz', 'knit-ft-gz'):
2450
raise ValueError("Unknown content storage kind for"
2451
" inventory text: %s" % (record.storage_kind,))
2452
# It's a knit record, it has a _raw_record field (even if it was
2453
# reconstituted from a network stream).
2454
raw_data = record._raw_record
2455
# read the entire thing
2456
revision_id = record.key[-1]
2457
content, _ = knit._parse_record(revision_id, raw_data)
2458
if record.storage_kind == 'knit-delta-gz':
2459
line_iterator = factory.get_linedelta_content(content)
2460
elif record.storage_kind == 'knit-ft-gz':
2461
line_iterator = factory.get_fulltext_content(content)
2462
content_text_keys.update(find_text_keys(
2463
[(line, revision_id) for line in line_iterator]))
2464
revision_keys = [(r,) for r in revision_ids]
2465
def _filtered_inv_stream():
2466
source_vf = from_repo.inventories
2467
stream = source_vf.get_record_stream(revision_keys,
2469
for record in stream:
2470
if record.storage_kind == 'absent':
2471
raise errors.NoSuchRevision(from_repo, record.key)
2472
find_text_keys_from_content(record)
2474
self._text_keys = content_text_keys - parent_text_keys
2475
return ('inventories', _filtered_inv_stream())
2477
def _get_text_stream(self):
2478
# Note: We know we don't have to handle adding root keys, because both
2479
# the source and target are the identical network name.
2480
text_stream = self.from_repository.texts.get_record_stream(
2481
self._text_keys, self._text_fetch_order, False)
2482
return ('texts', text_stream)
2484
def get_stream(self, search):
2485
revision_ids = search.get_keys()
2486
for stream_info in self._fetch_revision_texts(revision_ids):
2488
self._revision_keys = [(rev_id,) for rev_id in revision_ids]
2489
yield self._get_filtered_inv_stream(revision_ids)
2490
yield self._get_text_stream()
2494
class RepositoryFormatPack(MetaDirRepositoryFormat):
1859
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
2495
1860
"""Format logic for pack structured repositories.
2497
1862
This repository format has:
2567
1936
_serializer=self._serializer)
2570
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2571
"""A no-subtrees parameterized Pack repository.
2573
This format was introduced in 0.92.
2576
repository_class = KnitPackRepository
2577
_commit_builder_class = PackCommitBuilder
2579
def _serializer(self):
2580
return xml5.serializer_v5
2581
# What index classes to use
2582
index_builder_class = InMemoryGraphIndex
2583
index_class = GraphIndex
2585
def _get_matching_bzrdir(self):
2586
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2588
def _ignore_setting_bzrdir(self, format):
2591
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2593
def get_format_string(self):
2594
"""See RepositoryFormat.get_format_string()."""
2595
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2597
def get_format_description(self):
2598
"""See RepositoryFormat.get_format_description()."""
2599
return "Packs containing knits without subtree support"
2602
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2603
"""A subtrees parameterized Pack repository.
2605
This repository format uses the xml7 serializer to get:
2606
- support for recording full info about the tree root
2607
- support for recording tree-references
2609
This format was introduced in 0.92.
2612
repository_class = KnitPackRepository
2613
_commit_builder_class = PackRootCommitBuilder
2614
rich_root_data = True
2616
supports_tree_reference = True
2618
def _serializer(self):
2619
return xml7.serializer_v7
2620
# What index classes to use
2621
index_builder_class = InMemoryGraphIndex
2622
index_class = GraphIndex
2624
def _get_matching_bzrdir(self):
2625
return bzrdir.format_registry.make_bzrdir(
2626
'pack-0.92-subtree')
2628
def _ignore_setting_bzrdir(self, format):
2631
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2633
def get_format_string(self):
2634
"""See RepositoryFormat.get_format_string()."""
2635
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2637
def get_format_description(self):
2638
"""See RepositoryFormat.get_format_description()."""
2639
return "Packs containing knits with subtree support\n"
2642
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2643
"""A rich-root, no subtrees parameterized Pack repository.
2645
This repository format uses the xml6 serializer to get:
2646
- support for recording full info about the tree root
2648
This format was introduced in 1.0.
2651
repository_class = KnitPackRepository
2652
_commit_builder_class = PackRootCommitBuilder
2653
rich_root_data = True
2654
supports_tree_reference = False
2656
def _serializer(self):
2657
return xml6.serializer_v6
2658
# What index classes to use
2659
index_builder_class = InMemoryGraphIndex
2660
index_class = GraphIndex
2662
def _get_matching_bzrdir(self):
2663
return bzrdir.format_registry.make_bzrdir(
2666
def _ignore_setting_bzrdir(self, format):
2669
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2671
def get_format_string(self):
2672
"""See RepositoryFormat.get_format_string()."""
2673
return ("Bazaar pack repository format 1 with rich root"
2674
" (needs bzr 1.0)\n")
2676
def get_format_description(self):
2677
"""See RepositoryFormat.get_format_description()."""
2678
return "Packs containing knits with rich root support\n"
2681
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2682
"""Repository that supports external references to allow stacking.
2686
Supports external lookups, which results in non-truncated ghosts after
2687
reconcile compared to pack-0.92 formats.
2690
repository_class = KnitPackRepository
2691
_commit_builder_class = PackCommitBuilder
2692
supports_external_lookups = True
2693
# What index classes to use
2694
index_builder_class = InMemoryGraphIndex
2695
index_class = GraphIndex
2698
def _serializer(self):
2699
return xml5.serializer_v5
2701
def _get_matching_bzrdir(self):
2702
return bzrdir.format_registry.make_bzrdir('1.6')
2704
def _ignore_setting_bzrdir(self, format):
2707
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2709
def get_format_string(self):
2710
"""See RepositoryFormat.get_format_string()."""
2711
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2713
def get_format_description(self):
2714
"""See RepositoryFormat.get_format_description()."""
2715
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2718
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2719
"""A repository with rich roots and stacking.
2721
New in release 1.6.1.
2723
Supports stacking on other repositories, allowing data to be accessed
2724
without being stored locally.
2727
repository_class = KnitPackRepository
2728
_commit_builder_class = PackRootCommitBuilder
2729
rich_root_data = True
2730
supports_tree_reference = False # no subtrees
2731
supports_external_lookups = True
2732
# What index classes to use
2733
index_builder_class = InMemoryGraphIndex
2734
index_class = GraphIndex
2737
def _serializer(self):
2738
return xml6.serializer_v6
2740
def _get_matching_bzrdir(self):
2741
return bzrdir.format_registry.make_bzrdir(
2744
def _ignore_setting_bzrdir(self, format):
2747
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2749
def get_format_string(self):
2750
"""See RepositoryFormat.get_format_string()."""
2751
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2753
def get_format_description(self):
2754
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2757
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2758
"""A repository with rich roots and external references.
2762
Supports external lookups, which results in non-truncated ghosts after
2763
reconcile compared to pack-0.92 formats.
2765
This format was deprecated because the serializer it uses accidentally
2766
supported subtrees, when the format was not intended to. This meant that
2767
someone could accidentally fetch from an incorrect repository.
2770
repository_class = KnitPackRepository
2771
_commit_builder_class = PackRootCommitBuilder
2772
rich_root_data = True
2773
supports_tree_reference = False # no subtrees
2775
supports_external_lookups = True
2776
# What index classes to use
2777
index_builder_class = InMemoryGraphIndex
2778
index_class = GraphIndex
2781
def _serializer(self):
2782
return xml7.serializer_v7
2784
def _get_matching_bzrdir(self):
2785
matching = bzrdir.format_registry.make_bzrdir(
2787
matching.repository_format = self
2790
def _ignore_setting_bzrdir(self, format):
2793
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2795
def get_format_string(self):
2796
"""See RepositoryFormat.get_format_string()."""
2797
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2799
def get_format_description(self):
2800
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2804
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2805
"""A repository with stacking and btree indexes,
2806
without rich roots or subtrees.
2808
This is equivalent to pack-1.6 with B+Tree indices.
2811
repository_class = KnitPackRepository
2812
_commit_builder_class = PackCommitBuilder
2813
supports_external_lookups = True
2814
# What index classes to use
2815
index_builder_class = BTreeBuilder
2816
index_class = BTreeGraphIndex
2819
def _serializer(self):
2820
return xml5.serializer_v5
2822
def _get_matching_bzrdir(self):
2823
return bzrdir.format_registry.make_bzrdir('1.9')
2825
def _ignore_setting_bzrdir(self, format):
2828
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2830
def get_format_string(self):
2831
"""See RepositoryFormat.get_format_string()."""
2832
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2834
def get_format_description(self):
2835
"""See RepositoryFormat.get_format_description()."""
2836
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2839
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2840
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2842
1.6-rich-root with B+Tree indices.
2845
repository_class = KnitPackRepository
2846
_commit_builder_class = PackRootCommitBuilder
2847
rich_root_data = True
2848
supports_tree_reference = False # no subtrees
2849
supports_external_lookups = True
2850
# What index classes to use
2851
index_builder_class = BTreeBuilder
2852
index_class = BTreeGraphIndex
2855
def _serializer(self):
2856
return xml6.serializer_v6
2858
def _get_matching_bzrdir(self):
2859
return bzrdir.format_registry.make_bzrdir(
2862
def _ignore_setting_bzrdir(self, format):
2865
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2867
def get_format_string(self):
2868
"""See RepositoryFormat.get_format_string()."""
2869
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2871
def get_format_description(self):
2872
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2875
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2876
"""A subtrees development repository.
2878
This format should be retained until the second release after bzr 1.7.
2880
1.6.1-subtree[as it might have been] with B+Tree indices.
2882
This is [now] retained until we have a CHK based subtree format in
2886
repository_class = KnitPackRepository
2887
_commit_builder_class = PackRootCommitBuilder
2888
rich_root_data = True
2890
supports_tree_reference = True
2891
supports_external_lookups = True
2892
# What index classes to use
2893
index_builder_class = BTreeBuilder
2894
index_class = BTreeGraphIndex
2897
def _serializer(self):
2898
return xml7.serializer_v7
2900
def _get_matching_bzrdir(self):
2901
return bzrdir.format_registry.make_bzrdir(
2902
'development-subtree')
2904
def _ignore_setting_bzrdir(self, format):
2907
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2909
def get_format_string(self):
2910
"""See RepositoryFormat.get_format_string()."""
2911
return ("Bazaar development format 2 with subtree support "
2912
"(needs bzr.dev from before 1.8)\n")
2914
def get_format_description(self):
2915
"""See RepositoryFormat.get_format_description()."""
2916
return ("Development repository format, currently the same as "
2917
"1.6.1-subtree with B+Tree indices.\n")
1939
class RetryPackOperations(errors.RetryWithNewPacks):
1940
"""Raised when we are packing and we find a missing file.
1942
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1943
code it should try again.
1946
internal_error = True
1948
_fmt = ("Pack files have changed, reload and try pack again."
1949
" context: %(context)s %(orig_error)s")
1952
class _DirectPackAccess(object):
1953
"""Access to data in one or more packs with less translation."""
1955
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1956
"""Create a _DirectPackAccess object.
1958
:param index_to_packs: A dict mapping index objects to the transport
1959
and file names for obtaining data.
1960
:param reload_func: A function to call if we determine that the pack
1961
files have moved and we need to reload our caches. See
1962
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1964
self._container_writer = None
1965
self._write_index = None
1966
self._indices = index_to_packs
1967
self._reload_func = reload_func
1968
self._flush_func = flush_func
1970
def add_raw_records(self, key_sizes, raw_data):
1971
"""Add raw knit bytes to a storage area.
1973
The data is spooled to the container writer in one bytes-record per
1976
:param sizes: An iterable of tuples containing the key and size of each
1978
:param raw_data: A bytestring containing the data.
1979
:return: A list of memos to retrieve the record later. Each memo is an
1980
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1981
length), where the index field is the write_index object supplied
1982
to the PackAccess object.
1984
if type(raw_data) is not str:
1985
raise AssertionError(
1986
'data must be plain bytes was %s' % type(raw_data))
1989
for key, size in key_sizes:
1990
p_offset, p_length = self._container_writer.add_bytes_record(
1991
raw_data[offset:offset+size], [])
1993
result.append((self._write_index, p_offset, p_length))
1997
"""Flush pending writes on this access object.
1999
This will flush any buffered writes to a NewPack.
2001
if self._flush_func is not None:
2004
def get_raw_records(self, memos_for_retrieval):
2005
"""Get the raw bytes for a records.
2007
:param memos_for_retrieval: An iterable containing the (index, pos,
2008
length) memo for retrieving the bytes. The Pack access method
2009
looks up the pack to use for a given record in its index_to_pack
2011
:return: An iterator over the bytes of the records.
2013
# first pass, group into same-index requests
2015
current_index = None
2016
for (index, offset, length) in memos_for_retrieval:
2017
if current_index == index:
2018
current_list.append((offset, length))
2020
if current_index is not None:
2021
request_lists.append((current_index, current_list))
2022
current_index = index
2023
current_list = [(offset, length)]
2024
# handle the last entry
2025
if current_index is not None:
2026
request_lists.append((current_index, current_list))
2027
for index, offsets in request_lists:
2029
transport, path = self._indices[index]
2031
# A KeyError here indicates that someone has triggered an index
2032
# reload, and this index has gone missing, we need to start
2034
if self._reload_func is None:
2035
# If we don't have a _reload_func there is nothing that can
2038
raise errors.RetryWithNewPacks(index,
2039
reload_occurred=True,
2040
exc_info=sys.exc_info())
2042
reader = pack.make_readv_reader(transport, path, offsets)
2043
for names, read_func in reader.iter_records():
2044
yield read_func(None)
2045
except errors.NoSuchFile:
2046
# A NoSuchFile error indicates that a pack file has gone
2047
# missing on disk, we need to trigger a reload, and start over.
2048
if self._reload_func is None:
2050
raise errors.RetryWithNewPacks(transport.abspath(path),
2051
reload_occurred=False,
2052
exc_info=sys.exc_info())
2054
def set_writer(self, writer, index, transport_packname):
2055
"""Set a writer to use for adding data."""
2056
if index is not None:
2057
self._indices[index] = transport_packname
2058
self._container_writer = writer
2059
self._write_index = index
2061
def reload_or_raise(self, retry_exc):
2062
"""Try calling the reload function, or re-raise the original exception.
2064
This should be called after _DirectPackAccess raises a
2065
RetryWithNewPacks exception. This function will handle the common logic
2066
of determining when the error is fatal versus being temporary.
2067
It will also make sure that the original exception is raised, rather
2068
than the RetryWithNewPacks exception.
2070
If this function returns, then the calling function should retry
2071
whatever operation was being performed. Otherwise an exception will
2074
:param retry_exc: A RetryWithNewPacks exception.
2077
if self._reload_func is None:
2079
elif not self._reload_func():
2080
# The reload claimed that nothing changed
2081
if not retry_exc.reload_occurred:
2082
# If there wasn't an earlier reload, then we really were
2083
# expecting to find changes. We didn't find them, so this is a
2087
exc_class, exc_value, exc_traceback = retry_exc.exc_info
2088
raise exc_class, exc_value, exc_traceback