732
839
Sets self._text_filter appropriately.
734
raise NotImplementedError(self._copy_inventory_texts)
841
# select inventory keys
842
inv_keys = self._revision_keys # currently the same keyspace, and note that
843
# querying for keys here could introduce a bug where an inventory item
844
# is missed, so do not change it to query separately without cross
845
# checking like the text key check below.
846
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
848
inv_nodes = self._index_contents(inventory_indices, inv_keys)
849
# copy inventory keys and adjust values
850
# XXX: Should be a helper function to allow different inv representation
852
self.pb.update("Copying inventory texts", 2)
853
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
854
# Only grab the output lines if we will be processing them
855
output_lines = bool(self.revision_ids)
856
inv_lines = self._copy_nodes_graph(inventory_index_map,
857
self.new_pack._writer, self.new_pack.inventory_index,
858
readv_group_iter, total_items, output_lines=output_lines)
859
if self.revision_ids:
860
self._process_inventory_lines(inv_lines)
862
# eat the iterator to cause it to execute.
864
self._text_filter = None
865
if 'pack' in debug.debug_flags:
866
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
867
time.ctime(), self._pack_collection._upload_transport.base,
868
self.new_pack.random_name,
869
self.new_pack.inventory_index.key_count(),
870
time.time() - self.new_pack.start_time)
736
872
def _copy_text_texts(self):
737
raise NotImplementedError(self._copy_text_texts)
874
text_index_map, text_nodes = self._get_text_nodes()
875
if self._text_filter is not None:
876
# We could return the keys copied as part of the return value from
877
# _copy_nodes_graph but this doesn't work all that well with the
878
# need to get line output too, so we check separately, and as we're
879
# going to buffer everything anyway, we check beforehand, which
880
# saves reading knit data over the wire when we know there are
882
text_nodes = set(text_nodes)
883
present_text_keys = set(_node[1] for _node in text_nodes)
884
missing_text_keys = set(self._text_filter) - present_text_keys
885
if missing_text_keys:
886
# TODO: raise a specific error that can handle many missing
888
mutter("missing keys during fetch: %r", missing_text_keys)
889
a_missing_key = missing_text_keys.pop()
890
raise errors.RevisionNotPresent(a_missing_key[1],
892
# copy text keys and adjust values
893
self.pb.update("Copying content texts", 3)
894
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
895
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
896
self.new_pack.text_index, readv_group_iter, total_items))
897
self._log_copied_texts()
739
899
def _create_pack_from_packs(self):
740
raise NotImplementedError(self._create_pack_from_packs)
900
self.pb.update("Opening pack", 0, 5)
901
self.new_pack = self.open_pack()
902
new_pack = self.new_pack
903
# buffer data - we won't be reading-back during the pack creation and
904
# this makes a significant difference on sftp pushes.
905
new_pack.set_write_cache_size(1024*1024)
906
if 'pack' in debug.debug_flags:
907
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
908
for a_pack in self.packs]
909
if self.revision_ids is not None:
910
rev_count = len(self.revision_ids)
913
mutter('%s: create_pack: creating pack from source packs: '
914
'%s%s %s revisions wanted %s t=0',
915
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
916
plain_pack_list, rev_count)
917
self._copy_revision_texts()
918
self._copy_inventory_texts()
919
self._copy_text_texts()
920
# select signature keys
921
signature_filter = self._revision_keys # same keyspace
922
signature_index_map, signature_indices = self._pack_map_and_index_list(
924
signature_nodes = self._index_contents(signature_indices,
926
# copy signature keys and adjust values
927
self.pb.update("Copying signature texts", 4)
928
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
929
new_pack.signature_index)
930
if 'pack' in debug.debug_flags:
931
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
932
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
933
new_pack.signature_index.key_count(),
934
time.time() - new_pack.start_time)
936
# NB XXX: how to check CHK references are present? perhaps by yielding
937
# the items? How should that interact with stacked repos?
938
if new_pack.chk_index is not None:
940
if 'pack' in debug.debug_flags:
941
mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
942
time.ctime(), self._pack_collection._upload_transport.base,
943
new_pack.random_name,
944
new_pack.chk_index.key_count(),
945
time.time() - new_pack.start_time)
946
new_pack._check_references()
947
if not self._use_pack(new_pack):
950
self.pb.update("Finishing pack", 5)
952
self._pack_collection.allocate(new_pack)
955
def _copy_chks(self, refs=None):
956
# XXX: Todo, recursive follow-pointers facility when fetching some
958
chk_index_map, chk_indices = self._pack_map_and_index_list(
960
chk_nodes = self._index_contents(chk_indices, refs)
962
# TODO: This isn't strictly tasteful as we are accessing some private
963
# variables (_serializer). Perhaps a better way would be to have
964
# Repository._deserialise_chk_node()
965
search_key_func = chk_map.search_key_registry.get(
966
self._pack_collection.repo._serializer.search_key_name)
967
def accumlate_refs(lines):
968
# XXX: move to a generic location
970
bytes = ''.join(lines)
971
node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
972
new_refs.update(node.refs())
973
self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
974
self.new_pack.chk_index, output_lines=accumlate_refs)
977
def _copy_nodes(self, nodes, index_map, writer, write_index,
979
"""Copy knit nodes between packs with no graph references.
981
:param output_lines: Output full texts of copied items.
983
pb = ui.ui_factory.nested_progress_bar()
985
return self._do_copy_nodes(nodes, index_map, writer,
986
write_index, pb, output_lines=output_lines)
990
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
992
# for record verification
993
knit = KnitVersionedFiles(None, None)
994
# plan a readv on each source pack:
996
nodes = sorted(nodes)
997
# how to map this into knit.py - or knit.py into this?
998
# we don't want the typical knit logic, we want grouping by pack
999
# at this point - perhaps a helper library for the following code
1000
# duplication points?
1002
for index, key, value in nodes:
1003
if index not in request_groups:
1004
request_groups[index] = []
1005
request_groups[index].append((key, value))
1007
pb.update("Copied record", record_index, len(nodes))
1008
for index, items in request_groups.iteritems():
1009
pack_readv_requests = []
1010
for key, value in items:
1011
# ---- KnitGraphIndex.get_position
1012
bits = value[1:].split(' ')
1013
offset, length = int(bits[0]), int(bits[1])
1014
pack_readv_requests.append((offset, length, (key, value[0])))
1015
# linear scan up the pack
1016
pack_readv_requests.sort()
1018
pack_obj = index_map[index]
1019
transport, path = pack_obj.access_tuple()
1021
reader = pack.make_readv_reader(transport, path,
1022
[offset[0:2] for offset in pack_readv_requests])
1023
except errors.NoSuchFile:
1024
if self._reload_func is not None:
1027
for (names, read_func), (_1, _2, (key, eol_flag)) in \
1028
izip(reader.iter_records(), pack_readv_requests):
1029
raw_data = read_func(None)
1030
# check the header only
1031
if output_lines is not None:
1032
output_lines(knit._parse_record(key[-1], raw_data)[0])
1034
df, _ = knit._parse_record_header(key, raw_data)
1036
pos, size = writer.add_bytes_record(raw_data, names)
1037
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
1038
pb.update("Copied record", record_index)
1041
def _copy_nodes_graph(self, index_map, writer, write_index,
1042
readv_group_iter, total_items, output_lines=False):
1043
"""Copy knit nodes between packs.
1045
:param output_lines: Return lines present in the copied data as
1046
an iterator of line,version_id.
1048
pb = ui.ui_factory.nested_progress_bar()
1050
for result in self._do_copy_nodes_graph(index_map, writer,
1051
write_index, output_lines, pb, readv_group_iter, total_items):
1054
# Python 2.4 does not permit try:finally: in a generator.
1060
def _do_copy_nodes_graph(self, index_map, writer, write_index,
1061
output_lines, pb, readv_group_iter, total_items):
1062
# for record verification
1063
knit = KnitVersionedFiles(None, None)
1064
# for line extraction when requested (inventories only)
1066
factory = KnitPlainFactory()
1068
pb.update("Copied record", record_index, total_items)
1069
for index, readv_vector, node_vector in readv_group_iter:
1071
pack_obj = index_map[index]
1072
transport, path = pack_obj.access_tuple()
1074
reader = pack.make_readv_reader(transport, path, readv_vector)
1075
except errors.NoSuchFile:
1076
if self._reload_func is not None:
1079
for (names, read_func), (key, eol_flag, references) in \
1080
izip(reader.iter_records(), node_vector):
1081
raw_data = read_func(None)
1083
# read the entire thing
1084
content, _ = knit._parse_record(key[-1], raw_data)
1085
if len(references[-1]) == 0:
1086
line_iterator = factory.get_fulltext_content(content)
1088
line_iterator = factory.get_linedelta_content(content)
1089
for line in line_iterator:
1092
# check the header only
1093
df, _ = knit._parse_record_header(key, raw_data)
1095
pos, size = writer.add_bytes_record(raw_data, names)
1096
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1097
pb.update("Copied record", record_index)
1100
def _get_text_nodes(self):
1101
text_index_map, text_indices = self._pack_map_and_index_list(
1103
return text_index_map, self._index_contents(text_indices,
1106
def _least_readv_node_readv(self, nodes):
1107
"""Generate request groups for nodes using the least readv's.
1109
:param nodes: An iterable of graph index nodes.
1110
:return: Total node count and an iterator of the data needed to perform
1111
readvs to obtain the data for nodes. Each item yielded by the
1112
iterator is a tuple with:
1113
index, readv_vector, node_vector. readv_vector is a list ready to
1114
hand to the transport readv method, and node_vector is a list of
1115
(key, eol_flag, references) for the the node retrieved by the
1116
matching readv_vector.
1118
# group by pack so we do one readv per pack
1119
nodes = sorted(nodes)
1122
for index, key, value, references in nodes:
1123
if index not in request_groups:
1124
request_groups[index] = []
1125
request_groups[index].append((key, value, references))
1127
for index, items in request_groups.iteritems():
1128
pack_readv_requests = []
1129
for key, value, references in items:
1130
# ---- KnitGraphIndex.get_position
1131
bits = value[1:].split(' ')
1132
offset, length = int(bits[0]), int(bits[1])
1133
pack_readv_requests.append(
1134
((offset, length), (key, value[0], references)))
1135
# linear scan up the pack to maximum range combining.
1136
pack_readv_requests.sort()
1137
# split out the readv and the node data.
1138
pack_readv = [readv for readv, node in pack_readv_requests]
1139
node_vector = [node for readv, node in pack_readv_requests]
1140
result.append((index, pack_readv, node_vector))
1141
return total, result
742
1143
def _log_copied_texts(self):
743
1144
if 'pack' in debug.debug_flags:
756
1176
return new_pack.data_inserted()
1179
class OptimisingPacker(Packer):
1180
"""A packer which spends more time to create better disk layouts."""
1182
def _revision_node_readv(self, revision_nodes):
1183
"""Return the total revisions and the readv's to issue.
1185
This sort places revisions in topological order with the ancestors
1188
:param revision_nodes: The revision index contents for the packs being
1189
incorporated into the new pack.
1190
:return: As per _least_readv_node_readv.
1192
# build an ancestors dict
1195
for index, key, value, references in revision_nodes:
1196
ancestors[key] = references[0]
1197
by_key[key] = (index, value, references)
1198
order = tsort.topo_sort(ancestors)
1200
# Single IO is pathological, but it will work as a starting point.
1202
for key in reversed(order):
1203
index, value, references = by_key[key]
1204
# ---- KnitGraphIndex.get_position
1205
bits = value[1:].split(' ')
1206
offset, length = int(bits[0]), int(bits[1])
1208
(index, [(offset, length)], [(key, value[0], references)]))
1209
# TODO: combine requests in the same index that are in ascending order.
1210
return total, requests
1212
def open_pack(self):
1213
"""Open a pack for the pack we are creating."""
1214
new_pack = super(OptimisingPacker, self).open_pack()
1215
# Turn on the optimization flags for all the index builders.
1216
new_pack.revision_index.set_optimize(for_size=True)
1217
new_pack.inventory_index.set_optimize(for_size=True)
1218
new_pack.text_index.set_optimize(for_size=True)
1219
new_pack.signature_index.set_optimize(for_size=True)
1223
class ReconcilePacker(Packer):
1224
"""A packer which regenerates indices etc as it copies.
1226
This is used by ``bzr reconcile`` to cause parent text pointers to be
1230
def _extra_init(self):
1231
self._data_changed = False
1233
def _process_inventory_lines(self, inv_lines):
1234
"""Generate a text key reference map rather for reconciling with."""
1235
repo = self._pack_collection.repo
1236
refs = repo._find_text_key_references_from_xml_inventory_lines(
1238
self._text_refs = refs
1239
# during reconcile we:
1240
# - convert unreferenced texts to full texts
1241
# - correct texts which reference a text not copied to be full texts
1242
# - copy all others as-is but with corrected parents.
1243
# - so at this point we don't know enough to decide what becomes a full
1245
self._text_filter = None
1247
def _copy_text_texts(self):
1248
"""generate what texts we should have and then copy."""
1249
self.pb.update("Copying content texts", 3)
1250
# we have three major tasks here:
1251
# 1) generate the ideal index
1252
repo = self._pack_collection.repo
1253
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1254
_1, key, _2, refs in
1255
self.new_pack.revision_index.iter_all_entries()])
1256
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1257
# 2) generate a text_nodes list that contains all the deltas that can
1258
# be used as-is, with corrected parents.
1261
discarded_nodes = []
1262
NULL_REVISION = _mod_revision.NULL_REVISION
1263
text_index_map, text_nodes = self._get_text_nodes()
1264
for node in text_nodes:
1270
ideal_parents = tuple(ideal_index[node[1]])
1272
discarded_nodes.append(node)
1273
self._data_changed = True
1275
if ideal_parents == (NULL_REVISION,):
1277
if ideal_parents == node[3][0]:
1279
ok_nodes.append(node)
1280
elif ideal_parents[0:1] == node[3][0][0:1]:
1281
# the left most parent is the same, or there are no parents
1282
# today. Either way, we can preserve the representation as
1283
# long as we change the refs to be inserted.
1284
self._data_changed = True
1285
ok_nodes.append((node[0], node[1], node[2],
1286
(ideal_parents, node[3][1])))
1287
self._data_changed = True
1289
# Reinsert this text completely
1290
bad_texts.append((node[1], ideal_parents))
1291
self._data_changed = True
1292
# we're finished with some data.
1295
# 3) bulk copy the ok data
1296
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1297
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1298
self.new_pack.text_index, readv_group_iter, total_items))
1299
# 4) adhoc copy all the other texts.
1300
# We have to topologically insert all texts otherwise we can fail to
1301
# reconcile when parts of a single delta chain are preserved intact,
1302
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1303
# reinserted, and if d3 has incorrect parents it will also be
1304
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1305
# copied), so we will try to delta, but d2 is not currently able to be
1306
# extracted because it's basis d1 is not present. Topologically sorting
1307
# addresses this. The following generates a sort for all the texts that
1308
# are being inserted without having to reference the entire text key
1309
# space (we only topo sort the revisions, which is smaller).
1310
topo_order = tsort.topo_sort(ancestors)
1311
rev_order = dict(zip(topo_order, range(len(topo_order))))
1312
bad_texts.sort(key=lambda key:rev_order.get(key[0][1], 0))
1313
transaction = repo.get_transaction()
1314
file_id_index = GraphIndexPrefixAdapter(
1315
self.new_pack.text_index,
1317
add_nodes_callback=self.new_pack.text_index.add_nodes)
1318
data_access = _DirectPackAccess(
1319
{self.new_pack.text_index:self.new_pack.access_tuple()})
1320
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1321
self.new_pack.access_tuple())
1322
output_texts = KnitVersionedFiles(
1323
_KnitGraphIndex(self.new_pack.text_index,
1324
add_callback=self.new_pack.text_index.add_nodes,
1325
deltas=True, parents=True, is_locked=repo.is_locked),
1326
data_access=data_access, max_delta_chain=200)
1327
for key, parent_keys in bad_texts:
1328
# We refer to the new pack to delta data being output.
1329
# A possible improvement would be to catch errors on short reads
1330
# and only flush then.
1331
self.new_pack.flush()
1333
for parent_key in parent_keys:
1334
if parent_key[0] != key[0]:
1335
# Graph parents must match the fileid
1336
raise errors.BzrError('Mismatched key parent %r:%r' %
1338
parents.append(parent_key[1])
1339
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1340
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1341
output_texts.add_lines(key, parent_keys, text_lines,
1342
random_id=True, check_content=False)
1343
# 5) check that nothing inserted has a reference outside the keyspace.
1344
missing_text_keys = self.new_pack.text_index._external_references()
1345
if missing_text_keys:
1346
raise errors.BzrCheckError('Reference to missing compression parents %r'
1347
% (missing_text_keys,))
1348
self._log_copied_texts()
1350
def _use_pack(self, new_pack):
1351
"""Override _use_pack to check for reconcile having changed content."""
1352
# XXX: we might be better checking this at the copy time.
1353
original_inventory_keys = set()
1354
inv_index = self._pack_collection.inventory_index.combined_index
1355
for entry in inv_index.iter_all_entries():
1356
original_inventory_keys.add(entry[1])
1357
new_inventory_keys = set()
1358
for entry in new_pack.inventory_index.iter_all_entries():
1359
new_inventory_keys.add(entry[1])
1360
if new_inventory_keys != original_inventory_keys:
1361
self._data_changed = True
1362
return new_pack.data_inserted() and self._data_changed
759
1365
class RepositoryPackCollection(object):
760
1366
"""Management of packs within a repository.
762
1368
:ivar _names: map of {pack_name: (index_size,)}
766
resumed_pack_factory = None
767
normal_packer_class = None
768
optimising_packer_class = None
1371
pack_factory = NewPack
1372
resumed_pack_factory = ResumedPack
770
1374
def __init__(self, repo, transport, index_transport, upload_transport,
771
1375
pack_transport, index_builder_class, index_class,
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
2149
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
2151
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2152
_commit_builder_class, _serializer)
2153
index_transport = self._transport.clone('indices')
2154
self._pack_collection = RepositoryPackCollection(self, self._transport,
2156
self._transport.clone('upload'),
2157
self._transport.clone('packs'),
2158
_format.index_builder_class,
2159
_format.index_class,
2160
use_chk_index=self._format.supports_chks,
2162
self.inventories = KnitVersionedFiles(
2163
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2164
add_callback=self._pack_collection.inventory_index.add_callback,
2165
deltas=True, parents=True, is_locked=self.is_locked),
2166
data_access=self._pack_collection.inventory_index.data_access,
2167
max_delta_chain=200)
2168
self.revisions = KnitVersionedFiles(
2169
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2170
add_callback=self._pack_collection.revision_index.add_callback,
2171
deltas=False, parents=True, is_locked=self.is_locked,
2172
track_external_parent_refs=True),
2173
data_access=self._pack_collection.revision_index.data_access,
2175
self.signatures = KnitVersionedFiles(
2176
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2177
add_callback=self._pack_collection.signature_index.add_callback,
2178
deltas=False, parents=False, is_locked=self.is_locked),
2179
data_access=self._pack_collection.signature_index.data_access,
2181
self.texts = KnitVersionedFiles(
2182
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2183
add_callback=self._pack_collection.text_index.add_callback,
2184
deltas=True, parents=True, is_locked=self.is_locked),
2185
data_access=self._pack_collection.text_index.data_access,
2186
max_delta_chain=200)
2187
if _format.supports_chks:
2188
# No graph, no compression:- references from chks are between
2189
# different objects not temporal versions of the same; and without
2190
# some sort of temporal structure knit compression will just fail.
2191
self.chk_bytes = KnitVersionedFiles(
2192
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2193
add_callback=self._pack_collection.chk_index.add_callback,
2194
deltas=False, parents=False, is_locked=self.is_locked),
2195
data_access=self._pack_collection.chk_index.data_access,
2198
self.chk_bytes = None
2199
# True when the repository object is 'write locked' (as opposed to the
2200
# physical lock only taken out around changes to the pack-names list.)
2201
# Another way to represent this would be a decorator around the control
2202
# files object that presents logical locks as physical ones - if this
2203
# gets ugly consider that alternative design. RBC 20071011
2204
self._write_lock_count = 0
2205
self._transaction = None
2207
self._reconcile_does_inventory_gc = True
1667
2208
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()
2209
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()]
2211
def _warn_if_deprecated(self):
2212
# This class isn't deprecated, but one sub-format is
2213
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2214
from bzrlib import repository
2215
if repository._deprecation_warning_done:
2217
repository._deprecation_warning_done = True
2218
warning("Format %s for %s is deprecated - please use"
2219
" 'bzr upgrade --1.6.1-rich-root'"
2220
% (self._format, self.bzrdir.transport.base))
1680
2222
def _abort_write_group(self):
1681
self.revisions._index._key_dependencies.clear()
2223
self.revisions._index._key_dependencies.refs.clear()
1682
2224
self._pack_collection._abort_write_group()
2226
def _find_inconsistent_revision_parents(self):
2227
"""Find revisions with incorrectly cached parents.
2229
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2230
parents-in-revision).
2232
if not self.is_locked():
2233
raise errors.ObjectNotLocked(self)
2234
pb = ui.ui_factory.nested_progress_bar()
2237
revision_nodes = self._pack_collection.revision_index \
2238
.combined_index.iter_all_entries()
2239
index_positions = []
2240
# Get the cached index values for all revisions, and also the
2241
# location in each index of the revision text so we can perform
2243
for index, key, value, refs in revision_nodes:
2244
node = (index, key, value, refs)
2245
index_memo = self.revisions._index._node_to_position(node)
2246
if index_memo[0] != index:
2247
raise AssertionError('%r != %r' % (index_memo[0], index))
2248
index_positions.append((index_memo, key[0],
2249
tuple(parent[0] for parent in refs[0])))
2250
pb.update("Reading revision index", 0, 0)
2251
index_positions.sort()
2253
pb.update("Checking cached revision graph", 0,
2254
len(index_positions))
2255
for offset in xrange(0, len(index_positions), 1000):
2256
pb.update("Checking cached revision graph", offset)
2257
to_query = index_positions[offset:offset + batch_size]
2260
rev_ids = [item[1] for item in to_query]
2261
revs = self.get_revisions(rev_ids)
2262
for revision, item in zip(revs, to_query):
2263
index_parents = item[2]
2264
rev_parents = tuple(revision.parent_ids)
2265
if index_parents != rev_parents:
2266
result.append((revision.revision_id, index_parents,
2272
def _get_source(self, to_format):
2273
if to_format.network_name() == self._format.network_name():
2274
return KnitPackStreamSource(self, to_format)
2275
return super(KnitPackRepository, self)._get_source(to_format)
1684
2277
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))
2278
return graph.CachingParentsProvider(self)
1690
2280
def _refresh_data(self):
1691
2281
if not self.is_locked():
1693
2283
self._pack_collection.reload_pack_names()
1694
self._unstacked_provider.disable_cache()
1695
self._unstacked_provider.enable_cache()
1697
2285
def _start_write_group(self):
1698
2286
self._pack_collection._start_write_group()
1700
2288
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()
2289
self.revisions._index._key_dependencies.refs.clear()
2290
return self._pack_collection._commit_write_group()
1709
2292
def suspend_write_group(self):
1710
2293
# XXX check self._write_group is self.get_transaction()?
1711
2294
tokens = self._pack_collection._suspend_write_group()
1712
self.revisions._index._key_dependencies.clear()
2295
self.revisions._index._key_dependencies.refs.clear()
1713
2296
self._write_group = None
1825
2389
self.control_files.unlock()
1827
2391
if not self.is_locked():
1828
self._unstacked_provider.disable_cache()
1829
2392
for repo in self._fallback_repositories:
1833
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
2396
class KnitPackStreamSource(StreamSource):
2397
"""A StreamSource used to transfer data between same-format KnitPack repos.
2399
This source assumes:
2400
1) Same serialization format for all objects
2401
2) Same root information
2402
3) XML format inventories
2403
4) Atomic inserts (so we can stream inventory texts before text
2408
def __init__(self, from_repository, to_format):
2409
super(KnitPackStreamSource, self).__init__(from_repository, to_format)
2410
self._text_keys = None
2411
self._text_fetch_order = 'unordered'
2413
def _get_filtered_inv_stream(self, revision_ids):
2414
from_repo = self.from_repository
2415
parent_ids = from_repo._find_parent_ids_of_revisions(revision_ids)
2416
parent_keys = [(p,) for p in parent_ids]
2417
find_text_keys = from_repo._find_text_key_references_from_xml_inventory_lines
2418
parent_text_keys = set(find_text_keys(
2419
from_repo._inventory_xml_lines_for_keys(parent_keys)))
2420
content_text_keys = set()
2421
knit = KnitVersionedFiles(None, None)
2422
factory = KnitPlainFactory()
2423
def find_text_keys_from_content(record):
2424
if record.storage_kind not in ('knit-delta-gz', 'knit-ft-gz'):
2425
raise ValueError("Unknown content storage kind for"
2426
" inventory text: %s" % (record.storage_kind,))
2427
# It's a knit record, it has a _raw_record field (even if it was
2428
# reconstituted from a network stream).
2429
raw_data = record._raw_record
2430
# read the entire thing
2431
revision_id = record.key[-1]
2432
content, _ = knit._parse_record(revision_id, raw_data)
2433
if record.storage_kind == 'knit-delta-gz':
2434
line_iterator = factory.get_linedelta_content(content)
2435
elif record.storage_kind == 'knit-ft-gz':
2436
line_iterator = factory.get_fulltext_content(content)
2437
content_text_keys.update(find_text_keys(
2438
[(line, revision_id) for line in line_iterator]))
2439
revision_keys = [(r,) for r in revision_ids]
2440
def _filtered_inv_stream():
2441
source_vf = from_repo.inventories
2442
stream = source_vf.get_record_stream(revision_keys,
2444
for record in stream:
2445
if record.storage_kind == 'absent':
2446
raise errors.NoSuchRevision(from_repo, record.key)
2447
find_text_keys_from_content(record)
2449
self._text_keys = content_text_keys - parent_text_keys
2450
return ('inventories', _filtered_inv_stream())
2452
def _get_text_stream(self):
2453
# Note: We know we don't have to handle adding root keys, because both
2454
# the source and target are the identical network name.
2455
text_stream = self.from_repository.texts.get_record_stream(
2456
self._text_keys, self._text_fetch_order, False)
2457
return ('texts', text_stream)
2459
def get_stream(self, search):
2460
revision_ids = search.get_keys()
2461
for stream_info in self._fetch_revision_texts(revision_ids):
2463
self._revision_keys = [(rev_id,) for rev_id in revision_ids]
2464
yield self._get_filtered_inv_stream(revision_ids)
2465
yield self._get_text_stream()
2469
class RepositoryFormatPack(MetaDirRepositoryFormat):
1834
2470
"""Format logic for pack structured repositories.
1836
2472
This repository format has:
1910
2542
_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
2545
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2546
"""A no-subtrees parameterized Pack repository.
2548
This format was introduced in 0.92.
2551
repository_class = KnitPackRepository
2552
_commit_builder_class = PackCommitBuilder
2554
def _serializer(self):
2555
return xml5.serializer_v5
2556
# What index classes to use
2557
index_builder_class = InMemoryGraphIndex
2558
index_class = GraphIndex
2560
def _get_matching_bzrdir(self):
2561
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2563
def _ignore_setting_bzrdir(self, format):
2566
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2568
def get_format_string(self):
2569
"""See RepositoryFormat.get_format_string()."""
2570
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2572
def get_format_description(self):
2573
"""See RepositoryFormat.get_format_description()."""
2574
return "Packs containing knits without subtree support"
2576
def check_conversion_target(self, target_format):
2580
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2581
"""A subtrees parameterized Pack repository.
2583
This repository format uses the xml7 serializer to get:
2584
- support for recording full info about the tree root
2585
- support for recording tree-references
2587
This format was introduced in 0.92.
2590
repository_class = KnitPackRepository
2591
_commit_builder_class = PackRootCommitBuilder
2592
rich_root_data = True
2593
supports_tree_reference = True
2595
def _serializer(self):
2596
return xml7.serializer_v7
2597
# What index classes to use
2598
index_builder_class = InMemoryGraphIndex
2599
index_class = GraphIndex
2601
def _get_matching_bzrdir(self):
2602
return bzrdir.format_registry.make_bzrdir(
2603
'pack-0.92-subtree')
2605
def _ignore_setting_bzrdir(self, format):
2608
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2610
def check_conversion_target(self, target_format):
2611
if not target_format.rich_root_data:
2612
raise errors.BadConversionTarget(
2613
'Does not support rich root data.', target_format)
2614
if not getattr(target_format, 'supports_tree_reference', False):
2615
raise errors.BadConversionTarget(
2616
'Does not support nested trees', target_format)
2618
def get_format_string(self):
2619
"""See RepositoryFormat.get_format_string()."""
2620
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2622
def get_format_description(self):
2623
"""See RepositoryFormat.get_format_description()."""
2624
return "Packs containing knits with subtree support\n"
2627
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2628
"""A rich-root, no subtrees parameterized Pack repository.
2630
This repository format uses the xml6 serializer to get:
2631
- support for recording full info about the tree root
2633
This format was introduced in 1.0.
2636
repository_class = KnitPackRepository
2637
_commit_builder_class = PackRootCommitBuilder
2638
rich_root_data = True
2639
supports_tree_reference = False
2641
def _serializer(self):
2642
return xml6.serializer_v6
2643
# What index classes to use
2644
index_builder_class = InMemoryGraphIndex
2645
index_class = GraphIndex
2647
def _get_matching_bzrdir(self):
2648
return bzrdir.format_registry.make_bzrdir(
2651
def _ignore_setting_bzrdir(self, format):
2654
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2656
def check_conversion_target(self, target_format):
2657
if not target_format.rich_root_data:
2658
raise errors.BadConversionTarget(
2659
'Does not support rich root data.', target_format)
2661
def get_format_string(self):
2662
"""See RepositoryFormat.get_format_string()."""
2663
return ("Bazaar pack repository format 1 with rich root"
2664
" (needs bzr 1.0)\n")
2666
def get_format_description(self):
2667
"""See RepositoryFormat.get_format_description()."""
2668
return "Packs containing knits with rich root support\n"
2671
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2672
"""Repository that supports external references to allow stacking.
2676
Supports external lookups, which results in non-truncated ghosts after
2677
reconcile compared to pack-0.92 formats.
2680
repository_class = KnitPackRepository
2681
_commit_builder_class = PackCommitBuilder
2682
supports_external_lookups = True
2683
# What index classes to use
2684
index_builder_class = InMemoryGraphIndex
2685
index_class = GraphIndex
2688
def _serializer(self):
2689
return xml5.serializer_v5
2691
def _get_matching_bzrdir(self):
2692
return bzrdir.format_registry.make_bzrdir('1.6')
2694
def _ignore_setting_bzrdir(self, format):
2697
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2699
def get_format_string(self):
2700
"""See RepositoryFormat.get_format_string()."""
2701
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2703
def get_format_description(self):
2704
"""See RepositoryFormat.get_format_description()."""
2705
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2707
def check_conversion_target(self, target_format):
2711
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2712
"""A repository with rich roots and stacking.
2714
New in release 1.6.1.
2716
Supports stacking on other repositories, allowing data to be accessed
2717
without being stored locally.
2720
repository_class = KnitPackRepository
2721
_commit_builder_class = PackRootCommitBuilder
2722
rich_root_data = True
2723
supports_tree_reference = False # no subtrees
2724
supports_external_lookups = True
2725
# What index classes to use
2726
index_builder_class = InMemoryGraphIndex
2727
index_class = GraphIndex
2730
def _serializer(self):
2731
return xml6.serializer_v6
2733
def _get_matching_bzrdir(self):
2734
return bzrdir.format_registry.make_bzrdir(
2737
def _ignore_setting_bzrdir(self, format):
2740
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2742
def check_conversion_target(self, target_format):
2743
if not target_format.rich_root_data:
2744
raise errors.BadConversionTarget(
2745
'Does not support rich root data.', target_format)
2747
def get_format_string(self):
2748
"""See RepositoryFormat.get_format_string()."""
2749
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2751
def get_format_description(self):
2752
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2755
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2756
"""A repository with rich roots and external references.
2760
Supports external lookups, which results in non-truncated ghosts after
2761
reconcile compared to pack-0.92 formats.
2763
This format was deprecated because the serializer it uses accidentally
2764
supported subtrees, when the format was not intended to. This meant that
2765
someone could accidentally fetch from an incorrect repository.
2768
repository_class = KnitPackRepository
2769
_commit_builder_class = PackRootCommitBuilder
2770
rich_root_data = True
2771
supports_tree_reference = False # no subtrees
2773
supports_external_lookups = True
2774
# What index classes to use
2775
index_builder_class = InMemoryGraphIndex
2776
index_class = GraphIndex
2779
def _serializer(self):
2780
return xml7.serializer_v7
2782
def _get_matching_bzrdir(self):
2783
matching = bzrdir.format_registry.make_bzrdir(
2785
matching.repository_format = self
2788
def _ignore_setting_bzrdir(self, format):
2791
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2793
def check_conversion_target(self, target_format):
2794
if not target_format.rich_root_data:
2795
raise errors.BadConversionTarget(
2796
'Does not support rich root data.', target_format)
2798
def get_format_string(self):
2799
"""See RepositoryFormat.get_format_string()."""
2800
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2802
def get_format_description(self):
2803
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2807
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2808
"""A repository with stacking and btree indexes,
2809
without rich roots or subtrees.
2811
This is equivalent to pack-1.6 with B+Tree indices.
2814
repository_class = KnitPackRepository
2815
_commit_builder_class = PackCommitBuilder
2816
supports_external_lookups = True
2817
# What index classes to use
2818
index_builder_class = BTreeBuilder
2819
index_class = BTreeGraphIndex
2822
def _serializer(self):
2823
return xml5.serializer_v5
2825
def _get_matching_bzrdir(self):
2826
return bzrdir.format_registry.make_bzrdir('1.9')
2828
def _ignore_setting_bzrdir(self, format):
2831
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2833
def get_format_string(self):
2834
"""See RepositoryFormat.get_format_string()."""
2835
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2837
def get_format_description(self):
2838
"""See RepositoryFormat.get_format_description()."""
2839
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2841
def check_conversion_target(self, target_format):
2845
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2846
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2848
1.6-rich-root with B+Tree indices.
2851
repository_class = KnitPackRepository
2852
_commit_builder_class = PackRootCommitBuilder
2853
rich_root_data = True
2854
supports_tree_reference = False # no subtrees
2855
supports_external_lookups = True
2856
# What index classes to use
2857
index_builder_class = BTreeBuilder
2858
index_class = BTreeGraphIndex
2861
def _serializer(self):
2862
return xml6.serializer_v6
2864
def _get_matching_bzrdir(self):
2865
return bzrdir.format_registry.make_bzrdir(
2868
def _ignore_setting_bzrdir(self, format):
2871
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2873
def check_conversion_target(self, target_format):
2874
if not target_format.rich_root_data:
2875
raise errors.BadConversionTarget(
2876
'Does not support rich root data.', target_format)
2878
def get_format_string(self):
2879
"""See RepositoryFormat.get_format_string()."""
2880
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2882
def get_format_description(self):
2883
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2886
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2887
"""A subtrees development repository.
2889
This format should be retained until the second release after bzr 1.7.
2891
1.6.1-subtree[as it might have been] with B+Tree indices.
2893
This is [now] retained until we have a CHK based subtree format in
2897
repository_class = KnitPackRepository
2898
_commit_builder_class = PackRootCommitBuilder
2899
rich_root_data = True
2900
supports_tree_reference = True
2901
supports_external_lookups = True
2902
# What index classes to use
2903
index_builder_class = BTreeBuilder
2904
index_class = BTreeGraphIndex
2907
def _serializer(self):
2908
return xml7.serializer_v7
2910
def _get_matching_bzrdir(self):
2911
return bzrdir.format_registry.make_bzrdir(
2912
'development-subtree')
2914
def _ignore_setting_bzrdir(self, format):
2917
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2919
def check_conversion_target(self, target_format):
2920
if not target_format.rich_root_data:
2921
raise errors.BadConversionTarget(
2922
'Does not support rich root data.', target_format)
2923
if not getattr(target_format, 'supports_tree_reference', False):
2924
raise errors.BadConversionTarget(
2925
'Does not support nested trees', target_format)
2927
def get_format_string(self):
2928
"""See RepositoryFormat.get_format_string()."""
2929
return ("Bazaar development format 2 with subtree support "
2930
"(needs bzr.dev from before 1.8)\n")
2932
def get_format_description(self):
2933
"""See RepositoryFormat.get_format_description()."""
2934
return ("Development repository format, currently the same as "
2935
"1.6.1-subtree with B+Tree indices.\n")