732
804
Sets self._text_filter appropriately.
734
raise NotImplementedError(self._copy_inventory_texts)
806
# select inventory keys
807
inv_keys = self._revision_keys # currently the same keyspace, and note that
808
# querying for keys here could introduce a bug where an inventory item
809
# is missed, so do not change it to query separately without cross
810
# checking like the text key check below.
811
inventory_index_map, inventory_indices = self._pack_map_and_index_list(
813
inv_nodes = self._index_contents(inventory_indices, inv_keys)
814
# copy inventory keys and adjust values
815
# XXX: Should be a helper function to allow different inv representation
817
self.pb.update("Copying inventory texts", 2)
818
total_items, readv_group_iter = self._least_readv_node_readv(inv_nodes)
819
# Only grab the output lines if we will be processing them
820
output_lines = bool(self.revision_ids)
821
inv_lines = self._copy_nodes_graph(inventory_index_map,
822
self.new_pack._writer, self.new_pack.inventory_index,
823
readv_group_iter, total_items, output_lines=output_lines)
824
if self.revision_ids:
825
self._process_inventory_lines(inv_lines)
827
# eat the iterator to cause it to execute.
829
self._text_filter = None
830
if 'pack' in debug.debug_flags:
831
mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
832
time.ctime(), self._pack_collection._upload_transport.base,
833
self.new_pack.random_name,
834
self.new_pack.inventory_index.key_count(),
835
time.time() - self.new_pack.start_time)
736
837
def _copy_text_texts(self):
737
raise NotImplementedError(self._copy_text_texts)
839
text_index_map, text_nodes = self._get_text_nodes()
840
if self._text_filter is not None:
841
# We could return the keys copied as part of the return value from
842
# _copy_nodes_graph but this doesn't work all that well with the
843
# need to get line output too, so we check separately, and as we're
844
# going to buffer everything anyway, we check beforehand, which
845
# saves reading knit data over the wire when we know there are
847
text_nodes = set(text_nodes)
848
present_text_keys = set(_node[1] for _node in text_nodes)
849
missing_text_keys = set(self._text_filter) - present_text_keys
850
if missing_text_keys:
851
# TODO: raise a specific error that can handle many missing
853
mutter("missing keys during fetch: %r", missing_text_keys)
854
a_missing_key = missing_text_keys.pop()
855
raise errors.RevisionNotPresent(a_missing_key[1],
857
# copy text keys and adjust values
858
self.pb.update("Copying content texts", 3)
859
total_items, readv_group_iter = self._least_readv_node_readv(text_nodes)
860
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
861
self.new_pack.text_index, readv_group_iter, total_items))
862
self._log_copied_texts()
739
864
def _create_pack_from_packs(self):
740
raise NotImplementedError(self._create_pack_from_packs)
865
self.pb.update("Opening pack", 0, 5)
866
self.new_pack = self.open_pack()
867
new_pack = self.new_pack
868
# buffer data - we won't be reading-back during the pack creation and
869
# this makes a significant difference on sftp pushes.
870
new_pack.set_write_cache_size(1024*1024)
871
if 'pack' in debug.debug_flags:
872
plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
873
for a_pack in self.packs]
874
if self.revision_ids is not None:
875
rev_count = len(self.revision_ids)
878
mutter('%s: create_pack: creating pack from source packs: '
879
'%s%s %s revisions wanted %s t=0',
880
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
881
plain_pack_list, rev_count)
882
self._copy_revision_texts()
883
self._copy_inventory_texts()
884
self._copy_text_texts()
885
# select signature keys
886
signature_filter = self._revision_keys # same keyspace
887
signature_index_map, signature_indices = self._pack_map_and_index_list(
889
signature_nodes = self._index_contents(signature_indices,
891
# copy signature keys and adjust values
892
self.pb.update("Copying signature texts", 4)
893
self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
894
new_pack.signature_index)
895
if 'pack' in debug.debug_flags:
896
mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
897
time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
898
new_pack.signature_index.key_count(),
899
time.time() - new_pack.start_time)
900
new_pack._check_references()
901
if not self._use_pack(new_pack):
904
self.pb.update("Finishing pack", 5)
906
self._pack_collection.allocate(new_pack)
909
def _copy_nodes(self, nodes, index_map, writer, write_index):
910
"""Copy knit nodes between packs with no graph references."""
911
pb = ui.ui_factory.nested_progress_bar()
913
return self._do_copy_nodes(nodes, index_map, writer,
918
def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
919
# for record verification
920
knit = KnitVersionedFiles(None, None)
921
# plan a readv on each source pack:
923
nodes = sorted(nodes)
924
# how to map this into knit.py - or knit.py into this?
925
# we don't want the typical knit logic, we want grouping by pack
926
# at this point - perhaps a helper library for the following code
927
# duplication points?
929
for index, key, value in nodes:
930
if index not in request_groups:
931
request_groups[index] = []
932
request_groups[index].append((key, value))
934
pb.update("Copied record", record_index, len(nodes))
935
for index, items in request_groups.iteritems():
936
pack_readv_requests = []
937
for key, value in items:
938
# ---- KnitGraphIndex.get_position
939
bits = value[1:].split(' ')
940
offset, length = int(bits[0]), int(bits[1])
941
pack_readv_requests.append((offset, length, (key, value[0])))
942
# linear scan up the pack
943
pack_readv_requests.sort()
945
pack_obj = index_map[index]
946
transport, path = pack_obj.access_tuple()
948
reader = pack.make_readv_reader(transport, path,
949
[offset[0:2] for offset in pack_readv_requests])
950
except errors.NoSuchFile:
951
if self._reload_func is not None:
954
for (names, read_func), (_1, _2, (key, eol_flag)) in \
955
izip(reader.iter_records(), pack_readv_requests):
956
raw_data = read_func(None)
957
# check the header only
958
df, _ = knit._parse_record_header(key, raw_data)
960
pos, size = writer.add_bytes_record(raw_data, names)
961
write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
962
pb.update("Copied record", record_index)
965
def _copy_nodes_graph(self, index_map, writer, write_index,
966
readv_group_iter, total_items, output_lines=False):
967
"""Copy knit nodes between packs.
969
:param output_lines: Return lines present in the copied data as
970
an iterator of line,version_id.
972
pb = ui.ui_factory.nested_progress_bar()
974
for result in self._do_copy_nodes_graph(index_map, writer,
975
write_index, output_lines, pb, readv_group_iter, total_items):
978
# Python 2.4 does not permit try:finally: in a generator.
984
def _do_copy_nodes_graph(self, index_map, writer, write_index,
985
output_lines, pb, readv_group_iter, total_items):
986
# for record verification
987
knit = KnitVersionedFiles(None, None)
988
# for line extraction when requested (inventories only)
990
factory = KnitPlainFactory()
992
pb.update("Copied record", record_index, total_items)
993
for index, readv_vector, node_vector in readv_group_iter:
995
pack_obj = index_map[index]
996
transport, path = pack_obj.access_tuple()
998
reader = pack.make_readv_reader(transport, path, readv_vector)
999
except errors.NoSuchFile:
1000
if self._reload_func is not None:
1003
for (names, read_func), (key, eol_flag, references) in \
1004
izip(reader.iter_records(), node_vector):
1005
raw_data = read_func(None)
1007
# read the entire thing
1008
content, _ = knit._parse_record(key[-1], raw_data)
1009
if len(references[-1]) == 0:
1010
line_iterator = factory.get_fulltext_content(content)
1012
line_iterator = factory.get_linedelta_content(content)
1013
for line in line_iterator:
1016
# check the header only
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), references)
1021
pb.update("Copied record", record_index)
1024
def _get_text_nodes(self):
1025
text_index_map, text_indices = self._pack_map_and_index_list(
1027
return text_index_map, self._index_contents(text_indices,
1030
def _least_readv_node_readv(self, nodes):
1031
"""Generate request groups for nodes using the least readv's.
1033
:param nodes: An iterable of graph index nodes.
1034
:return: Total node count and an iterator of the data needed to perform
1035
readvs to obtain the data for nodes. Each item yielded by the
1036
iterator is a tuple with:
1037
index, readv_vector, node_vector. readv_vector is a list ready to
1038
hand to the transport readv method, and node_vector is a list of
1039
(key, eol_flag, references) for the the node retrieved by the
1040
matching readv_vector.
1042
# group by pack so we do one readv per pack
1043
nodes = sorted(nodes)
1046
for index, key, value, references in nodes:
1047
if index not in request_groups:
1048
request_groups[index] = []
1049
request_groups[index].append((key, value, references))
1051
for index, items in request_groups.iteritems():
1052
pack_readv_requests = []
1053
for key, value, references in items:
1054
# ---- KnitGraphIndex.get_position
1055
bits = value[1:].split(' ')
1056
offset, length = int(bits[0]), int(bits[1])
1057
pack_readv_requests.append(
1058
((offset, length), (key, value[0], references)))
1059
# linear scan up the pack to maximum range combining.
1060
pack_readv_requests.sort()
1061
# split out the readv and the node data.
1062
pack_readv = [readv for readv, node in pack_readv_requests]
1063
node_vector = [node for readv, node in pack_readv_requests]
1064
result.append((index, pack_readv, node_vector))
1065
return total, result
742
1067
def _log_copied_texts(self):
743
1068
if 'pack' in debug.debug_flags:
756
1100
return new_pack.data_inserted()
1103
class OptimisingPacker(Packer):
1104
"""A packer which spends more time to create better disk layouts."""
1106
def _revision_node_readv(self, revision_nodes):
1107
"""Return the total revisions and the readv's to issue.
1109
This sort places revisions in topological order with the ancestors
1112
:param revision_nodes: The revision index contents for the packs being
1113
incorporated into the new pack.
1114
:return: As per _least_readv_node_readv.
1116
# build an ancestors dict
1119
for index, key, value, references in revision_nodes:
1120
ancestors[key] = references[0]
1121
by_key[key] = (index, value, references)
1122
order = tsort.topo_sort(ancestors)
1124
# Single IO is pathological, but it will work as a starting point.
1126
for key in reversed(order):
1127
index, value, references = by_key[key]
1128
# ---- KnitGraphIndex.get_position
1129
bits = value[1:].split(' ')
1130
offset, length = int(bits[0]), int(bits[1])
1132
(index, [(offset, length)], [(key, value[0], references)]))
1133
# TODO: combine requests in the same index that are in ascending order.
1134
return total, requests
1136
def open_pack(self):
1137
"""Open a pack for the pack we are creating."""
1138
new_pack = super(OptimisingPacker, self).open_pack()
1139
# Turn on the optimization flags for all the index builders.
1140
new_pack.revision_index.set_optimize(for_size=True)
1141
new_pack.inventory_index.set_optimize(for_size=True)
1142
new_pack.text_index.set_optimize(for_size=True)
1143
new_pack.signature_index.set_optimize(for_size=True)
1147
class ReconcilePacker(Packer):
1148
"""A packer which regenerates indices etc as it copies.
1150
This is used by ``bzr reconcile`` to cause parent text pointers to be
1154
def _extra_init(self):
1155
self._data_changed = False
1157
def _process_inventory_lines(self, inv_lines):
1158
"""Generate a text key reference map rather for reconciling with."""
1159
repo = self._pack_collection.repo
1160
refs = repo._find_text_key_references_from_xml_inventory_lines(
1162
self._text_refs = refs
1163
# during reconcile we:
1164
# - convert unreferenced texts to full texts
1165
# - correct texts which reference a text not copied to be full texts
1166
# - copy all others as-is but with corrected parents.
1167
# - so at this point we don't know enough to decide what becomes a full
1169
self._text_filter = None
1171
def _copy_text_texts(self):
1172
"""generate what texts we should have and then copy."""
1173
self.pb.update("Copying content texts", 3)
1174
# we have three major tasks here:
1175
# 1) generate the ideal index
1176
repo = self._pack_collection.repo
1177
ancestors = dict([(key[0], tuple(ref[0] for ref in refs[0])) for
1178
_1, key, _2, refs in
1179
self.new_pack.revision_index.iter_all_entries()])
1180
ideal_index = repo._generate_text_key_index(self._text_refs, ancestors)
1181
# 2) generate a text_nodes list that contains all the deltas that can
1182
# be used as-is, with corrected parents.
1185
discarded_nodes = []
1186
NULL_REVISION = _mod_revision.NULL_REVISION
1187
text_index_map, text_nodes = self._get_text_nodes()
1188
for node in text_nodes:
1194
ideal_parents = tuple(ideal_index[node[1]])
1196
discarded_nodes.append(node)
1197
self._data_changed = True
1199
if ideal_parents == (NULL_REVISION,):
1201
if ideal_parents == node[3][0]:
1203
ok_nodes.append(node)
1204
elif ideal_parents[0:1] == node[3][0][0:1]:
1205
# the left most parent is the same, or there are no parents
1206
# today. Either way, we can preserve the representation as
1207
# long as we change the refs to be inserted.
1208
self._data_changed = True
1209
ok_nodes.append((node[0], node[1], node[2],
1210
(ideal_parents, node[3][1])))
1211
self._data_changed = True
1213
# Reinsert this text completely
1214
bad_texts.append((node[1], ideal_parents))
1215
self._data_changed = True
1216
# we're finished with some data.
1219
# 3) bulk copy the ok data
1220
total_items, readv_group_iter = self._least_readv_node_readv(ok_nodes)
1221
list(self._copy_nodes_graph(text_index_map, self.new_pack._writer,
1222
self.new_pack.text_index, readv_group_iter, total_items))
1223
# 4) adhoc copy all the other texts.
1224
# We have to topologically insert all texts otherwise we can fail to
1225
# reconcile when parts of a single delta chain are preserved intact,
1226
# and other parts are not. E.g. Discarded->d1->d2->d3. d1 will be
1227
# reinserted, and if d3 has incorrect parents it will also be
1228
# reinserted. If we insert d3 first, d2 is present (as it was bulk
1229
# copied), so we will try to delta, but d2 is not currently able to be
1230
# extracted because it's basis d1 is not present. Topologically sorting
1231
# addresses this. The following generates a sort for all the texts that
1232
# are being inserted without having to reference the entire text key
1233
# space (we only topo sort the revisions, which is smaller).
1234
topo_order = tsort.topo_sort(ancestors)
1235
rev_order = dict(zip(topo_order, range(len(topo_order))))
1236
bad_texts.sort(key=lambda key:rev_order[key[0][1]])
1237
transaction = repo.get_transaction()
1238
file_id_index = GraphIndexPrefixAdapter(
1239
self.new_pack.text_index,
1241
add_nodes_callback=self.new_pack.text_index.add_nodes)
1242
data_access = _DirectPackAccess(
1243
{self.new_pack.text_index:self.new_pack.access_tuple()})
1244
data_access.set_writer(self.new_pack._writer, self.new_pack.text_index,
1245
self.new_pack.access_tuple())
1246
output_texts = KnitVersionedFiles(
1247
_KnitGraphIndex(self.new_pack.text_index,
1248
add_callback=self.new_pack.text_index.add_nodes,
1249
deltas=True, parents=True, is_locked=repo.is_locked),
1250
data_access=data_access, max_delta_chain=200)
1251
for key, parent_keys in bad_texts:
1252
# We refer to the new pack to delta data being output.
1253
# A possible improvement would be to catch errors on short reads
1254
# and only flush then.
1255
self.new_pack.flush()
1257
for parent_key in parent_keys:
1258
if parent_key[0] != key[0]:
1259
# Graph parents must match the fileid
1260
raise errors.BzrError('Mismatched key parent %r:%r' %
1262
parents.append(parent_key[1])
1263
text_lines = osutils.split_lines(repo.texts.get_record_stream(
1264
[key], 'unordered', True).next().get_bytes_as('fulltext'))
1265
output_texts.add_lines(key, parent_keys, text_lines,
1266
random_id=True, check_content=False)
1267
# 5) check that nothing inserted has a reference outside the keyspace.
1268
missing_text_keys = self.new_pack.text_index._external_references()
1269
if missing_text_keys:
1270
raise errors.BzrCheckError('Reference to missing compression parents %r'
1271
% (missing_text_keys,))
1272
self._log_copied_texts()
1274
def _use_pack(self, new_pack):
1275
"""Override _use_pack to check for reconcile having changed content."""
1276
# XXX: we might be better checking this at the copy time.
1277
original_inventory_keys = set()
1278
inv_index = self._pack_collection.inventory_index.combined_index
1279
for entry in inv_index.iter_all_entries():
1280
original_inventory_keys.add(entry[1])
1281
new_inventory_keys = set()
1282
for entry in new_pack.inventory_index.iter_all_entries():
1283
new_inventory_keys.add(entry[1])
1284
if new_inventory_keys != original_inventory_keys:
1285
self._data_changed = True
1286
return new_pack.data_inserted() and self._data_changed
759
1289
class RepositoryPackCollection(object):
760
1290
"""Management of packs within a repository.
762
1292
:ivar _names: map of {pack_name: (index_size,)}
766
resumed_pack_factory = None
767
normal_packer_class = None
768
optimising_packer_class = None
770
1295
def __init__(self, repo, transport, index_transport, upload_transport,
771
pack_transport, index_builder_class, index_class,
1296
pack_transport, index_builder_class, index_class):
773
1297
"""Create a new RepositoryPackCollection.
775
1299
:param transport: Addresses the repository base directory
1655
# These attributes are inherited from the Repository base class. Setting
1656
# them to None ensures that if the constructor is changed to not initialize
1657
# them, or a subclass fails to call the constructor, that an error will
1658
# occur rather than the system working but generating incorrect data.
1659
_commit_builder_class = None
1662
2039
def __init__(self, _format, a_bzrdir, control_files, _commit_builder_class,
1664
MetaDirRepository.__init__(self, _format, a_bzrdir, control_files)
1665
self._commit_builder_class = _commit_builder_class
1666
self._serializer = _serializer
2041
KnitRepository.__init__(self, _format, a_bzrdir, control_files,
2042
_commit_builder_class, _serializer)
2043
index_transport = self._transport.clone('indices')
2044
self._pack_collection = RepositoryPackCollection(self, self._transport,
2046
self._transport.clone('upload'),
2047
self._transport.clone('packs'),
2048
_format.index_builder_class,
2049
_format.index_class)
2050
self.inventories = KnitVersionedFiles(
2051
_KnitGraphIndex(self._pack_collection.inventory_index.combined_index,
2052
add_callback=self._pack_collection.inventory_index.add_callback,
2053
deltas=True, parents=True, is_locked=self.is_locked),
2054
data_access=self._pack_collection.inventory_index.data_access,
2055
max_delta_chain=200)
2056
self.revisions = KnitVersionedFiles(
2057
_KnitGraphIndex(self._pack_collection.revision_index.combined_index,
2058
add_callback=self._pack_collection.revision_index.add_callback,
2059
deltas=False, parents=True, is_locked=self.is_locked),
2060
data_access=self._pack_collection.revision_index.data_access,
2062
self.signatures = KnitVersionedFiles(
2063
_KnitGraphIndex(self._pack_collection.signature_index.combined_index,
2064
add_callback=self._pack_collection.signature_index.add_callback,
2065
deltas=False, parents=False, is_locked=self.is_locked),
2066
data_access=self._pack_collection.signature_index.data_access,
2068
self.texts = KnitVersionedFiles(
2069
_KnitGraphIndex(self._pack_collection.text_index.combined_index,
2070
add_callback=self._pack_collection.text_index.add_callback,
2071
deltas=True, parents=True, is_locked=self.is_locked),
2072
data_access=self._pack_collection.text_index.data_access,
2073
max_delta_chain=200)
2074
self.chk_bytes = None
2075
# True when the repository object is 'write locked' (as opposed to the
2076
# physical lock only taken out around changes to the pack-names list.)
2077
# Another way to represent this would be a decorator around the control
2078
# files object that presents logical locks as physical ones - if this
2079
# gets ugly consider that alternative design. RBC 20071011
2080
self._write_lock_count = 0
2081
self._transaction = None
2083
self._reconcile_does_inventory_gc = True
1667
2084
self._reconcile_fixes_text_parents = True
1668
if self._format.supports_external_lookups:
1669
self._unstacked_provider = graph.CachingParentsProvider(
1670
self._make_parents_provider_unstacked())
1672
self._unstacked_provider = graph.CachingParentsProvider(self)
1673
self._unstacked_provider.disable_cache()
2085
self._reconcile_backsup_inventory = False
1676
def _all_revision_ids(self):
1677
"""See Repository.all_revision_ids()."""
1678
return [key[0] for key in self.revisions.keys()]
2087
def _warn_if_deprecated(self):
2088
# This class isn't deprecated, but one sub-format is
2089
if isinstance(self._format, RepositoryFormatKnitPack5RichRootBroken):
2090
from bzrlib import repository
2091
if repository._deprecation_warning_done:
2093
repository._deprecation_warning_done = True
2094
warning("Format %s for %s is deprecated - please use"
2095
" 'bzr upgrade --1.6.1-rich-root'"
2096
% (self._format, self.bzrdir.transport.base))
1680
2098
def _abort_write_group(self):
1681
self.revisions._index._key_dependencies.clear()
1682
2099
self._pack_collection._abort_write_group()
2101
def _find_inconsistent_revision_parents(self):
2102
"""Find revisions with incorrectly cached parents.
2104
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
2105
parents-in-revision).
2107
if not self.is_locked():
2108
raise errors.ObjectNotLocked(self)
2109
pb = ui.ui_factory.nested_progress_bar()
2112
revision_nodes = self._pack_collection.revision_index \
2113
.combined_index.iter_all_entries()
2114
index_positions = []
2115
# Get the cached index values for all revisions, and also the location
2116
# in each index of the revision text so we can perform linear IO.
2117
for index, key, value, refs in revision_nodes:
2118
pos, length = value[1:].split(' ')
2119
index_positions.append((index, int(pos), key[0],
2120
tuple(parent[0] for parent in refs[0])))
2121
pb.update("Reading revision index", 0, 0)
2122
index_positions.sort()
2123
batch_count = len(index_positions) / 1000 + 1
2124
pb.update("Checking cached revision graph", 0, batch_count)
2125
for offset in xrange(batch_count):
2126
pb.update("Checking cached revision graph", offset)
2127
to_query = index_positions[offset * 1000:(offset + 1) * 1000]
2130
rev_ids = [item[2] for item in to_query]
2131
revs = self.get_revisions(rev_ids)
2132
for revision, item in zip(revs, to_query):
2133
index_parents = item[3]
2134
rev_parents = tuple(revision.parent_ids)
2135
if index_parents != rev_parents:
2136
result.append((revision.revision_id, index_parents, rev_parents))
1684
2141
def _make_parents_provider(self):
1685
if not self._format.supports_external_lookups:
1686
return self._unstacked_provider
1687
return graph.StackedParentsProvider(_LazyListJoin(
1688
[self._unstacked_provider], self._fallback_repositories))
2142
return graph.CachingParentsProvider(self)
1690
2144
def _refresh_data(self):
1691
2145
if not self.is_locked():
1693
2147
self._pack_collection.reload_pack_names()
1694
self._unstacked_provider.disable_cache()
1695
self._unstacked_provider.enable_cache()
1697
2149
def _start_write_group(self):
1698
2150
self._pack_collection._start_write_group()
1700
2152
def _commit_write_group(self):
1701
hint = self._pack_collection._commit_write_group()
1702
self.revisions._index._key_dependencies.clear()
1703
# The commit may have added keys that were previously cached as
1704
# missing, so reset the cache.
1705
self._unstacked_provider.disable_cache()
1706
self._unstacked_provider.enable_cache()
2153
return self._pack_collection._commit_write_group()
1709
2155
def suspend_write_group(self):
1710
2156
# XXX check self._write_group is self.get_transaction()?
1711
2157
tokens = self._pack_collection._suspend_write_group()
1712
self.revisions._index._key_dependencies.clear()
1713
2158
self._write_group = None
1716
2161
def _resume_write_group(self, tokens):
1717
2162
self._start_write_group()
1719
self._pack_collection._resume_write_group(tokens)
1720
except errors.UnresumableWriteGroup:
1721
self._abort_write_group()
1723
for pack in self._pack_collection._resumed_packs:
1724
self.revisions._index.scan_unvalidated_index(pack.revision_index)
2163
self._pack_collection._resume_write_group(tokens)
1726
2165
def get_transaction(self):
1727
2166
if self._write_lock_count:
1910
2326
_serializer=self._serializer)
1913
class RetryPackOperations(errors.RetryWithNewPacks):
1914
"""Raised when we are packing and we find a missing file.
1916
Meant as a signaling exception, to tell the RepositoryPackCollection.pack
1917
code it should try again.
1920
internal_error = True
1922
_fmt = ("Pack files have changed, reload and try pack again."
1923
" context: %(context)s %(orig_error)s")
1926
class _DirectPackAccess(object):
1927
"""Access to data in one or more packs with less translation."""
1929
def __init__(self, index_to_packs, reload_func=None, flush_func=None):
1930
"""Create a _DirectPackAccess object.
1932
:param index_to_packs: A dict mapping index objects to the transport
1933
and file names for obtaining data.
1934
:param reload_func: A function to call if we determine that the pack
1935
files have moved and we need to reload our caches. See
1936
bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
1938
self._container_writer = None
1939
self._write_index = None
1940
self._indices = index_to_packs
1941
self._reload_func = reload_func
1942
self._flush_func = flush_func
1944
def add_raw_records(self, key_sizes, raw_data):
1945
"""Add raw knit bytes to a storage area.
1947
The data is spooled to the container writer in one bytes-record per
1950
:param sizes: An iterable of tuples containing the key and size of each
1952
:param raw_data: A bytestring containing the data.
1953
:return: A list of memos to retrieve the record later. Each memo is an
1954
opaque index memo. For _DirectPackAccess the memo is (index, pos,
1955
length), where the index field is the write_index object supplied
1956
to the PackAccess object.
1958
if type(raw_data) is not str:
1959
raise AssertionError(
1960
'data must be plain bytes was %s' % type(raw_data))
1963
for key, size in key_sizes:
1964
p_offset, p_length = self._container_writer.add_bytes_record(
1965
raw_data[offset:offset+size], [])
1967
result.append((self._write_index, p_offset, p_length))
1971
"""Flush pending writes on this access object.
1973
This will flush any buffered writes to a NewPack.
1975
if self._flush_func is not None:
1978
def get_raw_records(self, memos_for_retrieval):
1979
"""Get the raw bytes for a records.
1981
:param memos_for_retrieval: An iterable containing the (index, pos,
1982
length) memo for retrieving the bytes. The Pack access method
1983
looks up the pack to use for a given record in its index_to_pack
1985
:return: An iterator over the bytes of the records.
1987
# first pass, group into same-index requests
1989
current_index = None
1990
for (index, offset, length) in memos_for_retrieval:
1991
if current_index == index:
1992
current_list.append((offset, length))
1994
if current_index is not None:
1995
request_lists.append((current_index, current_list))
1996
current_index = index
1997
current_list = [(offset, length)]
1998
# handle the last entry
1999
if current_index is not None:
2000
request_lists.append((current_index, current_list))
2001
for index, offsets in request_lists:
2003
transport, path = self._indices[index]
2005
# A KeyError here indicates that someone has triggered an index
2006
# reload, and this index has gone missing, we need to start
2008
if self._reload_func is None:
2009
# If we don't have a _reload_func there is nothing that can
2012
raise errors.RetryWithNewPacks(index,
2013
reload_occurred=True,
2014
exc_info=sys.exc_info())
2016
reader = pack.make_readv_reader(transport, path, offsets)
2017
for names, read_func in reader.iter_records():
2018
yield read_func(None)
2019
except errors.NoSuchFile:
2020
# A NoSuchFile error indicates that a pack file has gone
2021
# missing on disk, we need to trigger a reload, and start over.
2022
if self._reload_func is None:
2024
raise errors.RetryWithNewPacks(transport.abspath(path),
2025
reload_occurred=False,
2026
exc_info=sys.exc_info())
2028
def set_writer(self, writer, index, transport_packname):
2029
"""Set a writer to use for adding data."""
2030
if index is not None:
2031
self._indices[index] = transport_packname
2032
self._container_writer = writer
2033
self._write_index = index
2035
def reload_or_raise(self, retry_exc):
2036
"""Try calling the reload function, or re-raise the original exception.
2038
This should be called after _DirectPackAccess raises a
2039
RetryWithNewPacks exception. This function will handle the common logic
2040
of determining when the error is fatal versus being temporary.
2041
It will also make sure that the original exception is raised, rather
2042
than the RetryWithNewPacks exception.
2044
If this function returns, then the calling function should retry
2045
whatever operation was being performed. Otherwise an exception will
2048
:param retry_exc: A RetryWithNewPacks exception.
2051
if self._reload_func is None:
2053
elif not self._reload_func():
2054
# The reload claimed that nothing changed
2055
if not retry_exc.reload_occurred:
2056
# If there wasn't an earlier reload, then we really were
2057
# expecting to find changes. We didn't find them, so this is a
2061
exc_class, exc_value, exc_traceback = retry_exc.exc_info
2062
raise exc_class, exc_value, exc_traceback
2329
class RepositoryFormatKnitPack1(RepositoryFormatPack):
2330
"""A no-subtrees parameterized Pack repository.
2332
This format was introduced in 0.92.
2335
repository_class = KnitPackRepository
2336
_commit_builder_class = PackCommitBuilder
2338
def _serializer(self):
2339
return xml5.serializer_v5
2340
# What index classes to use
2341
index_builder_class = InMemoryGraphIndex
2342
index_class = GraphIndex
2344
def _get_matching_bzrdir(self):
2345
return bzrdir.format_registry.make_bzrdir('pack-0.92')
2347
def _ignore_setting_bzrdir(self, format):
2350
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2352
def get_format_string(self):
2353
"""See RepositoryFormat.get_format_string()."""
2354
return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
2356
def get_format_description(self):
2357
"""See RepositoryFormat.get_format_description()."""
2358
return "Packs containing knits without subtree support"
2360
def check_conversion_target(self, target_format):
2364
class RepositoryFormatKnitPack3(RepositoryFormatPack):
2365
"""A subtrees parameterized Pack repository.
2367
This repository format uses the xml7 serializer to get:
2368
- support for recording full info about the tree root
2369
- support for recording tree-references
2371
This format was introduced in 0.92.
2374
repository_class = KnitPackRepository
2375
_commit_builder_class = PackRootCommitBuilder
2376
rich_root_data = True
2377
supports_tree_reference = True
2379
def _serializer(self):
2380
return xml7.serializer_v7
2381
# What index classes to use
2382
index_builder_class = InMemoryGraphIndex
2383
index_class = GraphIndex
2385
def _get_matching_bzrdir(self):
2386
return bzrdir.format_registry.make_bzrdir(
2387
'pack-0.92-subtree')
2389
def _ignore_setting_bzrdir(self, format):
2392
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2394
def check_conversion_target(self, target_format):
2395
if not target_format.rich_root_data:
2396
raise errors.BadConversionTarget(
2397
'Does not support rich root data.', target_format)
2398
if not getattr(target_format, 'supports_tree_reference', False):
2399
raise errors.BadConversionTarget(
2400
'Does not support nested trees', target_format)
2402
def get_format_string(self):
2403
"""See RepositoryFormat.get_format_string()."""
2404
return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
2406
def get_format_description(self):
2407
"""See RepositoryFormat.get_format_description()."""
2408
return "Packs containing knits with subtree support\n"
2411
class RepositoryFormatKnitPack4(RepositoryFormatPack):
2412
"""A rich-root, no subtrees parameterized Pack repository.
2414
This repository format uses the xml6 serializer to get:
2415
- support for recording full info about the tree root
2417
This format was introduced in 1.0.
2420
repository_class = KnitPackRepository
2421
_commit_builder_class = PackRootCommitBuilder
2422
rich_root_data = True
2423
supports_tree_reference = False
2425
def _serializer(self):
2426
return xml6.serializer_v6
2427
# What index classes to use
2428
index_builder_class = InMemoryGraphIndex
2429
index_class = GraphIndex
2431
def _get_matching_bzrdir(self):
2432
return bzrdir.format_registry.make_bzrdir(
2435
def _ignore_setting_bzrdir(self, format):
2438
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2440
def check_conversion_target(self, target_format):
2441
if not target_format.rich_root_data:
2442
raise errors.BadConversionTarget(
2443
'Does not support rich root data.', target_format)
2445
def get_format_string(self):
2446
"""See RepositoryFormat.get_format_string()."""
2447
return ("Bazaar pack repository format 1 with rich root"
2448
" (needs bzr 1.0)\n")
2450
def get_format_description(self):
2451
"""See RepositoryFormat.get_format_description()."""
2452
return "Packs containing knits with rich root support\n"
2455
class RepositoryFormatKnitPack5(RepositoryFormatPack):
2456
"""Repository that supports external references to allow stacking.
2460
Supports external lookups, which results in non-truncated ghosts after
2461
reconcile compared to pack-0.92 formats.
2464
repository_class = KnitPackRepository
2465
_commit_builder_class = PackCommitBuilder
2466
supports_external_lookups = True
2467
# What index classes to use
2468
index_builder_class = InMemoryGraphIndex
2469
index_class = GraphIndex
2472
def _serializer(self):
2473
return xml5.serializer_v5
2475
def _get_matching_bzrdir(self):
2476
return bzrdir.format_registry.make_bzrdir('1.6')
2478
def _ignore_setting_bzrdir(self, format):
2481
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2483
def get_format_string(self):
2484
"""See RepositoryFormat.get_format_string()."""
2485
return "Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n"
2487
def get_format_description(self):
2488
"""See RepositoryFormat.get_format_description()."""
2489
return "Packs 5 (adds stacking support, requires bzr 1.6)"
2491
def check_conversion_target(self, target_format):
2495
class RepositoryFormatKnitPack5RichRoot(RepositoryFormatPack):
2496
"""A repository with rich roots and stacking.
2498
New in release 1.6.1.
2500
Supports stacking on other repositories, allowing data to be accessed
2501
without being stored locally.
2504
repository_class = KnitPackRepository
2505
_commit_builder_class = PackRootCommitBuilder
2506
rich_root_data = True
2507
supports_tree_reference = False # no subtrees
2508
supports_external_lookups = True
2509
# What index classes to use
2510
index_builder_class = InMemoryGraphIndex
2511
index_class = GraphIndex
2514
def _serializer(self):
2515
return xml6.serializer_v6
2517
def _get_matching_bzrdir(self):
2518
return bzrdir.format_registry.make_bzrdir(
2521
def _ignore_setting_bzrdir(self, format):
2524
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2526
def check_conversion_target(self, target_format):
2527
if not target_format.rich_root_data:
2528
raise errors.BadConversionTarget(
2529
'Does not support rich root data.', target_format)
2531
def get_format_string(self):
2532
"""See RepositoryFormat.get_format_string()."""
2533
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n"
2535
def get_format_description(self):
2536
return "Packs 5 rich-root (adds stacking support, requires bzr 1.6.1)"
2539
class RepositoryFormatKnitPack5RichRootBroken(RepositoryFormatPack):
2540
"""A repository with rich roots and external references.
2544
Supports external lookups, which results in non-truncated ghosts after
2545
reconcile compared to pack-0.92 formats.
2547
This format was deprecated because the serializer it uses accidentally
2548
supported subtrees, when the format was not intended to. This meant that
2549
someone could accidentally fetch from an incorrect repository.
2552
repository_class = KnitPackRepository
2553
_commit_builder_class = PackRootCommitBuilder
2554
rich_root_data = True
2555
supports_tree_reference = False # no subtrees
2557
supports_external_lookups = True
2558
# What index classes to use
2559
index_builder_class = InMemoryGraphIndex
2560
index_class = GraphIndex
2563
def _serializer(self):
2564
return xml7.serializer_v7
2566
def _get_matching_bzrdir(self):
2567
matching = bzrdir.format_registry.make_bzrdir(
2569
matching.repository_format = self
2572
def _ignore_setting_bzrdir(self, format):
2575
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2577
def check_conversion_target(self, target_format):
2578
if not target_format.rich_root_data:
2579
raise errors.BadConversionTarget(
2580
'Does not support rich root data.', target_format)
2582
def get_format_string(self):
2583
"""See RepositoryFormat.get_format_string()."""
2584
return "Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n"
2586
def get_format_description(self):
2587
return ("Packs 5 rich-root (adds stacking support, requires bzr 1.6)"
2591
class RepositoryFormatKnitPack6(RepositoryFormatPack):
2592
"""A repository with stacking and btree indexes,
2593
without rich roots or subtrees.
2595
This is equivalent to pack-1.6 with B+Tree indices.
2598
repository_class = KnitPackRepository
2599
_commit_builder_class = PackCommitBuilder
2600
supports_external_lookups = True
2601
# What index classes to use
2602
index_builder_class = BTreeBuilder
2603
index_class = BTreeGraphIndex
2606
def _serializer(self):
2607
return xml5.serializer_v5
2609
def _get_matching_bzrdir(self):
2610
return bzrdir.format_registry.make_bzrdir('1.9')
2612
def _ignore_setting_bzrdir(self, format):
2615
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2617
def get_format_string(self):
2618
"""See RepositoryFormat.get_format_string()."""
2619
return "Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n"
2621
def get_format_description(self):
2622
"""See RepositoryFormat.get_format_description()."""
2623
return "Packs 6 (uses btree indexes, requires bzr 1.9)"
2625
def check_conversion_target(self, target_format):
2629
class RepositoryFormatKnitPack6RichRoot(RepositoryFormatPack):
2630
"""A repository with rich roots, no subtrees, stacking and btree indexes.
2632
1.6-rich-root with B+Tree indices.
2635
repository_class = KnitPackRepository
2636
_commit_builder_class = PackRootCommitBuilder
2637
rich_root_data = True
2638
supports_tree_reference = False # no subtrees
2639
supports_external_lookups = True
2640
# What index classes to use
2641
index_builder_class = BTreeBuilder
2642
index_class = BTreeGraphIndex
2645
def _serializer(self):
2646
return xml6.serializer_v6
2648
def _get_matching_bzrdir(self):
2649
return bzrdir.format_registry.make_bzrdir(
2652
def _ignore_setting_bzrdir(self, format):
2655
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2657
def check_conversion_target(self, target_format):
2658
if not target_format.rich_root_data:
2659
raise errors.BadConversionTarget(
2660
'Does not support rich root data.', target_format)
2662
def get_format_string(self):
2663
"""See RepositoryFormat.get_format_string()."""
2664
return "Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n"
2666
def get_format_description(self):
2667
return "Packs 6 rich-root (uses btree indexes, requires bzr 1.9)"
2670
class RepositoryFormatPackDevelopment2(RepositoryFormatPack):
2671
"""A no-subtrees development repository.
2673
This format should be retained until the second release after bzr 1.7.
2675
This is pack-1.6.1 with B+Tree indices.
2678
repository_class = KnitPackRepository
2679
_commit_builder_class = PackCommitBuilder
2680
supports_external_lookups = True
2681
# What index classes to use
2682
index_builder_class = BTreeBuilder
2683
index_class = BTreeGraphIndex
2684
# Set to true to get the fast-commit code path tested until a really fast
2685
# format lands in trunk. Not actually fast in this format.
2689
def _serializer(self):
2690
return xml5.serializer_v5
2692
def _get_matching_bzrdir(self):
2693
return bzrdir.format_registry.make_bzrdir('development2')
2695
def _ignore_setting_bzrdir(self, format):
2698
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2700
def get_format_string(self):
2701
"""See RepositoryFormat.get_format_string()."""
2702
return "Bazaar development format 2 (needs bzr.dev from before 1.8)\n"
2704
def get_format_description(self):
2705
"""See RepositoryFormat.get_format_description()."""
2706
return ("Development repository format, currently the same as "
2707
"1.6.1 with B+Trees.\n")
2709
def check_conversion_target(self, target_format):
2713
class RepositoryFormatPackDevelopment2Subtree(RepositoryFormatPack):
2714
"""A subtrees development repository.
2716
This format should be retained until the second release after bzr 1.7.
2718
1.6.1-subtree[as it might have been] with B+Tree indices.
2721
repository_class = KnitPackRepository
2722
_commit_builder_class = PackRootCommitBuilder
2723
rich_root_data = True
2724
supports_tree_reference = True
2725
supports_external_lookups = True
2726
# What index classes to use
2727
index_builder_class = BTreeBuilder
2728
index_class = BTreeGraphIndex
2731
def _serializer(self):
2732
return xml7.serializer_v7
2734
def _get_matching_bzrdir(self):
2735
return bzrdir.format_registry.make_bzrdir(
2736
'development2-subtree')
2738
def _ignore_setting_bzrdir(self, format):
2741
_matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
2743
def check_conversion_target(self, target_format):
2744
if not target_format.rich_root_data:
2745
raise errors.BadConversionTarget(
2746
'Does not support rich root data.', target_format)
2747
if not getattr(target_format, 'supports_tree_reference', False):
2748
raise errors.BadConversionTarget(
2749
'Does not support nested trees', target_format)
2751
def get_format_string(self):
2752
"""See RepositoryFormat.get_format_string()."""
2753
return ("Bazaar development format 2 with subtree support "
2754
"(needs bzr.dev from before 1.8)\n")
2756
def get_format_description(self):
2757
"""See RepositoryFormat.get_format_description()."""
2758
return ("Development repository format, currently the same as "
2759
"1.6.1-subtree with B+Tree indices.\n")