822
743
Sets self._text_filter appropriately.
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)
745
raise NotImplementedError(self._copy_inventory_texts)
855
747
def _copy_text_texts(self):
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()
748
raise NotImplementedError(self._copy_text_texts)
882
750
def _create_pack_from_packs(self):
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
751
raise NotImplementedError(self._create_pack_from_packs)
1126
753
def _log_copied_texts(self):
1127
754
if 'pack' in debug.debug_flags:
1159
767
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
1348
770
class RepositoryPackCollection(object):
1349
771
"""Management of packs within a repository.
1351
773
:ivar _names: map of {pack_name: (index_size,)}
1354
pack_factory = NewPack
777
resumed_pack_factory = None
778
normal_packer_class = None
779
optimising_packer_class = None
1356
781
def __init__(self, repo, transport, index_transport, upload_transport,
1357
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
2131
1688
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
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
data_access=self._pack_collection.revision_index.data_access,
2156
self.signatures = KnitVersionedFiles(
2157
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2158
add_callback=self._pack_collection.signature_index.add_callback,
2159
deltas=False, parents=False, is_locked=self.is_locked),
2160
data_access=self._pack_collection.signature_index.data_access,
2162
self.texts = KnitVersionedFiles(
2163
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2164
add_callback=self._pack_collection.text_index.add_callback,
2165
deltas=True, parents=True, is_locked=self.is_locked),
2166
data_access=self._pack_collection.text_index.data_access,
2167
max_delta_chain=200)
2168
if _format.supports_chks:
2169
# No graph, no compression:- references from chks are between
2170
# different objects not temporal versions of the same; and without
2171
# some sort of temporal structure knit compression will just fail.
2172
self.chk_bytes = KnitVersionedFiles(
2173
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2174
add_callback=self._pack_collection.chk_index.add_callback,
2175
deltas=False, parents=False, is_locked=self.is_locked),
2176
data_access=self._pack_collection.chk_index.data_access,
2179
self.chk_bytes = None
2180
# True when the repository object is 'write locked' (as opposed to the
2181
# physical lock only taken out around changes to the pack-names list.)
2182
# Another way to represent this would be a decorator around the control
2183
# files object that presents logical locks as physical ones - if this
2184
# gets ugly consider that alternative design. RBC 20071011
2185
self._write_lock_count = 0
2186
self._transaction = None
2188
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
2189
1693
self._reconcile_fixes_text_parents = True
2190
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()
2192
def _warn_if_deprecated(self):
2193
# This class isn't deprecated, but one sub-format is
2194
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2195
from bzrlib import repository
2196
if repository._deprecation_warning_done:
2198
repository._deprecation_warning_done = True
2199
warning("Format %s for %s is deprecated - please use"
2200
" 'bzr upgrade --1.6.1-rich-root'"
2201
% (self._format, self.bzrdir.transport.base))
1702
def _all_revision_ids(self):
1703
"""See Repository.all_revision_ids()."""
1704
return [key[0] for key in self.revisions.keys()]
2203
1706
def _abort_write_group(self):
1707
self.revisions._index._key_dependencies.clear()
2204
1708
self._pack_collection._abort_write_group()
2206
def _find_inconsistent_revision_parents(self):
2207
"""Find revisions with incorrectly cached parents.
2209
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2210
parents-in-revision).
2212
if not self.is_locked():
2213
raise errors.ObjectNotLocked(self)
2214
pb = ui.ui_factory.nested_progress_bar()
2217
revision_nodes = self._pack_collection.revision_index \
2218
.combined_index.iter_all_entries()
2219
index_positions = []
2220
# Get the cached index values for all revisions, and also the
2221
# location in each index of the revision text so we can perform
2223
for index, key, value, refs in revision_nodes:
2224
node = (index, key, value, refs)
2225
index_memo = self.revisions._index._node_to_position(node)
2226
if index_memo[0] != index:
2227
raise AssertionError('%r != %r' % (index_memo[0], index))
2228
index_positions.append((index_memo, key[0],
2229
tuple(parent[0] for parent in refs[0])))
2230
pb.update("Reading revision index", 0, 0)
2231
index_positions.sort()
2233
pb.update("Checking cached revision graph", 0,
2234
len(index_positions))
2235
for offset in xrange(0, len(index_positions), 1000):
2236
pb.update("Checking cached revision graph", offset)
2237
to_query = index_positions[offset:offset + batch_size]
2240
rev_ids = [item[1] for item in to_query]
2241
revs = self.get_revisions(rev_ids)
2242
for revision, item in zip(revs, to_query):
2243
index_parents = item[2]
2244
rev_parents = tuple(revision.parent_ids)
2245
if index_parents != rev_parents:
2246
result.append((revision.revision_id, index_parents,
2252
1710
def _make_parents_provider(self):
2253
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))
2255
1716
def _refresh_data(self):
2256
1717
if not self.is_locked():
2258
1719
self._pack_collection.reload_pack_names()
1720
self._unstacked_provider.disable_cache()
1721
self._unstacked_provider.enable_cache()
2260
1723
def _start_write_group(self):
2261
1724
self._pack_collection._start_write_group()
2263
1726
def _commit_write_group(self):
2264
return self._pack_collection._commit_write_group()
1727
hint = self._pack_collection._commit_write_group()
1728
self.revisions._index._key_dependencies.clear()
1729
# The commit may have added keys that were previously cached as
1730
# missing, so reset the cache.
1731
self._unstacked_provider.disable_cache()
1732
self._unstacked_provider.enable_cache()
2266
1735
def suspend_write_group(self):
2267
1736
# XXX check self._write_group is self.get_transaction()?
2268
1737
tokens = self._pack_collection._suspend_write_group()
1738
self.revisions._index._key_dependencies.clear()
2269
1739
self._write_group = None
2272
1742
def _resume_write_group(self, tokens):
2273
1743
self._start_write_group()
2274
self._pack_collection._resume_write_group(tokens)
1745
self._pack_collection._resume_write_group(tokens)
1746
except errors.UnresumableWriteGroup:
1747
self._abort_write_group()
1749
for pack in self._pack_collection._resumed_packs:
1750
self.revisions._index.scan_unvalidated_index(pack.revision_index)
2276
1752
def get_transaction(self):
2277
1753
if self._write_lock_count:
2437
1936
_serializer=self._serializer)
2440
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2441
"""A no-subtrees parameterized Pack repository.
2443
This format was introduced in 0.92.
2446
repository_class = KnitPackRepository
2447
_commit_builder_class = PackCommitBuilder
2449
def _serializer(self):
2450
return xml5.serializer_v5
2451
# What index classes to use
2452
index_builder_class = InMemoryGraphIndex
2453
index_class = GraphIndex
2455
def _get_matching_bzrdir(self):
2456
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2458
def _ignore_setting_bzrdir(self, format):
2461
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2463
def get_format_string(self):
2464
"""See RepositoryFormat.get_format_string()."""
2465
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2467
def get_format_description(self):
2468
"""See RepositoryFormat.get_format_description()."""
2469
return "Packs containing knits without subtree support"
2471
def check_conversion_target(self, target_format):
2475
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2476
"""A subtrees parameterized Pack repository.
2478
This repository format uses the xml7 serializer to get:
2479
- support for recording full info about the tree root
2480
- support for recording tree-references
2482
This format was introduced in 0.92.
2485
repository_class = KnitPackRepository
2486
_commit_builder_class = PackRootCommitBuilder
2487
rich_root_data = True
2488
supports_tree_reference = True
2490
def _serializer(self):
2491
return xml7.serializer_v7
2492
# What index classes to use
2493
index_builder_class = InMemoryGraphIndex
2494
index_class = GraphIndex
2496
def _get_matching_bzrdir(self):
2497
return bzrdir.format_registry.make_bzrdir(
2498
'pack-0.92-subtree')
2500
def _ignore_setting_bzrdir(self, format):
2503
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2505
def check_conversion_target(self, target_format):
2506
if not target_format.rich_root_data:
2507
raise errors.BadConversionTarget(
2508
'Does not support rich root data.', target_format)
2509
if not getattr(target_format, 'supports_tree_reference', False):
2510
raise errors.BadConversionTarget(
2511
'Does not support nested trees', target_format)
2513
def get_format_string(self):
2514
"""See RepositoryFormat.get_format_string()."""
2515
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2517
def get_format_description(self):
2518
"""See RepositoryFormat.get_format_description()."""
2519
return "Packs containing knits with subtree support\n"
2522
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2523
"""A rich-root, no subtrees parameterized Pack repository.
2525
This repository format uses the xml6 serializer to get:
2526
- support for recording full info about the tree root
2528
This format was introduced in 1.0.
2531
repository_class = KnitPackRepository
2532
_commit_builder_class = PackRootCommitBuilder
2533
rich_root_data = True
2534
supports_tree_reference = False
2536
def _serializer(self):
2537
return xml6.serializer_v6
2538
# What index classes to use
2539
index_builder_class = InMemoryGraphIndex
2540
index_class = GraphIndex
2542
def _get_matching_bzrdir(self):
2543
return bzrdir.format_registry.make_bzrdir(
2546
def _ignore_setting_bzrdir(self, format):
2549
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2551
def check_conversion_target(self, target_format):
2552
if not target_format.rich_root_data:
2553
raise errors.BadConversionTarget(
2554
'Does not support rich root data.', target_format)
2556
def get_format_string(self):
2557
"""See RepositoryFormat.get_format_string()."""
2558
return ("Bazaar pack repository format 1 with rich root"
2559
" (needs bzr 1.0)\n")
2561
def get_format_description(self):
2562
"""See RepositoryFormat.get_format_description()."""
2563
return "Packs containing knits with rich root support\n"
2566
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2567
"""Repository that supports external references to allow stacking.
2571
Supports external lookups, which results in non-truncated ghosts after
2572
reconcile compared to pack-0.92 formats.
2575
repository_class = KnitPackRepository
2576
_commit_builder_class = PackCommitBuilder
2577
supports_external_lookups = True
2578
# What index classes to use
2579
index_builder_class = InMemoryGraphIndex
2580
index_class = GraphIndex
2583
def _serializer(self):
2584
return xml5.serializer_v5
2586
def _get_matching_bzrdir(self):
2587
return bzrdir.format_registry.make_bzrdir('1.6')
2589
def _ignore_setting_bzrdir(self, format):
2592
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2594
def get_format_string(self):
2595
"""See RepositoryFormat.get_format_string()."""
2596
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2598
def get_format_description(self):
2599
"""See RepositoryFormat.get_format_description()."""
2600
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2602
def check_conversion_target(self, target_format):
2606
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2607
"""A repository with rich roots and stacking.
2609
New in release 1.6.1.
2611
Supports stacking on other repositories, allowing data to be accessed
2612
without being stored locally.
2615
repository_class = KnitPackRepository
2616
_commit_builder_class = PackRootCommitBuilder
2617
rich_root_data = True
2618
supports_tree_reference = False # no subtrees
2619
supports_external_lookups = True
2620
# What index classes to use
2621
index_builder_class = InMemoryGraphIndex
2622
index_class = GraphIndex
2625
def _serializer(self):
2626
return xml6.serializer_v6
2628
def _get_matching_bzrdir(self):
2629
return bzrdir.format_registry.make_bzrdir(
2632
def _ignore_setting_bzrdir(self, format):
2635
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2637
def check_conversion_target(self, target_format):
2638
if not target_format.rich_root_data:
2639
raise errors.BadConversionTarget(
2640
'Does not support rich root data.', target_format)
2642
def get_format_string(self):
2643
"""See RepositoryFormat.get_format_string()."""
2644
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2646
def get_format_description(self):
2647
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2650
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2651
"""A repository with rich roots and external references.
2655
Supports external lookups, which results in non-truncated ghosts after
2656
reconcile compared to pack-0.92 formats.
2658
This format was deprecated because the serializer it uses accidentally
2659
supported subtrees, when the format was not intended to. This meant that
2660
someone could accidentally fetch from an incorrect repository.
2663
repository_class = KnitPackRepository
2664
_commit_builder_class = PackRootCommitBuilder
2665
rich_root_data = True
2666
supports_tree_reference = False # no subtrees
2668
supports_external_lookups = True
2669
# What index classes to use
2670
index_builder_class = InMemoryGraphIndex
2671
index_class = GraphIndex
2674
def _serializer(self):
2675
return xml7.serializer_v7
2677
def _get_matching_bzrdir(self):
2678
matching = bzrdir.format_registry.make_bzrdir(
2680
matching.repository_format = self
2683
def _ignore_setting_bzrdir(self, format):
2686
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2688
def check_conversion_target(self, target_format):
2689
if not target_format.rich_root_data:
2690
raise errors.BadConversionTarget(
2691
'Does not support rich root data.', target_format)
2693
def get_format_string(self):
2694
"""See RepositoryFormat.get_format_string()."""
2695
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2697
def get_format_description(self):
2698
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2702
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2703
"""A repository with stacking and btree indexes,
2704
without rich roots or subtrees.
2706
This is equivalent to pack-1.6 with B+Tree indices.
2709
repository_class = KnitPackRepository
2710
_commit_builder_class = PackCommitBuilder
2711
supports_external_lookups = True
2712
# What index classes to use
2713
index_builder_class = BTreeBuilder
2714
index_class = BTreeGraphIndex
2717
def _serializer(self):
2718
return xml5.serializer_v5
2720
def _get_matching_bzrdir(self):
2721
return bzrdir.format_registry.make_bzrdir('1.9')
2723
def _ignore_setting_bzrdir(self, format):
2726
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2728
def get_format_string(self):
2729
"""See RepositoryFormat.get_format_string()."""
2730
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2732
def get_format_description(self):
2733
"""See RepositoryFormat.get_format_description()."""
2734
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2736
def check_conversion_target(self, target_format):
2740
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2741
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2743
1.6-rich-root with B+Tree indices.
2746
repository_class = KnitPackRepository
2747
_commit_builder_class = PackRootCommitBuilder
2748
rich_root_data = True
2749
supports_tree_reference = False # no subtrees
2750
supports_external_lookups = True
2751
# What index classes to use
2752
index_builder_class = BTreeBuilder
2753
index_class = BTreeGraphIndex
2756
def _serializer(self):
2757
return xml6.serializer_v6
2759
def _get_matching_bzrdir(self):
2760
return bzrdir.format_registry.make_bzrdir(
2763
def _ignore_setting_bzrdir(self, format):
2766
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2768
def check_conversion_target(self, target_format):
2769
if not target_format.rich_root_data:
2770
raise errors.BadConversionTarget(
2771
'Does not support rich root data.', target_format)
2773
def get_format_string(self):
2774
"""See RepositoryFormat.get_format_string()."""
2775
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2777
def get_format_description(self):
2778
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2781
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2782
"""A subtrees development repository.
2784
This format should be retained until the second release after bzr 1.7.
2786
1.6.1-subtree[as it might have been] with B+Tree indices.
2788
This is [now] retained until we have a CHK based subtree format in
2792
repository_class = KnitPackRepository
2793
_commit_builder_class = PackRootCommitBuilder
2794
rich_root_data = True
2795
supports_tree_reference = True
2796
supports_external_lookups = True
2797
# What index classes to use
2798
index_builder_class = BTreeBuilder
2799
index_class = BTreeGraphIndex
2802
def _serializer(self):
2803
return xml7.serializer_v7
2805
def _get_matching_bzrdir(self):
2806
return bzrdir.format_registry.make_bzrdir(
2807
'development-subtree')
2809
def _ignore_setting_bzrdir(self, format):
2812
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2814
def check_conversion_target(self, target_format):
2815
if not target_format.rich_root_data:
2816
raise errors.BadConversionTarget(
2817
'Does not support rich root data.', target_format)
2818
if not getattr(target_format, 'supports_tree_reference', False):
2819
raise errors.BadConversionTarget(
2820
'Does not support nested trees', target_format)
2822
def get_format_string(self):
2823
"""See RepositoryFormat.get_format_string()."""
2824
return ("Bazaar development format 2 with subtree support "
2825
"(needs bzr.dev from before 1.8)\n")
2827
def get_format_description(self):
2828
"""See RepositoryFormat.get_format_description()."""
2829
return ("Development repository format, currently the same as "
2830
"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