732
822
Sets self._text_filter appropriately.
734
raise NotImplementedError(self._copy_inventory_texts)
824
# select inventory keys
825
inv_keys = self._revision_keys # currently the same keyspace, and note that
826
# querying for keys here could introduce a bug where an inventory item
827
# is missed, so do not change it to query separately without cross
828
# checking like the text key check below.
829
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
831
inv_nodes = self._index_contents(inventory_indices, inv_keys)
832
# copy inventory keys and adjust values
833
# XXX: Should be a helper function to allow different inv representation
835
self.pb.update("Copying inventory texts", 2)
836
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
837
# Only grab the output lines if we will be processing them
838
output_lines = bool(self.revision_ids)
839
inv_lines = self._copy_nodes_graph(inventory_index_map,
840
self.new_pack._writer, self.new_pack.inventory_index,
841
readv_group_iter, total_items, output_lines=output_lines)
842
if self.revision_ids:
843
self._process_inventory_lines(inv_lines)
845
# eat the iterator to cause it to execute.
847
self._text_filter = None
848
if 'pack' in debug.debug_flags:
849
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
850
time.ctime(), self._pack_collection._upload_transport.base,
851
self.new_pack.random_name,
852
self.new_pack.inventory_index.key_count(),
853
time.time() - self.new_pack.start_time)
736
855
def _copy_text_texts(self):
737
raise NotImplementedError(self._copy_text_texts)
857
text_index_map, text_nodes = self._get_text_nodes()
858
if self._text_filter is not None:
859
# We could return the keys copied as part of the return value from
860
# _copy_nodes_graph but this doesn't work all that well with the
861
# need to get line output too, so we check separately, and as we're
862
# going to buffer everything anyway, we check beforehand, which
863
# saves reading knit data over the wire when we know there are
865
text_nodes = set(text_nodes)
866
present_text_keys = set(_node[1] for _node in text_nodes)
867
missing_text_keys = set(self._text_filter) - present_text_keys
868
if missing_text_keys:
869
# TODO: raise a specific error that can handle many missing
871
mutter("missing keys during fetch: %r", missing_text_keys)
872
a_missing_key = missing_text_keys.pop()
873
raise errors.RevisionNotPresent(a_missing_key[1],
875
# copy text keys and adjust values
876
self.pb.update("Copying content texts", 3)
877
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
878
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
879
self.new_pack.text_index, readv_group_iter, total_items))
880
self._log_copied_texts()
739
882
def _create_pack_from_packs(self):
740
raise NotImplementedError(self._create_pack_from_packs)
883
self.pb.update("Opening pack", 0, 5)
884
self.new_pack = self.open_pack()
885
new_pack = self.new_pack
886
# buffer data - we won't be reading-back during the pack creation and
887
# this makes a significant difference on sftp pushes.
888
new_pack.set_write_cache_size(1024*1024)
889
if 'pack' in debug.debug_flags:
890
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
891
for a_pack in self.packs]
892
if self.revision_ids is not None:
893
rev_count = len(self.revision_ids)
896
mutter('%s: create_pack: creating pack from source packs: '
897
'%s%s %s revisions wanted %s t=0',
898
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
899
plain_pack_list, rev_count)
900
self._copy_revision_texts()
901
self._copy_inventory_texts()
902
self._copy_text_texts()
903
# select signature keys
904
signature_filter = self._revision_keys # same keyspace
905
signature_index_map, signature_indices = self._pack_map_and_index_list(
907
signature_nodes = self._index_contents(signature_indices,
909
# copy signature keys and adjust values
910
self.pb.update("Copying signature texts", 4)
911
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
912
new_pack.signature_index)
913
if 'pack' in debug.debug_flags:
914
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
915
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
916
new_pack.signature_index.key_count(),
917
time.time() - new_pack.start_time)
919
# NB XXX: how to check CHK references are present? perhaps by yielding
920
# the items? How should that interact with stacked repos?
921
if new_pack.chk_index is not None:
923
if 'pack' in debug.debug_flags:
924
mutter('%s: create_pack: chk content copied: %s%s %d items t+%6.3fs',
925
time.ctime(), self._pack_collection._upload_transport.base,
926
new_pack.random_name,
927
new_pack.chk_index.key_count(),
928
time.time() - new_pack.start_time)
929
new_pack._check_references()
930
if not self._use_pack(new_pack):
933
self.pb.update("Finishing pack", 5)
935
self._pack_collection.allocate(new_pack)
938
def _copy_chks(self, refs=None):
939
# XXX: Todo, recursive follow-pointers facility when fetching some
941
chk_index_map, chk_indices = self._pack_map_and_index_list(
943
chk_nodes = self._index_contents(chk_indices, refs)
945
# TODO: This isn't strictly tasteful as we are accessing some private
946
# variables (_serializer). Perhaps a better way would be to have
947
# Repository._deserialise_chk_node()
948
search_key_func = chk_map.search_key_registry.get(
949
self._pack_collection.repo._serializer.search_key_name)
950
def accumlate_refs(lines):
951
# XXX: move to a generic location
953
bytes = ''.join(lines)
954
node = chk_map._deserialise(bytes, ("unknown",), search_key_func)
955
new_refs.update(node.refs())
956
self._copy_nodes(chk_nodes, chk_index_map, self.new_pack._writer,
957
self.new_pack.chk_index, output_lines=accumlate_refs)
960
def _copy_nodes(self, nodes, index_map, writer, write_index,
962
"""Copy knit nodes between packs with no graph references.
964
:param output_lines: Output full texts of copied items.
966
pb = ui.ui_factory.nested_progress_bar()
968
return self._do_copy_nodes(nodes, index_map, writer,
969
write_index, pb, output_lines=output_lines)
973
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb,
975
# for record verification
976
knit = KnitVersionedFiles(None, None)
977
# plan a readv on each source pack:
979
nodes = sorted(nodes)
980
# how to map this into knit.py - or knit.py into this?
981
# we don't want the typical knit logic, we want grouping by pack
982
# at this point - perhaps a helper library for the following code
983
# duplication points?
985
for index, key, value in nodes:
986
if index not in request_groups:
987
request_groups[index] = []
988
request_groups[index].append((key, value))
990
pb.update("Copied record", record_index, len(nodes))
991
for index, items in request_groups.iteritems():
992
pack_readv_requests = []
993
for key, value in items:
994
# ---- KnitGraphIndex.get_position
995
bits = value[1:].split(' ')
996
offset, length = int(bits[0]), int(bits[1])
997
pack_readv_requests.append((offset, length, (key, value[0])))
998
# linear scan up the pack
999
pack_readv_requests.sort()
1001
pack_obj = index_map[index]
1002
transport, path = pack_obj.access_tuple()
1004
reader = pack.make_readv_reader(transport, path,
1005
[offset[0:2] for offset in pack_readv_requests])
1006
except errors.NoSuchFile:
1007
if self._reload_func is not None:
1010
for (names, read_func), (_1, _2, (key, eol_flag)) in \
1011
izip(reader.iter_records(), pack_readv_requests):
1012
raw_data = read_func(None)
1013
# check the header only
1014
if output_lines is not None:
1015
output_lines(knit._parse_record(key[-1], raw_data)[0])
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))
1021
pb.update("Copied record", record_index)
1024
def _copy_nodes_graph(self, index_map, writer, write_index,
1025
readv_group_iter, total_items, output_lines=False):
1026
"""Copy knit nodes between packs.
1028
:param output_lines: Return lines present in the copied data as
1029
an iterator of line,version_id.
1031
pb = ui.ui_factory.nested_progress_bar()
1033
for result in self._do_copy_nodes_graph(index_map, writer,
1034
write_index, output_lines, pb, readv_group_iter, total_items):
1037
# Python 2.4 does not permit try:finally: in a generator.
1043
def _do_copy_nodes_graph(self, index_map, writer, write_index,
1044
output_lines, pb, readv_group_iter, total_items):
1045
# for record verification
1046
knit = KnitVersionedFiles(None, None)
1047
# for line extraction when requested (inventories only)
1049
factory = KnitPlainFactory()
1051
pb.update("Copied record", record_index, total_items)
1052
for index, readv_vector, node_vector in readv_group_iter:
1054
pack_obj = index_map[index]
1055
transport, path = pack_obj.access_tuple()
1057
reader = pack.make_readv_reader(transport, path, readv_vector)
1058
except errors.NoSuchFile:
1059
if self._reload_func is not None:
1062
for (names, read_func), (key, eol_flag, references) in \
1063
izip(reader.iter_records(), node_vector):
1064
raw_data = read_func(None)
1066
# read the entire thing
1067
content, _ = knit._parse_record(key[-1], raw_data)
1068
if len(references[-1]) == 0:
1069
line_iterator = factory.get_fulltext_content(content)
1071
line_iterator = factory.get_linedelta_content(content)
1072
for line in line_iterator:
1075
# check the header only
1076
df, _ = knit._parse_record_header(key, raw_data)
1078
pos, size = writer.add_bytes_record(raw_data, names)
1079
write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
1080
pb.update("Copied record", record_index)
1083
def _get_text_nodes(self):
1084
text_index_map, text_indices = self._pack_map_and_index_list(
1086
return text_index_map, self._index_contents(text_indices,
1089
def _least_readv_node_readv(self, nodes):
1090
"""Generate request groups for nodes using the least readv's.
1092
:param nodes: An iterable of graph index nodes.
1093
:return: Total node count and an iterator of the data needed to perform
1094
readvs to obtain the data for nodes. Each item yielded by the
1095
iterator is a tuple with:
1096
index, readv_vector, node_vector. readv_vector is a list ready to
1097
hand to the transport readv method, and node_vector is a list of
1098
(key, eol_flag, references) for the the node retrieved by the
1099
matching readv_vector.
1101
# group by pack so we do one readv per pack
1102
nodes = sorted(nodes)
1105
for index, key, value, references in nodes:
1106
if index not in request_groups:
1107
request_groups[index] = []
1108
request_groups[index].append((key, value, references))
1110
for index, items in request_groups.iteritems():
1111
pack_readv_requests = []
1112
for key, value, references in items:
1113
# ---- KnitGraphIndex.get_position
1114
bits = value[1:].split(' ')
1115
offset, length = int(bits[0]), int(bits[1])
1116
pack_readv_requests.append(
1117
((offset, length), (key, value[0], references)))
1118
# linear scan up the pack to maximum range combining.
1119
pack_readv_requests.sort()
1120
# split out the readv and the node data.
1121
pack_readv = [readv for readv, node in pack_readv_requests]
1122
node_vector = [node for readv, node in pack_readv_requests]
1123
result.append((index, pack_readv, node_vector))
1124
return total, result
742
1126
def _log_copied_texts(self):
743
1127
if 'pack' in debug.debug_flags:
756
1159
return new_pack.data_inserted()
1162
class OptimisingPacker(Packer):
1163
"""A packer which spends more time to create better disk layouts."""
1165
def _revision_node_readv(self, revision_nodes):
1166
"""Return the total revisions and the readv's to issue.
1168
This sort places revisions in topological order with the ancestors
1171
:param revision_nodes: The revision index contents for the packs being
1172
incorporated into the new pack.
1173
:return: As per _least_readv_node_readv.
1175
# build an ancestors dict
1178
for index, key, value, references in revision_nodes:
1179
ancestors[key] = references[0]
1180
by_key[key] = (index, value, references)
1181
order = tsort.topo_sort(ancestors)
1183
# Single IO is pathological, but it will work as a starting point.
1185
for key in reversed(order):
1186
index, value, references = by_key[key]
1187
# ---- KnitGraphIndex.get_position
1188
bits = value[1:].split(' ')
1189
offset, length = int(bits[0]), int(bits[1])
1191
(index, [(offset, length)], [(key, value[0], references)]))
1192
# TODO: combine requests in the same index that are in ascending order.
1193
return total, requests
1195
def open_pack(self):
1196
"""Open a pack for the pack we are creating."""
1197
new_pack = super(OptimisingPacker, self).open_pack()
1198
# Turn on the optimization flags for all the index builders.
1199
new_pack.revision_index.set_optimize(for_size=True)
1200
new_pack.inventory_index.set_optimize(for_size=True)
1201
new_pack.text_index.set_optimize(for_size=True)
1202
new_pack.signature_index.set_optimize(for_size=True)
1206
class ReconcilePacker(Packer):
1207
"""A packer which regenerates indices etc as it copies.
1209
This is used by ``bzr reconcile`` to cause parent text pointers to be
1213
def _extra_init(self):
1214
self._data_changed = False
1216
def _process_inventory_lines(self, inv_lines):
1217
"""Generate a text key reference map rather for reconciling with."""
1218
repo = self._pack_collection.repo
1219
refs = repo._find_text_key_references_from_xml_inventory_lines(
1221
self._text_refs = refs
1222
# during reconcile we:
1223
# - convert unreferenced texts to full texts
1224
# - correct texts which reference a text not copied to be full texts
1225
# - copy all others as-is but with corrected parents.
1226
# - so at this point we don't know enough to decide what becomes a full
1228
self._text_filter = None
1230
def _copy_text_texts(self):
1231
"""generate what texts we should have and then copy."""
1232
self.pb.update("Copying content texts", 3)
1233
# we have three major tasks here:
1234
# 1) generate the ideal index
1235
repo = self._pack_collection.repo
1236
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1237
_1, key, _2, refs in
1238
self.new_pack.revision_index.iter_all_entries()])
1239
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1240
# 2) generate a text_nodes list that contains all the deltas that can
1241
# be used as-is, with corrected parents.
1244
discarded_nodes = []
1245
NULL_REVISION = _mod_revision.NULL_REVISION
1246
text_index_map, text_nodes = self._get_text_nodes()
1247
for node in text_nodes:
1253
ideal_parents = tuple(ideal_index[node[1]])
1255
discarded_nodes.append(node)
1256
self._data_changed = True
1258
if ideal_parents == (NULL_REVISION,):
1260
if ideal_parents == node[3][0]:
1262
ok_nodes.append(node)
1263
elif ideal_parents[0:1] == node[3][0][0:1]:
1264
# the left most parent is the same, or there are no parents
1265
# today. Either way, we can preserve the representation as
1266
# long as we change the refs to be inserted.
1267
self._data_changed = True
1268
ok_nodes.append((node[0], node[1], node[2],
1269
(ideal_parents, node[3][1])))
1270
self._data_changed = True
1272
# Reinsert this text completely
1273
bad_texts.append((node[1], ideal_parents))
1274
self._data_changed = True
1275
# we're finished with some data.
1278
# 3) bulk copy the ok data
1279
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1280
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1281
self.new_pack.text_index, readv_group_iter, total_items))
1282
# 4) adhoc copy all the other texts.
1283
# We have to topologically insert all texts otherwise we can fail to
1284
# reconcile when parts of a single delta chain are preserved intact,
1285
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1286
# reinserted, and if d3 has incorrect parents it will also be
1287
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1288
# copied), so we will try to delta, but d2 is not currently able to be
1289
# extracted because it's basis d1 is not present. Topologically sorting
1290
# addresses this. The following generates a sort for all the texts that
1291
# are being inserted without having to reference the entire text key
1292
# space (we only topo sort the revisions, which is smaller).
1293
topo_order = tsort.topo_sort(ancestors)
1294
rev_order = dict(zip(topo_order, range(len(topo_order))))
1295
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1296
transaction = repo.get_transaction()
1297
file_id_index = GraphIndexPrefixAdapter(
1298
self.new_pack.text_index,
1300
add_nodes_callback=self.new_pack.text_index.add_nodes)
1301
data_access = _DirectPackAccess(
1302
{self.new_pack.text_index:self.new_pack.access_tuple()})
1303
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1304
self.new_pack.access_tuple())
1305
output_texts = KnitVersionedFiles(
1306
_KnitGraphIndex(self.new_pack.text_index,
1307
add_callback=self.new_pack.text_index.add_nodes,
1308
deltas=True, parents=True, is_locked=repo.is_locked),
1309
data_access=data_access, max_delta_chain=200)
1310
for key, parent_keys in bad_texts:
1311
# We refer to the new pack to delta data being output.
1312
# A possible improvement would be to catch errors on short reads
1313
# and only flush then.
1314
self.new_pack.flush()
1316
for parent_key in parent_keys:
1317
if parent_key[0] != key[0]:
1318
# Graph parents must match the fileid
1319
raise errors.BzrError('Mismatched key parent %r:%r' %
1321
parents.append(parent_key[1])
1322
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1323
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1324
output_texts.add_lines(key, parent_keys, text_lines,
1325
random_id=True, check_content=False)
1326
# 5) check that nothing inserted has a reference outside the keyspace.
1327
missing_text_keys = self.new_pack.text_index._external_references()
1328
if missing_text_keys:
1329
raise errors.BzrCheckError('Reference to missing compression parents %r'
1330
% (missing_text_keys,))
1331
self._log_copied_texts()
1333
def _use_pack(self, new_pack):
1334
"""Override _use_pack to check for reconcile having changed content."""
1335
# XXX: we might be better checking this at the copy time.
1336
original_inventory_keys = set()
1337
inv_index = self._pack_collection.inventory_index.combined_index
1338
for entry in inv_index.iter_all_entries():
1339
original_inventory_keys.add(entry[1])
1340
new_inventory_keys = set()
1341
for entry in new_pack.inventory_index.iter_all_entries():
1342
new_inventory_keys.add(entry[1])
1343
if new_inventory_keys != original_inventory_keys:
1344
self._data_changed = True
1345
return new_pack.data_inserted() and self._data_changed
759
1348
class RepositoryPackCollection(object):
760
1349
"""Management of packs within a repository.
762
1351
:ivar _names: map of {pack_name: (index_size,)}
766
resumed_pack_factory = None
767
normal_packer_class = None
768
optimising_packer_class = None
1354
pack_factory = NewPack
770
1356
def __init__(self, repo, transport, index_transport, upload_transport,
771
1357
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
2131
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
2133
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2134
_commit_builder_class, _serializer)
2135
index_transport = self._transport.clone('indices')
2136
self._pack_collection = RepositoryPackCollection(self, self._transport,
2138
self._transport.clone('upload'),
2139
self._transport.clone('packs'),
2140
_format.index_builder_class,
2141
_format.index_class,
2142
use_chk_index=self._format.supports_chks,
2144
self.inventories = KnitVersionedFiles(
2145
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2146
add_callback=self._pack_collection.inventory_index.add_callback,
2147
deltas=True, parents=True, is_locked=self.is_locked),
2148
data_access=self._pack_collection.inventory_index.data_access,
2149
max_delta_chain=200)
2150
self.revisions = KnitVersionedFiles(
2151
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2152
add_callback=self._pack_collection.revision_index.add_callback,
2153
deltas=False, parents=True, is_locked=self.is_locked,
2154
track_external_parent_refs=True),
2155
data_access=self._pack_collection.revision_index.data_access,
2157
self.signatures = KnitVersionedFiles(
2158
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2159
add_callback=self._pack_collection.signature_index.add_callback,
2160
deltas=False, parents=False, is_locked=self.is_locked),
2161
data_access=self._pack_collection.signature_index.data_access,
2163
self.texts = KnitVersionedFiles(
2164
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2165
add_callback=self._pack_collection.text_index.add_callback,
2166
deltas=True, parents=True, is_locked=self.is_locked),
2167
data_access=self._pack_collection.text_index.data_access,
2168
max_delta_chain=200)
2169
if _format.supports_chks:
2170
# No graph, no compression:- references from chks are between
2171
# different objects not temporal versions of the same; and without
2172
# some sort of temporal structure knit compression will just fail.
2173
self.chk_bytes = KnitVersionedFiles(
2174
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2175
add_callback=self._pack_collection.chk_index.add_callback,
2176
deltas=False, parents=False, is_locked=self.is_locked),
2177
data_access=self._pack_collection.chk_index.data_access,
2180
self.chk_bytes = None
2181
# True when the repository object is 'write locked' (as opposed to the
2182
# physical lock only taken out around changes to the pack-names list.)
2183
# Another way to represent this would be a decorator around the control
2184
# files object that presents logical locks as physical ones - if this
2185
# gets ugly consider that alternative design. RBC 20071011
2186
self._write_lock_count = 0
2187
self._transaction = None
2189
self._reconcile_does_inventory_gc = True
1667
2190
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()
2191
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()]
2193
def _warn_if_deprecated(self):
2194
# This class isn't deprecated, but one sub-format is
2195
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2196
from bzrlib import repository
2197
if repository._deprecation_warning_done:
2199
repository._deprecation_warning_done = True
2200
warning("Format %s for %s is deprecated - please use"
2201
" 'bzr upgrade --1.6.1-rich-root'"
2202
% (self._format, self.bzrdir.transport.base))
1680
2204
def _abort_write_group(self):
1681
self.revisions._index._key_dependencies.clear()
1682
2205
self._pack_collection._abort_write_group()
2207
def _find_inconsistent_revision_parents(self):
2208
"""Find revisions with incorrectly cached parents.
2210
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2211
parents-in-revision).
2213
if not self.is_locked():
2214
raise errors.ObjectNotLocked(self)
2215
pb = ui.ui_factory.nested_progress_bar()
2218
revision_nodes = self._pack_collection.revision_index \
2219
.combined_index.iter_all_entries()
2220
index_positions = []
2221
# Get the cached index values for all revisions, and also the
2222
# location in each index of the revision text so we can perform
2224
for index, key, value, refs in revision_nodes:
2225
node = (index, key, value, refs)
2226
index_memo = self.revisions._index._node_to_position(node)
2227
if index_memo[0] != index:
2228
raise AssertionError('%r != %r' % (index_memo[0], index))
2229
index_positions.append((index_memo, key[0],
2230
tuple(parent[0] for parent in refs[0])))
2231
pb.update("Reading revision index", 0, 0)
2232
index_positions.sort()
2234
pb.update("Checking cached revision graph", 0,
2235
len(index_positions))
2236
for offset in xrange(0, len(index_positions), 1000):
2237
pb.update("Checking cached revision graph", offset)
2238
to_query = index_positions[offset:offset + batch_size]
2241
rev_ids = [item[1] for item in to_query]
2242
revs = self.get_revisions(rev_ids)
2243
for revision, item in zip(revs, to_query):
2244
index_parents = item[2]
2245
rev_parents = tuple(revision.parent_ids)
2246
if index_parents != rev_parents:
2247
result.append((revision.revision_id, index_parents,
1684
2253
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))
2254
return graph.CachingParentsProvider(self)
1690
2256
def _refresh_data(self):
1691
2257
if not self.is_locked():
1693
2259
self._pack_collection.reload_pack_names()
1694
self._unstacked_provider.disable_cache()
1695
self._unstacked_provider.enable_cache()
1697
2261
def _start_write_group(self):
1698
2262
self._pack_collection._start_write_group()
1700
2264
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()
2265
return self._pack_collection._commit_write_group()
1709
2267
def suspend_write_group(self):
1710
2268
# XXX check self._write_group is self.get_transaction()?
1711
2269
tokens = self._pack_collection._suspend_write_group()
1712
self.revisions._index._key_dependencies.clear()
1713
2270
self._write_group = None
1716
2273
def _resume_write_group(self, tokens):
1717
2274
self._start_write_group()
1719
self._pack_collection._resume_write_group(tokens)
1720
except errors.UnresumableWriteGroup:
1721
self._abort_write_group()
2275
self._pack_collection._resume_write_group(tokens)
1723
2276
for pack in self._pack_collection._resumed_packs:
1724
2277
self.revisions._index.scan_unvalidated_index(pack.revision_index)
1910
2440
_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
2443
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2444
"""A no-subtrees parameterized Pack repository.
2446
This format was introduced in 0.92.
2449
repository_class = KnitPackRepository
2450
_commit_builder_class = PackCommitBuilder
2452
def _serializer(self):
2453
return xml5.serializer_v5
2454
# What index classes to use
2455
index_builder_class = InMemoryGraphIndex
2456
index_class = GraphIndex
2458
def _get_matching_bzrdir(self):
2459
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2461
def _ignore_setting_bzrdir(self, format):
2464
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2466
def get_format_string(self):
2467
"""See RepositoryFormat.get_format_string()."""
2468
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2470
def get_format_description(self):
2471
"""See RepositoryFormat.get_format_description()."""
2472
return "Packs containing knits without subtree support"
2474
def check_conversion_target(self, target_format):
2478
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2479
"""A subtrees parameterized Pack repository.
2481
This repository format uses the xml7 serializer to get:
2482
- support for recording full info about the tree root
2483
- support for recording tree-references
2485
This format was introduced in 0.92.
2488
repository_class = KnitPackRepository
2489
_commit_builder_class = PackRootCommitBuilder
2490
rich_root_data = True
2491
supports_tree_reference = True
2493
def _serializer(self):
2494
return xml7.serializer_v7
2495
# What index classes to use
2496
index_builder_class = InMemoryGraphIndex
2497
index_class = GraphIndex
2499
def _get_matching_bzrdir(self):
2500
return bzrdir.format_registry.make_bzrdir(
2501
'pack-0.92-subtree')
2503
def _ignore_setting_bzrdir(self, format):
2506
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2508
def check_conversion_target(self, target_format):
2509
if not target_format.rich_root_data:
2510
raise errors.BadConversionTarget(
2511
'Does not support rich root data.', target_format)
2512
if not getattr(target_format, 'supports_tree_reference', False):
2513
raise errors.BadConversionTarget(
2514
'Does not support nested trees', target_format)
2516
def get_format_string(self):
2517
"""See RepositoryFormat.get_format_string()."""
2518
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2520
def get_format_description(self):
2521
"""See RepositoryFormat.get_format_description()."""
2522
return "Packs containing knits with subtree support\n"
2525
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2526
"""A rich-root, no subtrees parameterized Pack repository.
2528
This repository format uses the xml6 serializer to get:
2529
- support for recording full info about the tree root
2531
This format was introduced in 1.0.
2534
repository_class = KnitPackRepository
2535
_commit_builder_class = PackRootCommitBuilder
2536
rich_root_data = True
2537
supports_tree_reference = False
2539
def _serializer(self):
2540
return xml6.serializer_v6
2541
# What index classes to use
2542
index_builder_class = InMemoryGraphIndex
2543
index_class = GraphIndex
2545
def _get_matching_bzrdir(self):
2546
return bzrdir.format_registry.make_bzrdir(
2549
def _ignore_setting_bzrdir(self, format):
2552
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2554
def check_conversion_target(self, target_format):
2555
if not target_format.rich_root_data:
2556
raise errors.BadConversionTarget(
2557
'Does not support rich root data.', target_format)
2559
def get_format_string(self):
2560
"""See RepositoryFormat.get_format_string()."""
2561
return ("Bazaar pack repository format 1 with rich root"
2562
" (needs bzr 1.0)\n")
2564
def get_format_description(self):
2565
"""See RepositoryFormat.get_format_description()."""
2566
return "Packs containing knits with rich root support\n"
2569
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2570
"""Repository that supports external references to allow stacking.
2574
Supports external lookups, which results in non-truncated ghosts after
2575
reconcile compared to pack-0.92 formats.
2578
repository_class = KnitPackRepository
2579
_commit_builder_class = PackCommitBuilder
2580
supports_external_lookups = True
2581
# What index classes to use
2582
index_builder_class = InMemoryGraphIndex
2583
index_class = GraphIndex
2586
def _serializer(self):
2587
return xml5.serializer_v5
2589
def _get_matching_bzrdir(self):
2590
return bzrdir.format_registry.make_bzrdir('1.6')
2592
def _ignore_setting_bzrdir(self, format):
2595
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2597
def get_format_string(self):
2598
"""See RepositoryFormat.get_format_string()."""
2599
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2601
def get_format_description(self):
2602
"""See RepositoryFormat.get_format_description()."""
2603
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2605
def check_conversion_target(self, target_format):
2609
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2610
"""A repository with rich roots and stacking.
2612
New in release 1.6.1.
2614
Supports stacking on other repositories, allowing data to be accessed
2615
without being stored locally.
2618
repository_class = KnitPackRepository
2619
_commit_builder_class = PackRootCommitBuilder
2620
rich_root_data = True
2621
supports_tree_reference = False # no subtrees
2622
supports_external_lookups = True
2623
# What index classes to use
2624
index_builder_class = InMemoryGraphIndex
2625
index_class = GraphIndex
2628
def _serializer(self):
2629
return xml6.serializer_v6
2631
def _get_matching_bzrdir(self):
2632
return bzrdir.format_registry.make_bzrdir(
2635
def _ignore_setting_bzrdir(self, format):
2638
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2640
def check_conversion_target(self, target_format):
2641
if not target_format.rich_root_data:
2642
raise errors.BadConversionTarget(
2643
'Does not support rich root data.', target_format)
2645
def get_format_string(self):
2646
"""See RepositoryFormat.get_format_string()."""
2647
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2649
def get_format_description(self):
2650
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2653
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2654
"""A repository with rich roots and external references.
2658
Supports external lookups, which results in non-truncated ghosts after
2659
reconcile compared to pack-0.92 formats.
2661
This format was deprecated because the serializer it uses accidentally
2662
supported subtrees, when the format was not intended to. This meant that
2663
someone could accidentally fetch from an incorrect repository.
2666
repository_class = KnitPackRepository
2667
_commit_builder_class = PackRootCommitBuilder
2668
rich_root_data = True
2669
supports_tree_reference = False # no subtrees
2671
supports_external_lookups = True
2672
# What index classes to use
2673
index_builder_class = InMemoryGraphIndex
2674
index_class = GraphIndex
2677
def _serializer(self):
2678
return xml7.serializer_v7
2680
def _get_matching_bzrdir(self):
2681
matching = bzrdir.format_registry.make_bzrdir(
2683
matching.repository_format = self
2686
def _ignore_setting_bzrdir(self, format):
2689
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2691
def check_conversion_target(self, target_format):
2692
if not target_format.rich_root_data:
2693
raise errors.BadConversionTarget(
2694
'Does not support rich root data.', target_format)
2696
def get_format_string(self):
2697
"""See RepositoryFormat.get_format_string()."""
2698
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2700
def get_format_description(self):
2701
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2705
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2706
"""A repository with stacking and btree indexes,
2707
without rich roots or subtrees.
2709
This is equivalent to pack-1.6 with B+Tree indices.
2712
repository_class = KnitPackRepository
2713
_commit_builder_class = PackCommitBuilder
2714
supports_external_lookups = True
2715
# What index classes to use
2716
index_builder_class = BTreeBuilder
2717
index_class = BTreeGraphIndex
2720
def _serializer(self):
2721
return xml5.serializer_v5
2723
def _get_matching_bzrdir(self):
2724
return bzrdir.format_registry.make_bzrdir('1.9')
2726
def _ignore_setting_bzrdir(self, format):
2729
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2731
def get_format_string(self):
2732
"""See RepositoryFormat.get_format_string()."""
2733
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2735
def get_format_description(self):
2736
"""See RepositoryFormat.get_format_description()."""
2737
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2739
def check_conversion_target(self, target_format):
2743
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2744
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2746
1.6-rich-root with B+Tree indices.
2749
repository_class = KnitPackRepository
2750
_commit_builder_class = PackRootCommitBuilder
2751
rich_root_data = True
2752
supports_tree_reference = False # no subtrees
2753
supports_external_lookups = True
2754
# What index classes to use
2755
index_builder_class = BTreeBuilder
2756
index_class = BTreeGraphIndex
2759
def _serializer(self):
2760
return xml6.serializer_v6
2762
def _get_matching_bzrdir(self):
2763
return bzrdir.format_registry.make_bzrdir(
2766
def _ignore_setting_bzrdir(self, format):
2769
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2771
def check_conversion_target(self, target_format):
2772
if not target_format.rich_root_data:
2773
raise errors.BadConversionTarget(
2774
'Does not support rich root data.', target_format)
2776
def get_format_string(self):
2777
"""See RepositoryFormat.get_format_string()."""
2778
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2780
def get_format_description(self):
2781
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2784
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2785
"""A subtrees development repository.
2787
This format should be retained until the second release after bzr 1.7.
2789
1.6.1-subtree[as it might have been] with B+Tree indices.
2791
This is [now] retained until we have a CHK based subtree format in
2795
repository_class = KnitPackRepository
2796
_commit_builder_class = PackRootCommitBuilder
2797
rich_root_data = True
2798
supports_tree_reference = True
2799
supports_external_lookups = True
2800
# What index classes to use
2801
index_builder_class = BTreeBuilder
2802
index_class = BTreeGraphIndex
2805
def _serializer(self):
2806
return xml7.serializer_v7
2808
def _get_matching_bzrdir(self):
2809
return bzrdir.format_registry.make_bzrdir(
2810
'development-subtree')
2812
def _ignore_setting_bzrdir(self, format):
2815
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2817
def check_conversion_target(self, target_format):
2818
if not target_format.rich_root_data:
2819
raise errors.BadConversionTarget(
2820
'Does not support rich root data.', target_format)
2821
if not getattr(target_format, 'supports_tree_reference', False):
2822
raise errors.BadConversionTarget(
2823
'Does not support nested trees', target_format)
2825
def get_format_string(self):
2826
"""See RepositoryFormat.get_format_string()."""
2827
return ("Bazaar development format 2 with subtree support "
2828
"(needs bzr.dev from before 1.8)\n")
2830
def get_format_description(self):
2831
"""See RepositoryFormat.get_format_description()."""
2832
return ("Development repository format, currently the same as "
2833
"1.6.1-subtree with B+Tree indices.\n")