743
839
Sets self._text_filter appropriately.
745
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)
747
872
def _copy_text_texts(self):
748
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()
750
899
def _create_pack_from_packs(self):
751
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
753
1143
def _log_copied_texts(self):
754
1144
if 'pack' in debug.debug_flags:
767
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
770
1365
class RepositoryPackCollection(object):
771
1366
"""Management of packs within a repository.
773
1368
:ivar _names: map of {pack_name: (index_size,)}
777
resumed_pack_factory = None
778
normal_packer_class = None
779
optimising_packer_class = None
1371
pack_factory = NewPack
1372
resumed_pack_factory = ResumedPack
781
1374
def __init__(self, repo, transport, index_transport, upload_transport,
782
1375
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
1688
2168
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1690
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1691
self._commit_builder_class = _commit_builder_class
1692
self._serializer = _serializer
2170
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2171
_commit_builder_class, _serializer)
2172
index_transport = self._transport.clone('indices')
2173
self._pack_collection = RepositoryPackCollection(self, self._transport,
2175
self._transport.clone('upload'),
2176
self._transport.clone('packs'),
2177
_format.index_builder_class,
2178
_format.index_class,
2179
use_chk_index=self._format.supports_chks,
2181
self.inventories = KnitVersionedFiles(
2182
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2183
add_callback=self._pack_collection.inventory_index.add_callback,
2184
deltas=True, parents=True, is_locked=self.is_locked),
2185
data_access=self._pack_collection.inventory_index.data_access,
2186
max_delta_chain=200)
2187
self.revisions = KnitVersionedFiles(
2188
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2189
add_callback=self._pack_collection.revision_index.add_callback,
2190
deltas=False, parents=True, is_locked=self.is_locked,
2191
track_external_parent_refs=True),
2192
data_access=self._pack_collection.revision_index.data_access,
2194
self.signatures = KnitVersionedFiles(
2195
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2196
add_callback=self._pack_collection.signature_index.add_callback,
2197
deltas=False, parents=False, is_locked=self.is_locked),
2198
data_access=self._pack_collection.signature_index.data_access,
2200
self.texts = KnitVersionedFiles(
2201
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2202
add_callback=self._pack_collection.text_index.add_callback,
2203
deltas=True, parents=True, is_locked=self.is_locked),
2204
data_access=self._pack_collection.text_index.data_access,
2205
max_delta_chain=200)
2206
if _format.supports_chks:
2207
# No graph, no compression:- references from chks are between
2208
# different objects not temporal versions of the same; and without
2209
# some sort of temporal structure knit compression will just fail.
2210
self.chk_bytes = KnitVersionedFiles(
2211
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2212
add_callback=self._pack_collection.chk_index.add_callback,
2213
deltas=False, parents=False, is_locked=self.is_locked),
2214
data_access=self._pack_collection.chk_index.data_access,
2217
self.chk_bytes = None
2218
# True when the repository object is 'write locked' (as opposed to the
2219
# physical lock only taken out around changes to the pack-names list.)
2220
# Another way to represent this would be a decorator around the control
2221
# files object that presents logical locks as physical ones - if this
2222
# gets ugly consider that alternative design. RBC 20071011
2223
self._write_lock_count = 0
2224
self._transaction = None
2226
self._reconcile_does_inventory_gc = True
1693
2227
self._reconcile_fixes_text_parents = True
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()
2228
self._reconcile_backsup_inventory = False
1702
def _all_revision_ids(self):
1703
"""See Repository.all_revision_ids()."""
1704
return [key[0] for key in self.revisions.keys()]
2230
def _warn_if_deprecated(self):
2231
# This class isn't deprecated, but one sub-format is
2232
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2233
from bzrlib import repository
2234
if repository._deprecation_warning_done:
2236
repository._deprecation_warning_done = True
2237
warning("Format %s for %s is deprecated - please use"
2238
" 'bzr upgrade --1.6.1-rich-root'"
2239
% (self._format, self.bzrdir.transport.base))
1706
2241
def _abort_write_group(self):
1707
2242
self.revisions._index._key_dependencies.clear()
1708
2243
self._pack_collection._abort_write_group()
2245
def _get_source(self, to_format):
2246
if to_format.network_name() == self._format.network_name():
2247
return KnitPackStreamSource(self, to_format)
2248
return super(KnitPackRepository, self)._get_source(to_format)
1710
2250
def _make_parents_provider(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))
2251
return graph.CachingParentsProvider(self)
1716
2253
def _refresh_data(self):
1717
2254
if not self.is_locked():
1719
2256
self._pack_collection.reload_pack_names()
1720
self._unstacked_provider.disable_cache()
1721
self._unstacked_provider.enable_cache()
1723
2258
def _start_write_group(self):
1724
2259
self._pack_collection._start_write_group()
1851
2363
self.control_files.unlock()
1853
2365
if not self.is_locked():
1854
self._unstacked_provider.disable_cache()
1855
2366
for repo in self._fallback_repositories:
1859
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
2370
class KnitPackStreamSource(StreamSource):
2371
"""A StreamSource used to transfer data between same-format KnitPack repos.
2373
This source assumes:
2374
1) Same serialization format for all objects
2375
2) Same root information
2376
3) XML format inventories
2377
4) Atomic inserts (so we can stream inventory texts before text
2382
def __init__(self, from_repository, to_format):
2383
super(KnitPackStreamSource, self).__init__(from_repository, to_format)
2384
self._text_keys = None
2385
self._text_fetch_order = 'unordered'
2387
def _get_filtered_inv_stream(self, revision_ids):
2388
from_repo = self.from_repository
2389
parent_ids = from_repo._find_parent_ids_of_revisions(revision_ids)
2390
parent_keys = [(p,) for p in parent_ids]
2391
find_text_keys = from_repo._find_text_key_references_from_xml_inventory_lines
2392
parent_text_keys = set(find_text_keys(
2393
from_repo._inventory_xml_lines_for_keys(parent_keys)))
2394
content_text_keys = set()
2395
knit = KnitVersionedFiles(None, None)
2396
factory = KnitPlainFactory()
2397
def find_text_keys_from_content(record):
2398
if record.storage_kind not in ('knit-delta-gz', 'knit-ft-gz'):
2399
raise ValueError("Unknown content storage kind for"
2400
" inventory text: %s" % (record.storage_kind,))
2401
# It's a knit record, it has a _raw_record field (even if it was
2402
# reconstituted from a network stream).
2403
raw_data = record._raw_record
2404
# read the entire thing
2405
revision_id = record.key[-1]
2406
content, _ = knit._parse_record(revision_id, raw_data)
2407
if record.storage_kind == 'knit-delta-gz':
2408
line_iterator = factory.get_linedelta_content(content)
2409
elif record.storage_kind == 'knit-ft-gz':
2410
line_iterator = factory.get_fulltext_content(content)
2411
content_text_keys.update(find_text_keys(
2412
[(line, revision_id) for line in line_iterator]))
2413
revision_keys = [(r,) for r in revision_ids]
2414
def _filtered_inv_stream():
2415
source_vf = from_repo.inventories
2416
stream = source_vf.get_record_stream(revision_keys,
2418
for record in stream:
2419
if record.storage_kind == 'absent':
2420
raise errors.NoSuchRevision(from_repo, record.key)
2421
find_text_keys_from_content(record)
2423
self._text_keys = content_text_keys - parent_text_keys
2424
return ('inventories', _filtered_inv_stream())
2426
def _get_text_stream(self):
2427
# Note: We know we don't have to handle adding root keys, because both
2428
# the source and target are the identical network name.
2429
text_stream = self.from_repository.texts.get_record_stream(
2430
self._text_keys, self._text_fetch_order, False)
2431
return ('texts', text_stream)
2433
def get_stream(self, search):
2434
revision_ids = search.get_keys()
2435
for stream_info in self._fetch_revision_texts(revision_ids):
2437
self._revision_keys = [(rev_id,) for rev_id in revision_ids]
2438
yield self._get_filtered_inv_stream(revision_ids)
2439
yield self._get_text_stream()
2443
class RepositoryFormatPack(MetaDirRepositoryFormat):
1860
2444
"""Format logic for pack structured repositories.
1862
2446
This repository format has:
1936
2516
_serializer=self._serializer)
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
2519
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2520
"""A no-subtrees parameterized Pack repository.
2522
This format was introduced in 0.92.
2525
repository_class = KnitPackRepository
2526
_commit_builder_class = PackCommitBuilder
2528
def _serializer(self):
2529
return xml5.serializer_v5
2530
# What index classes to use
2531
index_builder_class = InMemoryGraphIndex
2532
index_class = GraphIndex
2534
def _get_matching_bzrdir(self):
2535
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2537
def _ignore_setting_bzrdir(self, format):
2540
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2542
def get_format_string(self):
2543
"""See RepositoryFormat.get_format_string()."""
2544
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2546
def get_format_description(self):
2547
"""See RepositoryFormat.get_format_description()."""
2548
return "Packs containing knits without subtree support"
2551
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2552
"""A subtrees parameterized Pack repository.
2554
This repository format uses the xml7 serializer to get:
2555
- support for recording full info about the tree root
2556
- support for recording tree-references
2558
This format was introduced in 0.92.
2561
repository_class = KnitPackRepository
2562
_commit_builder_class = PackRootCommitBuilder
2563
rich_root_data = True
2564
supports_tree_reference = True
2566
def _serializer(self):
2567
return xml7.serializer_v7
2568
# What index classes to use
2569
index_builder_class = InMemoryGraphIndex
2570
index_class = GraphIndex
2572
def _get_matching_bzrdir(self):
2573
return bzrdir.format_registry.make_bzrdir(
2574
'pack-0.92-subtree')
2576
def _ignore_setting_bzrdir(self, format):
2579
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2581
def get_format_string(self):
2582
"""See RepositoryFormat.get_format_string()."""
2583
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2585
def get_format_description(self):
2586
"""See RepositoryFormat.get_format_description()."""
2587
return "Packs containing knits with subtree support\n"
2590
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2591
"""A rich-root, no subtrees parameterized Pack repository.
2593
This repository format uses the xml6 serializer to get:
2594
- support for recording full info about the tree root
2596
This format was introduced in 1.0.
2599
repository_class = KnitPackRepository
2600
_commit_builder_class = PackRootCommitBuilder
2601
rich_root_data = True
2602
supports_tree_reference = False
2604
def _serializer(self):
2605
return xml6.serializer_v6
2606
# What index classes to use
2607
index_builder_class = InMemoryGraphIndex
2608
index_class = GraphIndex
2610
def _get_matching_bzrdir(self):
2611
return bzrdir.format_registry.make_bzrdir(
2614
def _ignore_setting_bzrdir(self, format):
2617
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2619
def get_format_string(self):
2620
"""See RepositoryFormat.get_format_string()."""
2621
return ("Bazaar pack repository format 1 with rich root"
2622
" (needs bzr 1.0)\n")
2624
def get_format_description(self):
2625
"""See RepositoryFormat.get_format_description()."""
2626
return "Packs containing knits with rich root support\n"
2629
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2630
"""Repository that supports external references to allow stacking.
2634
Supports external lookups, which results in non-truncated ghosts after
2635
reconcile compared to pack-0.92 formats.
2638
repository_class = KnitPackRepository
2639
_commit_builder_class = PackCommitBuilder
2640
supports_external_lookups = True
2641
# What index classes to use
2642
index_builder_class = InMemoryGraphIndex
2643
index_class = GraphIndex
2646
def _serializer(self):
2647
return xml5.serializer_v5
2649
def _get_matching_bzrdir(self):
2650
return bzrdir.format_registry.make_bzrdir('1.6')
2652
def _ignore_setting_bzrdir(self, format):
2655
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2657
def get_format_string(self):
2658
"""See RepositoryFormat.get_format_string()."""
2659
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2661
def get_format_description(self):
2662
"""See RepositoryFormat.get_format_description()."""
2663
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2666
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2667
"""A repository with rich roots and stacking.
2669
New in release 1.6.1.
2671
Supports stacking on other repositories, allowing data to be accessed
2672
without being stored locally.
2675
repository_class = KnitPackRepository
2676
_commit_builder_class = PackRootCommitBuilder
2677
rich_root_data = True
2678
supports_tree_reference = False # no subtrees
2679
supports_external_lookups = True
2680
# What index classes to use
2681
index_builder_class = InMemoryGraphIndex
2682
index_class = GraphIndex
2685
def _serializer(self):
2686
return xml6.serializer_v6
2688
def _get_matching_bzrdir(self):
2689
return bzrdir.format_registry.make_bzrdir(
2692
def _ignore_setting_bzrdir(self, format):
2695
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2697
def get_format_string(self):
2698
"""See RepositoryFormat.get_format_string()."""
2699
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2701
def get_format_description(self):
2702
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2705
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2706
"""A repository with rich roots and external references.
2710
Supports external lookups, which results in non-truncated ghosts after
2711
reconcile compared to pack-0.92 formats.
2713
This format was deprecated because the serializer it uses accidentally
2714
supported subtrees, when the format was not intended to. This meant that
2715
someone could accidentally fetch from an incorrect repository.
2718
repository_class = KnitPackRepository
2719
_commit_builder_class = PackRootCommitBuilder
2720
rich_root_data = True
2721
supports_tree_reference = False # no subtrees
2723
supports_external_lookups = True
2724
# What index classes to use
2725
index_builder_class = InMemoryGraphIndex
2726
index_class = GraphIndex
2729
def _serializer(self):
2730
return xml7.serializer_v7
2732
def _get_matching_bzrdir(self):
2733
matching = bzrdir.format_registry.make_bzrdir(
2735
matching.repository_format = self
2738
def _ignore_setting_bzrdir(self, format):
2741
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2743
def get_format_string(self):
2744
"""See RepositoryFormat.get_format_string()."""
2745
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2747
def get_format_description(self):
2748
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2752
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2753
"""A repository with stacking and btree indexes,
2754
without rich roots or subtrees.
2756
This is equivalent to pack-1.6 with B+Tree indices.
2759
repository_class = KnitPackRepository
2760
_commit_builder_class = PackCommitBuilder
2761
supports_external_lookups = True
2762
# What index classes to use
2763
index_builder_class = BTreeBuilder
2764
index_class = BTreeGraphIndex
2767
def _serializer(self):
2768
return xml5.serializer_v5
2770
def _get_matching_bzrdir(self):
2771
return bzrdir.format_registry.make_bzrdir('1.9')
2773
def _ignore_setting_bzrdir(self, format):
2776
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2778
def get_format_string(self):
2779
"""See RepositoryFormat.get_format_string()."""
2780
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2782
def get_format_description(self):
2783
"""See RepositoryFormat.get_format_description()."""
2784
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2787
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2788
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2790
1.6-rich-root with B+Tree indices.
2793
repository_class = KnitPackRepository
2794
_commit_builder_class = PackRootCommitBuilder
2795
rich_root_data = True
2796
supports_tree_reference = False # no subtrees
2797
supports_external_lookups = True
2798
# What index classes to use
2799
index_builder_class = BTreeBuilder
2800
index_class = BTreeGraphIndex
2803
def _serializer(self):
2804
return xml6.serializer_v6
2806
def _get_matching_bzrdir(self):
2807
return bzrdir.format_registry.make_bzrdir(
2810
def _ignore_setting_bzrdir(self, format):
2813
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2815
def get_format_string(self):
2816
"""See RepositoryFormat.get_format_string()."""
2817
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2819
def get_format_description(self):
2820
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2823
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2824
"""A subtrees development repository.
2826
This format should be retained until the second release after bzr 1.7.
2828
1.6.1-subtree[as it might have been] with B+Tree indices.
2830
This is [now] retained until we have a CHK based subtree format in
2834
repository_class = KnitPackRepository
2835
_commit_builder_class = PackRootCommitBuilder
2836
rich_root_data = True
2837
supports_tree_reference = True
2838
supports_external_lookups = True
2839
# What index classes to use
2840
index_builder_class = BTreeBuilder
2841
index_class = BTreeGraphIndex
2844
def _serializer(self):
2845
return xml7.serializer_v7
2847
def _get_matching_bzrdir(self):
2848
return bzrdir.format_registry.make_bzrdir(
2849
'development-subtree')
2851
def _ignore_setting_bzrdir(self, format):
2854
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2856
def get_format_string(self):
2857
"""See RepositoryFormat.get_format_string()."""
2858
return ("Bazaar development format 2 with subtree support "
2859
"(needs bzr.dev from before 1.8)\n")
2861
def get_format_description(self):
2862
"""See RepositoryFormat.get_format_description()."""
2863
return ("Development repository format, currently the same as "
2864
"1.6.1-subtree with B+Tree indices.\n")