839
743
Sets self._text_filter appropriately.
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)
745
raise NotImplementedError(self._copy_inventory_texts)
872
747
def _copy_text_texts(self):
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()
748
raise NotImplementedError(self._copy_text_texts)
899
750
def _create_pack_from_packs(self):
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
751
raise NotImplementedError(self._create_pack_from_packs)
1143
753
def _log_copied_texts(self):
1144
754
if 'pack' in debug.debug_flags:
1176
767
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
1365
770
class RepositoryPackCollection(object):
1366
771
"""Management of packs within a repository.
1368
773
:ivar _names: map of {pack_name: (index_size,)}
1371
pack_factory = NewPack
1372
resumed_pack_factory = ResumedPack
777
resumed_pack_factory = None
778
normal_packer_class = None
779
optimising_packer_class = None
1374
781
def __init__(self, repo, transport, index_transport, upload_transport,
1375
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
2151
1688
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
2153
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2154
_commit_builder_class, _serializer)
2155
index_transport = self._transport.clone('indices')
2156
self._pack_collection = RepositoryPackCollection(self, self._transport,
2158
self._transport.clone('upload'),
2159
self._transport.clone('packs'),
2160
_format.index_builder_class,
2161
_format.index_class,
2162
use_chk_index=self._format.supports_chks,
2164
self.inventories = KnitVersionedFiles(
2165
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2166
add_callback=self._pack_collection.inventory_index.add_callback,
2167
deltas=True, parents=True, is_locked=self.is_locked),
2168
data_access=self._pack_collection.inventory_index.data_access,
2169
max_delta_chain=200)
2170
self.revisions = KnitVersionedFiles(
2171
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2172
add_callback=self._pack_collection.revision_index.add_callback,
2173
deltas=False, parents=True, is_locked=self.is_locked,
2174
track_external_parent_refs=True),
2175
data_access=self._pack_collection.revision_index.data_access,
2177
self.signatures = KnitVersionedFiles(
2178
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2179
add_callback=self._pack_collection.signature_index.add_callback,
2180
deltas=False, parents=False, is_locked=self.is_locked),
2181
data_access=self._pack_collection.signature_index.data_access,
2183
self.texts = KnitVersionedFiles(
2184
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2185
add_callback=self._pack_collection.text_index.add_callback,
2186
deltas=True, parents=True, is_locked=self.is_locked),
2187
data_access=self._pack_collection.text_index.data_access,
2188
max_delta_chain=200)
2189
if _format.supports_chks:
2190
# No graph, no compression:- references from chks are between
2191
# different objects not temporal versions of the same; and without
2192
# some sort of temporal structure knit compression will just fail.
2193
self.chk_bytes = KnitVersionedFiles(
2194
_KnitGraphIndex(self._pack_collection.chk_index.combined_index,
2195
add_callback=self._pack_collection.chk_index.add_callback,
2196
deltas=False, parents=False, is_locked=self.is_locked),
2197
data_access=self._pack_collection.chk_index.data_access,
2200
self.chk_bytes = None
2201
# True when the repository object is 'write locked' (as opposed to the
2202
# physical lock only taken out around changes to the pack-names list.)
2203
# Another way to represent this would be a decorator around the control
2204
# files object that presents logical locks as physical ones - if this
2205
# gets ugly consider that alternative design. RBC 20071011
2206
self._write_lock_count = 0
2207
self._transaction = None
2209
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
2210
1693
self._reconcile_fixes_text_parents = True
2211
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()
2213
def _warn_if_deprecated(self):
2214
# This class isn't deprecated, but one sub-format is
2215
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2216
from bzrlib import repository
2217
if repository._deprecation_warning_done:
2219
repository._deprecation_warning_done = True
2220
warning("Format %s for %s is deprecated - please use"
2221
" 'bzr upgrade --1.6.1-rich-root'"
2222
% (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()]
2224
1706
def _abort_write_group(self):
2225
self.revisions._index._key_dependencies.refs.clear()
1707
self.revisions._index._key_dependencies.clear()
2226
1708
self._pack_collection._abort_write_group()
2228
def _get_source(self, to_format):
2229
if to_format.network_name() == self._format.network_name():
2230
return KnitPackStreamSource(self, to_format)
2231
return super(KnitPackRepository, self)._get_source(to_format)
2233
1710
def _make_parents_provider(self):
2234
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))
2236
1716
def _refresh_data(self):
2237
1717
if not self.is_locked():
2239
1719
self._pack_collection.reload_pack_names()
1720
self._unstacked_provider.disable_cache()
1721
self._unstacked_provider.enable_cache()
2241
1723
def _start_write_group(self):
2242
1724
self._pack_collection._start_write_group()
2244
1726
def _commit_write_group(self):
2245
self.revisions._index._key_dependencies.refs.clear()
2246
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()
2248
1735
def suspend_write_group(self):
2249
1736
# XXX check self._write_group is self.get_transaction()?
2250
1737
tokens = self._pack_collection._suspend_write_group()
2251
self.revisions._index._key_dependencies.refs.clear()
1738
self.revisions._index._key_dependencies.clear()
2252
1739
self._write_group = None
2345
1851
self.control_files.unlock()
2347
1853
if not self.is_locked():
1854
self._unstacked_provider.disable_cache()
2348
1855
for repo in self._fallback_repositories:
2352
class KnitPackStreamSource(StreamSource):
2353
"""A StreamSource used to transfer data between same-format KnitPack repos.
2355
This source assumes:
2356
1) Same serialization format for all objects
2357
2) Same root information
2358
3) XML format inventories
2359
4) Atomic inserts (so we can stream inventory texts before text
2364
def __init__(self, from_repository, to_format):
2365
super(KnitPackStreamSource, self).__init__(from_repository, to_format)
2366
self._text_keys = None
2367
self._text_fetch_order = 'unordered'
2369
def _get_filtered_inv_stream(self, revision_ids):
2370
from_repo = self.from_repository
2371
parent_ids = from_repo._find_parent_ids_of_revisions(revision_ids)
2372
parent_keys = [(p,) for p in parent_ids]
2373
find_text_keys = from_repo._find_text_key_references_from_xml_inventory_lines
2374
parent_text_keys = set(find_text_keys(
2375
from_repo._inventory_xml_lines_for_keys(parent_keys)))
2376
content_text_keys = set()
2377
knit = KnitVersionedFiles(None, None)
2378
factory = KnitPlainFactory()
2379
def find_text_keys_from_content(record):
2380
if record.storage_kind not in ('knit-delta-gz', 'knit-ft-gz'):
2381
raise ValueError("Unknown content storage kind for"
2382
" inventory text: %s" % (record.storage_kind,))
2383
# It's a knit record, it has a _raw_record field (even if it was
2384
# reconstituted from a network stream).
2385
raw_data = record._raw_record
2386
# read the entire thing
2387
revision_id = record.key[-1]
2388
content, _ = knit._parse_record(revision_id, raw_data)
2389
if record.storage_kind == 'knit-delta-gz':
2390
line_iterator = factory.get_linedelta_content(content)
2391
elif record.storage_kind == 'knit-ft-gz':
2392
line_iterator = factory.get_fulltext_content(content)
2393
content_text_keys.update(find_text_keys(
2394
[(line, revision_id) for line in line_iterator]))
2395
revision_keys = [(r,) for r in revision_ids]
2396
def _filtered_inv_stream():
2397
source_vf = from_repo.inventories
2398
stream = source_vf.get_record_stream(revision_keys,
2400
for record in stream:
2401
if record.storage_kind == 'absent':
2402
raise errors.NoSuchRevision(from_repo, record.key)
2403
find_text_keys_from_content(record)
2405
self._text_keys = content_text_keys - parent_text_keys
2406
return ('inventories', _filtered_inv_stream())
2408
def _get_text_stream(self):
2409
# Note: We know we don't have to handle adding root keys, because both
2410
# the source and target are the identical network name.
2411
text_stream = self.from_repository.texts.get_record_stream(
2412
self._text_keys, self._text_fetch_order, False)
2413
return ('texts', text_stream)
2415
def get_stream(self, search):
2416
revision_ids = search.get_keys()
2417
for stream_info in self._fetch_revision_texts(revision_ids):
2419
self._revision_keys = [(rev_id,) for rev_id in revision_ids]
2420
yield self._get_filtered_inv_stream(revision_ids)
2421
yield self._get_text_stream()
2425
class RepositoryFormatPack(MetaDirRepositoryFormat):
1859
class RepositoryFormatPack(MetaDirVersionedFileRepositoryFormat):
2426
1860
"""Format logic for pack structured repositories.
2428
1862
This repository format has:
2498
1936
_serializer=self._serializer)
2501
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2502
"""A no-subtrees parameterized Pack repository.
2504
This format was introduced in 0.92.
2507
repository_class = KnitPackRepository
2508
_commit_builder_class = PackCommitBuilder
2510
def _serializer(self):
2511
return xml5.serializer_v5
2512
# What index classes to use
2513
index_builder_class = InMemoryGraphIndex
2514
index_class = GraphIndex
2516
def _get_matching_bzrdir(self):
2517
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2519
def _ignore_setting_bzrdir(self, format):
2522
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2524
def get_format_string(self):
2525
"""See RepositoryFormat.get_format_string()."""
2526
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2528
def get_format_description(self):
2529
"""See RepositoryFormat.get_format_description()."""
2530
return "Packs containing knits without subtree support"
2533
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2534
"""A subtrees parameterized Pack repository.
2536
This repository format uses the xml7 serializer to get:
2537
- support for recording full info about the tree root
2538
- support for recording tree-references
2540
This format was introduced in 0.92.
2543
repository_class = KnitPackRepository
2544
_commit_builder_class = PackRootCommitBuilder
2545
rich_root_data = True
2546
supports_tree_reference = True
2548
def _serializer(self):
2549
return xml7.serializer_v7
2550
# What index classes to use
2551
index_builder_class = InMemoryGraphIndex
2552
index_class = GraphIndex
2554
def _get_matching_bzrdir(self):
2555
return bzrdir.format_registry.make_bzrdir(
2556
'pack-0.92-subtree')
2558
def _ignore_setting_bzrdir(self, format):
2561
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2563
def get_format_string(self):
2564
"""See RepositoryFormat.get_format_string()."""
2565
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2567
def get_format_description(self):
2568
"""See RepositoryFormat.get_format_description()."""
2569
return "Packs containing knits with subtree support\n"
2572
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2573
"""A rich-root, no subtrees parameterized Pack repository.
2575
This repository format uses the xml6 serializer to get:
2576
- support for recording full info about the tree root
2578
This format was introduced in 1.0.
2581
repository_class = KnitPackRepository
2582
_commit_builder_class = PackRootCommitBuilder
2583
rich_root_data = True
2584
supports_tree_reference = False
2586
def _serializer(self):
2587
return xml6.serializer_v6
2588
# What index classes to use
2589
index_builder_class = InMemoryGraphIndex
2590
index_class = GraphIndex
2592
def _get_matching_bzrdir(self):
2593
return bzrdir.format_registry.make_bzrdir(
2596
def _ignore_setting_bzrdir(self, format):
2599
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2601
def get_format_string(self):
2602
"""See RepositoryFormat.get_format_string()."""
2603
return ("Bazaar pack repository format 1 with rich root"
2604
" (needs bzr 1.0)\n")
2606
def get_format_description(self):
2607
"""See RepositoryFormat.get_format_description()."""
2608
return "Packs containing knits with rich root support\n"
2611
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2612
"""Repository that supports external references to allow stacking.
2616
Supports external lookups, which results in non-truncated ghosts after
2617
reconcile compared to pack-0.92 formats.
2620
repository_class = KnitPackRepository
2621
_commit_builder_class = PackCommitBuilder
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 xml5.serializer_v5
2631
def _get_matching_bzrdir(self):
2632
return bzrdir.format_registry.make_bzrdir('1.6')
2634
def _ignore_setting_bzrdir(self, format):
2637
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2639
def get_format_string(self):
2640
"""See RepositoryFormat.get_format_string()."""
2641
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2643
def get_format_description(self):
2644
"""See RepositoryFormat.get_format_description()."""
2645
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2648
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2649
"""A repository with rich roots and stacking.
2651
New in release 1.6.1.
2653
Supports stacking on other repositories, allowing data to be accessed
2654
without being stored locally.
2657
repository_class = KnitPackRepository
2658
_commit_builder_class = PackRootCommitBuilder
2659
rich_root_data = True
2660
supports_tree_reference = False # no subtrees
2661
supports_external_lookups = True
2662
# What index classes to use
2663
index_builder_class = InMemoryGraphIndex
2664
index_class = GraphIndex
2667
def _serializer(self):
2668
return xml6.serializer_v6
2670
def _get_matching_bzrdir(self):
2671
return bzrdir.format_registry.make_bzrdir(
2674
def _ignore_setting_bzrdir(self, format):
2677
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2679
def get_format_string(self):
2680
"""See RepositoryFormat.get_format_string()."""
2681
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2683
def get_format_description(self):
2684
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2687
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2688
"""A repository with rich roots and external references.
2692
Supports external lookups, which results in non-truncated ghosts after
2693
reconcile compared to pack-0.92 formats.
2695
This format was deprecated because the serializer it uses accidentally
2696
supported subtrees, when the format was not intended to. This meant that
2697
someone could accidentally fetch from an incorrect repository.
2700
repository_class = KnitPackRepository
2701
_commit_builder_class = PackRootCommitBuilder
2702
rich_root_data = True
2703
supports_tree_reference = False # no subtrees
2705
supports_external_lookups = True
2706
# What index classes to use
2707
index_builder_class = InMemoryGraphIndex
2708
index_class = GraphIndex
2711
def _serializer(self):
2712
return xml7.serializer_v7
2714
def _get_matching_bzrdir(self):
2715
matching = bzrdir.format_registry.make_bzrdir(
2717
matching.repository_format = self
2720
def _ignore_setting_bzrdir(self, format):
2723
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2725
def get_format_string(self):
2726
"""See RepositoryFormat.get_format_string()."""
2727
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2729
def get_format_description(self):
2730
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2734
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2735
"""A repository with stacking and btree indexes,
2736
without rich roots or subtrees.
2738
This is equivalent to pack-1.6 with B+Tree indices.
2741
repository_class = KnitPackRepository
2742
_commit_builder_class = PackCommitBuilder
2743
supports_external_lookups = True
2744
# What index classes to use
2745
index_builder_class = BTreeBuilder
2746
index_class = BTreeGraphIndex
2749
def _serializer(self):
2750
return xml5.serializer_v5
2752
def _get_matching_bzrdir(self):
2753
return bzrdir.format_registry.make_bzrdir('1.9')
2755
def _ignore_setting_bzrdir(self, format):
2758
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2760
def get_format_string(self):
2761
"""See RepositoryFormat.get_format_string()."""
2762
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2764
def get_format_description(self):
2765
"""See RepositoryFormat.get_format_description()."""
2766
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2769
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2770
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2772
1.6-rich-root with B+Tree indices.
2775
repository_class = KnitPackRepository
2776
_commit_builder_class = PackRootCommitBuilder
2777
rich_root_data = True
2778
supports_tree_reference = False # no subtrees
2779
supports_external_lookups = True
2780
# What index classes to use
2781
index_builder_class = BTreeBuilder
2782
index_class = BTreeGraphIndex
2785
def _serializer(self):
2786
return xml6.serializer_v6
2788
def _get_matching_bzrdir(self):
2789
return bzrdir.format_registry.make_bzrdir(
2792
def _ignore_setting_bzrdir(self, format):
2795
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2797
def get_format_string(self):
2798
"""See RepositoryFormat.get_format_string()."""
2799
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2801
def get_format_description(self):
2802
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2805
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2806
"""A subtrees development repository.
2808
This format should be retained until the second release after bzr 1.7.
2810
1.6.1-subtree[as it might have been] with B+Tree indices.
2812
This is [now] retained until we have a CHK based subtree format in
2816
repository_class = KnitPackRepository
2817
_commit_builder_class = PackRootCommitBuilder
2818
rich_root_data = True
2819
supports_tree_reference = True
2820
supports_external_lookups = True
2821
# What index classes to use
2822
index_builder_class = BTreeBuilder
2823
index_class = BTreeGraphIndex
2826
def _serializer(self):
2827
return xml7.serializer_v7
2829
def _get_matching_bzrdir(self):
2830
return bzrdir.format_registry.make_bzrdir(
2831
'development-subtree')
2833
def _ignore_setting_bzrdir(self, format):
2836
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2838
def get_format_string(self):
2839
"""See RepositoryFormat.get_format_string()."""
2840
return ("Bazaar development format 2 with subtree support "
2841
"(needs bzr.dev from before 1.8)\n")
2843
def get_format_description(self):
2844
"""See RepositoryFormat.get_format_description()."""
2845
return ("Development repository format, currently the same as "
2846
"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