86
110
if not element or _whitespace_re.search(element) is not None:
87
111
raise errors.BadIndexKey(element)
89
def add_node(self, key, value, references=()):
90
"""Add a node to the index.
92
:param key: The key. keys are non-empty tuples containing
93
as many whitespace-free utf8 bytestrings as the key length
94
defined for this index.
95
:param references: An iterable of iterables of keys. Each is a
96
reference to another key.
97
:param value: The value to associate with the key. It may be any
98
bytes as long as it does not contain \0 or \n.
113
def _external_references(self):
114
"""Return references that are not present in this index.
118
# TODO: JAM 2008-11-21 This makes an assumption about how the reference
119
# lists are used. It is currently correct for pack-0.92 through
120
# 1.9, which use the node references (3rd column) second
121
# reference list as the compression parent. Perhaps this should
122
# be moved into something higher up the stack, since it
123
# makes assumptions about how the index is used.
124
if self.reference_lists > 1:
125
for node in self.iter_all_entries():
127
refs.update(node[3][1])
130
# If reference_lists == 0 there can be no external references, and
131
# if reference_lists == 1, then there isn't a place to store the
135
def _get_nodes_by_key(self):
136
if self._nodes_by_key is None:
138
if self.reference_lists:
139
for key, (absent, references, value) in self._nodes.iteritems():
142
key_dict = nodes_by_key
143
for subkey in key[:-1]:
144
key_dict = key_dict.setdefault(subkey, {})
145
key_dict[key[-1]] = key, value, references
147
for key, (absent, references, value) in self._nodes.iteritems():
150
key_dict = nodes_by_key
151
for subkey in key[:-1]:
152
key_dict = key_dict.setdefault(subkey, {})
153
key_dict[key[-1]] = key, value
154
self._nodes_by_key = nodes_by_key
155
return self._nodes_by_key
157
def _update_nodes_by_key(self, key, value, node_refs):
158
"""Update the _nodes_by_key dict with a new key.
160
For a key of (foo, bar, baz) create
161
_nodes_by_key[foo][bar][baz] = key_value
163
if self._nodes_by_key is None:
165
key_dict = self._nodes_by_key
166
if self.reference_lists:
167
key_value = key, value, node_refs
169
key_value = key, value
170
for subkey in key[:-1]:
171
key_dict = key_dict.setdefault(subkey, {})
172
key_dict[key[-1]] = key_value
174
def _check_key_ref_value(self, key, references, value):
175
"""Check that 'key' and 'references' are all valid.
177
:param key: A key tuple. Must conform to the key interface (be a tuple,
178
be of the right length, not have any whitespace or nulls in any key
180
:param references: An iterable of reference lists. Something like
181
[[(ref, key)], [(ref, key), (other, key)]]
182
:param value: The value associate with this key. Must not contain
183
newlines or null characters.
184
:return: (node_refs, absent_references)
185
node_refs basically a packed form of 'references' where all
187
absent_references reference keys that are not in self._nodes.
188
This may contain duplicates if the same key is
189
referenced in multiple lists.
100
191
self._check_key(key)
101
192
if _newline_null_re.search(value) is not None:
232
368
suitable for production use. :XXX
235
def __init__(self, transport, name):
371
def __init__(self, transport, name, size):
236
372
"""Open an index called name on transport.
238
374
:param transport: A bzrlib.transport.Transport.
239
375
:param name: A path to provide to transport API calls.
376
:param size: The size of the index in bytes. This is used for bisection
377
logic to perform partial index reads. While the size could be
378
obtained by statting the file this introduced an additional round
379
trip as well as requiring stat'able transports, both of which are
380
avoided by having it supplied. If size is None, then bisection
381
support will be disabled and accessing the index will just stream
241
384
self._transport = transport
242
385
self._name = name
386
# Becomes a dict of key:(value, reference-list-byte-locations) used by
387
# the bisection interface to store parsed but not resolved keys.
388
self._bisect_nodes = None
389
# Becomes a dict of key:(value, reference-list-keys) which are ready to
390
# be returned directly to callers.
243
391
self._nodes = None
392
# a sorted list of slice-addresses for the parsed bytes of the file.
393
# e.g. (0,1) would mean that byte 0 is parsed.
394
self._parsed_byte_map = []
395
# a sorted list of keys matching each slice address for parsed bytes
396
# e.g. (None, 'foo@bar') would mean that the first byte contained no
397
# key, and the end byte of the slice is the of the data for 'foo@bar'
398
self._parsed_key_map = []
244
399
self._key_count = None
245
400
self._keys_by_offset = None
246
401
self._nodes_by_key = None
248
def _buffer_all(self):
403
# The number of bytes we've read so far in trying to process this file
406
def __eq__(self, other):
407
"""Equal when self and other were created with the same parameters."""
409
type(self) == type(other) and
410
self._transport == other._transport and
411
self._name == other._name and
412
self._size == other._size)
414
def __ne__(self, other):
415
return not self.__eq__(other)
418
return "%s(%r)" % (self.__class__.__name__,
419
self._transport.abspath(self._name))
421
def _buffer_all(self, stream=None):
249
422
"""Buffer all the index data.
251
424
Mutates self._nodes and self.keys_by_offset.
426
if self._nodes is not None:
427
# We already did this
253
429
if 'index' in debug.debug_flags:
254
430
mutter('Reading entire index %s', self._transport.abspath(self._name))
255
stream = self._transport.get(self._name)
432
stream = self._transport.get(self._name)
256
433
self._read_prefix(stream)
257
expected_elements = 3 + self._key_length
434
self._expected_elements = 3 + self._key_length
259
436
# raw data keyed by offset
260
437
self._keys_by_offset = {}
261
438
# ready-to-return key:value or key:value, node_ref_lists
263
self._nodes_by_key = {}
440
self._nodes_by_key = None
265
442
pos = stream.tell()
266
for line in stream.readlines():
270
elements = line.split('\0')
271
if len(elements) != expected_elements:
272
raise errors.BadIndexData(self)
274
key = tuple(elements[:self._key_length])
275
absent, references, value = elements[-3:]
276
value = value[:-1] # remove the newline
278
for ref_string in references.split('\t'):
279
ref_lists.append(tuple([
280
int(ref) for ref in ref_string.split('\r') if ref
282
ref_lists = tuple(ref_lists)
283
self._keys_by_offset[pos] = (key, absent, ref_lists, value)
443
lines = stream.read().split('\n')
445
_, _, _, trailers = self._parse_lines(lines, pos)
285
446
for key, absent, references, value in self._keys_by_offset.itervalues():
288
449
# resolve references:
289
450
if self.node_ref_lists:
291
for ref_list in references:
292
node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
293
node_value = (value, tuple(node_refs))
451
node_value = (value, self._resolve_references(references))
295
453
node_value = value
296
454
self._nodes[key] = node_value
297
if self._key_length > 1:
298
subkey = list(reversed(key[:-1]))
299
key_dict = self._nodes_by_key
300
if self.node_ref_lists:
301
key_value = key, node_value[0], node_value[1]
303
key_value = key, node_value
304
# possibly should do this on-demand, but it seems likely it is
306
# For a key of (foo, bar, baz) create
307
# _nodes_by_key[foo][bar][baz] = key_value
308
for subkey in key[:-1]:
309
key_dict = key_dict.setdefault(subkey, {})
310
key_dict[key[-1]] = key_value
311
455
# cache the keys for quick set intersections
312
456
self._keys = set(self._nodes)
313
457
if trailers != 1:
314
458
# there must be one line - the empty trailer line.
315
459
raise errors.BadIndexData(self)
461
def external_references(self, ref_list_num):
462
"""Return references that are not present in this index.
465
if ref_list_num + 1 > self.node_ref_lists:
466
raise ValueError('No ref list %d, index has %d ref lists'
467
% (ref_list_num, self.node_ref_lists))
469
for key, (value, ref_lists) in self._nodes.iteritems():
470
ref_list = ref_lists[ref_list_num]
471
refs.update(ref_list)
472
return refs - self._keys
474
def _get_nodes_by_key(self):
475
if self._nodes_by_key is None:
477
if self.node_ref_lists:
478
for key, (value, references) in self._nodes.iteritems():
479
key_dict = nodes_by_key
480
for subkey in key[:-1]:
481
key_dict = key_dict.setdefault(subkey, {})
482
key_dict[key[-1]] = key, value, references
484
for key, value in self._nodes.iteritems():
485
key_dict = nodes_by_key
486
for subkey in key[:-1]:
487
key_dict = key_dict.setdefault(subkey, {})
488
key_dict[key[-1]] = key, value
489
self._nodes_by_key = nodes_by_key
490
return self._nodes_by_key
317
492
def iter_all_entries(self):
318
493
"""Iterate over all keys within the index.
320
:return: An iterable of (key, value) or (key, value, reference_lists).
495
:return: An iterable of (index, key, value) or (index, key, value, reference_lists).
321
496
The former tuple is used when there are no reference lists in the
322
497
index, making the API compatible with simple key:value index types.
323
498
There is no defined order for the result iteration - it will be in
324
499
the most efficient order for the index.
326
501
if 'evil' in debug.debug_flags:
327
trace.mutter_callsite(2,
502
trace.mutter_callsite(3,
328
503
"iter_all_entries scales with size of history.")
329
504
if self._nodes is None:
330
505
self._buffer_all()
455
718
# the last thing looked up was a terminal element
456
719
yield (self, ) + key_dict
721
def _find_ancestors(self, keys, ref_list_num, parent_map, missing_keys):
722
"""See BTreeIndex._find_ancestors."""
723
# The api can be implemented as a trivial overlay on top of
724
# iter_entries, it is not an efficient implementation, but it at least
728
for index, key, value, refs in self.iter_entries(keys):
729
parent_keys = refs[ref_list_num]
731
parent_map[key] = parent_keys
732
search_keys.update(parent_keys)
733
# Figure out what, if anything, was missing
734
missing_keys.update(set(keys).difference(found_keys))
735
search_keys = search_keys.difference(parent_map)
458
738
def key_count(self):
459
739
"""Return an estimate of the number of keys in this index.
461
741
For GraphIndex the estimate is exact.
463
743
if self._key_count is None:
464
# really this should just read the prefix
744
self._read_and_parse([_HEADER_READV])
466
745
return self._key_count
747
def _lookup_keys_via_location(self, location_keys):
748
"""Public interface for implementing bisection.
750
If _buffer_all has been called, then all the data for the index is in
751
memory, and this method should not be called, as it uses a separate
752
cache because it cannot pre-resolve all indices, which buffer_all does
755
:param location_keys: A list of location(byte offset), key tuples.
756
:return: A list of (location_key, result) tuples as expected by
757
bzrlib.bisect_multi.bisect_multi_bytes.
759
# Possible improvements:
760
# - only bisect lookup each key once
761
# - sort the keys first, and use that to reduce the bisection window
763
# this progresses in three parts:
766
# attempt to answer the question from the now in memory data.
767
# build the readv request
768
# for each location, ask for 800 bytes - much more than rows we've seen
771
for location, key in location_keys:
772
# can we answer from cache?
773
if self._bisect_nodes and key in self._bisect_nodes:
774
# We have the key parsed.
776
index = self._parsed_key_index(key)
777
if (len(self._parsed_key_map) and
778
self._parsed_key_map[index][0] <= key and
779
(self._parsed_key_map[index][1] >= key or
780
# end of the file has been parsed
781
self._parsed_byte_map[index][1] == self._size)):
782
# the key has been parsed, so no lookup is needed even if its
785
# - if we have examined this part of the file already - yes
786
index = self._parsed_byte_index(location)
787
if (len(self._parsed_byte_map) and
788
self._parsed_byte_map[index][0] <= location and
789
self._parsed_byte_map[index][1] > location):
790
# the byte region has been parsed, so no read is needed.
793
if location + length > self._size:
794
length = self._size - location
795
# todo, trim out parsed locations.
797
readv_ranges.append((location, length))
798
# read the header if needed
799
if self._bisect_nodes is None:
800
readv_ranges.append(_HEADER_READV)
801
self._read_and_parse(readv_ranges)
803
if self._nodes is not None:
804
# _read_and_parse triggered a _buffer_all because we requested the
806
for location, key in location_keys:
807
if key not in self._nodes: # not present
808
result.append(((location, key), False))
809
elif self.node_ref_lists:
810
value, refs = self._nodes[key]
811
result.append(((location, key),
812
(self, key, value, refs)))
814
result.append(((location, key),
815
(self, key, self._nodes[key])))
818
# - figure out <, >, missing, present
819
# - result present references so we can return them.
820
# keys that we cannot answer until we resolve references
821
pending_references = []
822
pending_locations = set()
823
for location, key in location_keys:
824
# can we answer from cache?
825
if key in self._bisect_nodes:
826
# the key has been parsed, so no lookup is needed
827
if self.node_ref_lists:
828
# the references may not have been all parsed.
829
value, refs = self._bisect_nodes[key]
830
wanted_locations = []
831
for ref_list in refs:
833
if ref not in self._keys_by_offset:
834
wanted_locations.append(ref)
836
pending_locations.update(wanted_locations)
837
pending_references.append((location, key))
839
result.append(((location, key), (self, key,
840
value, self._resolve_references(refs))))
842
result.append(((location, key),
843
(self, key, self._bisect_nodes[key])))
846
# has the region the key should be in, been parsed?
847
index = self._parsed_key_index(key)
848
if (self._parsed_key_map[index][0] <= key and
849
(self._parsed_key_map[index][1] >= key or
850
# end of the file has been parsed
851
self._parsed_byte_map[index][1] == self._size)):
852
result.append(((location, key), False))
854
# no, is the key above or below the probed location:
855
# get the range of the probed & parsed location
856
index = self._parsed_byte_index(location)
857
# if the key is below the start of the range, its below
858
if key < self._parsed_key_map[index][0]:
862
result.append(((location, key), direction))
864
# lookup data to resolve references
865
for location in pending_locations:
867
if location + length > self._size:
868
length = self._size - location
869
# TODO: trim out parsed locations (e.g. if the 800 is into the
870
# parsed region trim it, and dont use the adjust_for_latency
873
readv_ranges.append((location, length))
874
self._read_and_parse(readv_ranges)
875
if self._nodes is not None:
876
# The _read_and_parse triggered a _buffer_all, grab the data and
878
for location, key in pending_references:
879
value, refs = self._nodes[key]
880
result.append(((location, key), (self, key, value, refs)))
882
for location, key in pending_references:
883
# answer key references we had to look-up-late.
884
value, refs = self._bisect_nodes[key]
885
result.append(((location, key), (self, key,
886
value, self._resolve_references(refs))))
889
def _parse_header_from_bytes(self, bytes):
890
"""Parse the header from a region of bytes.
892
:param bytes: The data to parse.
893
:return: An offset, data tuple such as readv yields, for the unparsed
894
data. (which may length 0).
896
signature = bytes[0:len(self._signature())]
897
if not signature == self._signature():
898
raise errors.BadIndexFormatSignature(self._name, GraphIndex)
899
lines = bytes[len(self._signature()):].splitlines()
900
options_line = lines[0]
901
if not options_line.startswith(_OPTION_NODE_REFS):
902
raise errors.BadIndexOptions(self)
904
self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):])
906
raise errors.BadIndexOptions(self)
907
options_line = lines[1]
908
if not options_line.startswith(_OPTION_KEY_ELEMENTS):
909
raise errors.BadIndexOptions(self)
911
self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):])
913
raise errors.BadIndexOptions(self)
914
options_line = lines[2]
915
if not options_line.startswith(_OPTION_LEN):
916
raise errors.BadIndexOptions(self)
918
self._key_count = int(options_line[len(_OPTION_LEN):])
920
raise errors.BadIndexOptions(self)
921
# calculate the bytes we have processed
922
header_end = (len(signature) + len(lines[0]) + len(lines[1]) +
924
self._parsed_bytes(0, None, header_end, None)
925
# setup parsing state
926
self._expected_elements = 3 + self._key_length
927
# raw data keyed by offset
928
self._keys_by_offset = {}
929
# keys with the value and node references
930
self._bisect_nodes = {}
931
return header_end, bytes[header_end:]
933
def _parse_region(self, offset, data):
934
"""Parse node data returned from a readv operation.
936
:param offset: The byte offset the data starts at.
937
:param data: The data to parse.
941
end = offset + len(data)
944
# Trivial test - if the current index's end is within the
945
# low-matching parsed range, we're done.
946
index = self._parsed_byte_index(high_parsed)
947
if end < self._parsed_byte_map[index][1]:
949
# print "[%d:%d]" % (offset, end), \
950
# self._parsed_byte_map[index:index + 2]
951
high_parsed, last_segment = self._parse_segment(
952
offset, data, end, index)
956
def _parse_segment(self, offset, data, end, index):
957
"""Parse one segment of data.
959
:param offset: Where 'data' begins in the file.
960
:param data: Some data to parse a segment of.
961
:param end: Where data ends
962
:param index: The current index into the parsed bytes map.
963
:return: True if the parsed segment is the last possible one in the
965
:return: high_parsed_byte, last_segment.
966
high_parsed_byte is the location of the highest parsed byte in this
967
segment, last_segment is True if the parsed segment is the last
968
possible one in the data block.
970
# default is to use all data
972
# accomodate overlap with data before this.
973
if offset < self._parsed_byte_map[index][1]:
974
# overlaps the lower parsed region
975
# skip the parsed data
976
trim_start = self._parsed_byte_map[index][1] - offset
977
# don't trim the start for \n
978
start_adjacent = True
979
elif offset == self._parsed_byte_map[index][1]:
980
# abuts the lower parsed region
983
# do not trim anything
984
start_adjacent = True
986
# does not overlap the lower parsed region
989
# but trim the leading \n
990
start_adjacent = False
991
if end == self._size:
992
# lines up to the end of all data:
995
# do not strip to the last \n
998
elif index + 1 == len(self._parsed_byte_map):
999
# at the end of the parsed data
1002
# but strip to the last \n
1003
end_adjacent = False
1005
elif end == self._parsed_byte_map[index + 1][0]:
1006
# buts up against the next parsed region
1009
# do not strip to the last \n
1012
elif end > self._parsed_byte_map[index + 1][0]:
1013
# overlaps into the next parsed region
1014
# only consider the unparsed data
1015
trim_end = self._parsed_byte_map[index + 1][0] - offset
1016
# do not strip to the last \n as we know its an entire record
1018
last_segment = end < self._parsed_byte_map[index + 1][1]
1020
# does not overlap into the next region
1023
# but strip to the last \n
1024
end_adjacent = False
1026
# now find bytes to discard if needed
1027
if not start_adjacent:
1028
# work around python bug in rfind
1029
if trim_start is None:
1030
trim_start = data.find('\n') + 1
1032
trim_start = data.find('\n', trim_start) + 1
1033
if not (trim_start != 0):
1034
raise AssertionError('no \n was present')
1035
# print 'removing start', offset, trim_start, repr(data[:trim_start])
1036
if not end_adjacent:
1037
# work around python bug in rfind
1038
if trim_end is None:
1039
trim_end = data.rfind('\n') + 1
1041
trim_end = data.rfind('\n', None, trim_end) + 1
1042
if not (trim_end != 0):
1043
raise AssertionError('no \n was present')
1044
# print 'removing end', offset, trim_end, repr(data[trim_end:])
1045
# adjust offset and data to the parseable data.
1046
trimmed_data = data[trim_start:trim_end]
1047
if not (trimmed_data):
1048
raise AssertionError('read unneeded data [%d:%d] from [%d:%d]'
1049
% (trim_start, trim_end, offset, offset + len(data)))
1051
offset += trim_start
1052
# print "parsing", repr(trimmed_data)
1053
# splitlines mangles the \r delimiters.. don't use it.
1054
lines = trimmed_data.split('\n')
1057
first_key, last_key, nodes, _ = self._parse_lines(lines, pos)
1058
for key, value in nodes:
1059
self._bisect_nodes[key] = value
1060
self._parsed_bytes(offset, first_key,
1061
offset + len(trimmed_data), last_key)
1062
return offset + len(trimmed_data), last_segment
1064
def _parse_lines(self, lines, pos):
1071
# must be at the end
1073
if not (self._size == pos + 1):
1074
raise AssertionError("%s %s" % (self._size, pos))
1077
elements = line.split('\0')
1078
if len(elements) != self._expected_elements:
1079
raise errors.BadIndexData(self)
1080
# keys are tuples. Each element is a string that may occur many
1081
# times, so we intern them to save space. AB, RC, 200807
1082
key = tuple([intern(element) for element in elements[:self._key_length]])
1083
if first_key is None:
1085
absent, references, value = elements[-3:]
1087
for ref_string in references.split('\t'):
1088
ref_lists.append(tuple([
1089
int(ref) for ref in ref_string.split('\r') if ref
1091
ref_lists = tuple(ref_lists)
1092
self._keys_by_offset[pos] = (key, absent, ref_lists, value)
1093
pos += len(line) + 1 # +1 for the \n
1096
if self.node_ref_lists:
1097
node_value = (value, ref_lists)
1100
nodes.append((key, node_value))
1101
# print "parsed ", key
1102
return first_key, key, nodes, trailers
1104
def _parsed_bytes(self, start, start_key, end, end_key):
1105
"""Mark the bytes from start to end as parsed.
1107
Calling self._parsed_bytes(1,2) will mark one byte (the one at offset
1110
:param start: The start of the parsed region.
1111
:param end: The end of the parsed region.
1113
index = self._parsed_byte_index(start)
1114
new_value = (start, end)
1115
new_key = (start_key, end_key)
1117
# first range parsed is always the beginning.
1118
self._parsed_byte_map.insert(index, new_value)
1119
self._parsed_key_map.insert(index, new_key)
1123
# extend lower region
1124
# extend higher region
1125
# combine two regions
1126
if (index + 1 < len(self._parsed_byte_map) and
1127
self._parsed_byte_map[index][1] == start and
1128
self._parsed_byte_map[index + 1][0] == end):
1129
# combine two regions
1130
self._parsed_byte_map[index] = (self._parsed_byte_map[index][0],
1131
self._parsed_byte_map[index + 1][1])
1132
self._parsed_key_map[index] = (self._parsed_key_map[index][0],
1133
self._parsed_key_map[index + 1][1])
1134
del self._parsed_byte_map[index + 1]
1135
del self._parsed_key_map[index + 1]
1136
elif self._parsed_byte_map[index][1] == start:
1137
# extend the lower entry
1138
self._parsed_byte_map[index] = (
1139
self._parsed_byte_map[index][0], end)
1140
self._parsed_key_map[index] = (
1141
self._parsed_key_map[index][0], end_key)
1142
elif (index + 1 < len(self._parsed_byte_map) and
1143
self._parsed_byte_map[index + 1][0] == end):
1144
# extend the higher entry
1145
self._parsed_byte_map[index + 1] = (
1146
start, self._parsed_byte_map[index + 1][1])
1147
self._parsed_key_map[index + 1] = (
1148
start_key, self._parsed_key_map[index + 1][1])
1151
self._parsed_byte_map.insert(index + 1, new_value)
1152
self._parsed_key_map.insert(index + 1, new_key)
1154
def _read_and_parse(self, readv_ranges):
1155
"""Read the the ranges and parse the resulting data.
1157
:param readv_ranges: A prepared readv range list.
1159
if not readv_ranges:
1161
if self._nodes is None and self._bytes_read * 2 >= self._size:
1162
# We've already read more than 50% of the file and we are about to
1163
# request more data, just _buffer_all() and be done
1167
readv_data = self._transport.readv(self._name, readv_ranges, True,
1170
for offset, data in readv_data:
1171
self._bytes_read += len(data)
1172
if offset == 0 and len(data) == self._size:
1173
# We read the whole range, most likely because the
1174
# Transport upcast our readv ranges into one long request
1175
# for enough total data to grab the whole index.
1176
self._buffer_all(StringIO(data))
1178
if self._bisect_nodes is None:
1179
# this must be the start
1180
if not (offset == 0):
1181
raise AssertionError()
1182
offset, data = self._parse_header_from_bytes(data)
1183
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1184
self._parse_region(offset, data)
468
1186
def _signature(self):
469
1187
"""The file signature for this index type."""
470
1188
return _SIGNATURE
566
1320
seen_keys = set()
567
for index in self._indices:
568
for node in index.iter_entries_prefix(keys):
569
if node[1] in seen_keys:
571
seen_keys.add(node[1])
1323
for index in self._indices:
1324
for node in index.iter_entries_prefix(keys):
1325
if node[1] in seen_keys:
1327
seen_keys.add(node[1])
1330
except errors.NoSuchFile:
1331
self._reload_or_raise()
1333
def find_ancestry(self, keys, ref_list_num):
1334
"""Find the complete ancestry for the given set of keys.
1336
Note that this is a whole-ancestry request, so it should be used
1339
:param keys: An iterable of keys to look for
1340
:param ref_list_num: The reference list which references the parents
1342
:return: (parent_map, missing_keys)
1344
missing_keys = set()
1346
keys_to_lookup = set(keys)
1348
while keys_to_lookup:
1349
# keys that *all* indexes claim are missing, stop searching them
1351
all_index_missing = None
1352
# print 'gen\tidx\tsub\tn_keys\tn_pmap\tn_miss'
1353
# print '%4d\t\t\t%4d\t%5d\t%5d' % (generation, len(keys_to_lookup),
1355
# len(missing_keys))
1356
for index_idx, index in enumerate(self._indices):
1357
# TODO: we should probably be doing something with
1358
# 'missing_keys' since we've already determined that
1359
# those revisions have not been found anywhere
1360
index_missing_keys = set()
1361
# Find all of the ancestry we can from this index
1362
# keep looking until the search_keys set is empty, which means
1363
# things we didn't find should be in index_missing_keys
1364
search_keys = keys_to_lookup
1366
# print ' \t%2d\t\t%4d\t%5d\t%5d' % (
1367
# index_idx, len(search_keys),
1368
# len(parent_map), len(index_missing_keys))
1371
# TODO: ref_list_num should really be a parameter, since
1372
# CombinedGraphIndex does not know what the ref lists
1374
search_keys = index._find_ancestors(search_keys,
1375
ref_list_num, parent_map, index_missing_keys)
1376
# print ' \t \t%2d\t%4d\t%5d\t%5d' % (
1377
# sub_generation, len(search_keys),
1378
# len(parent_map), len(index_missing_keys))
1379
# Now set whatever was missing to be searched in the next index
1380
keys_to_lookup = index_missing_keys
1381
if all_index_missing is None:
1382
all_index_missing = set(index_missing_keys)
1384
all_index_missing.intersection_update(index_missing_keys)
1385
if not keys_to_lookup:
1387
if all_index_missing is None:
1388
# There were no indexes, so all search keys are 'missing'
1389
missing_keys.update(keys_to_lookup)
1390
keys_to_lookup = None
1392
missing_keys.update(all_index_missing)
1393
keys_to_lookup.difference_update(all_index_missing)
1394
return parent_map, missing_keys
574
1396
def key_count(self):
575
1397
"""Return an estimate of the number of keys in this index.
577
1399
For CombinedGraphIndex this is approximated by the sum of the keys of
578
1400
the child indices. As child indices may have duplicate keys this can
579
1401
have a maximum error of the number of child indices * largest number of
580
1402
keys in any index.
582
return sum((index.key_count() for index in self._indices), 0)
1406
return sum((index.key_count() for index in self._indices), 0)
1407
except errors.NoSuchFile:
1408
self._reload_or_raise()
1410
missing_keys = _missing_keys_from_parent_map
1412
def _reload_or_raise(self):
1413
"""We just got a NoSuchFile exception.
1415
Try to reload the indices, if it fails, just raise the current
1418
if self._reload_func is None:
1420
exc_type, exc_value, exc_traceback = sys.exc_info()
1421
trace.mutter('Trying to reload after getting exception: %s',
1423
if not self._reload_func():
1424
# We tried to reload, but nothing changed, so we fail anyway
1425
trace.mutter('_reload_func indicated nothing has changed.'
1426
' Raising original exception.')
1427
raise exc_type, exc_value, exc_traceback
584
1429
def validate(self):
585
1430
"""Validate that everything in the index can be accessed."""
586
for index in self._indices:
1433
for index in self._indices:
1436
except errors.NoSuchFile:
1437
self._reload_or_raise()
590
1440
class InMemoryGraphIndex(GraphIndexBuilder):