52
53
_newline_null_re = re.compile('[\n\0]')
56
def _has_key_from_parent_map(self, key):
57
"""Check if this index has one key.
59
If it's possible to check for multiple keys at once through
60
calling get_parent_map that should be faster.
62
return (key in self.get_parent_map([key]))
65
def _missing_keys_from_parent_map(self, keys):
66
return set(keys) - set(self.get_parent_map(keys))
55
69
class GraphIndexBuilder(object):
56
70
"""A builder that can build a GraphIndex.
58
72
The resulting graph has the structure:
60
74
_SIGNATURE OPTIONS NODES NEWLINE
61
75
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
62
76
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
94
110
if not element or _whitespace_re.search(element) is not None:
95
111
raise errors.BadIndexKey(element)
97
def add_node(self, key, value, references=()):
98
"""Add a node to the index.
100
:param key: The key. keys are non-empty tuples containing
101
as many whitespace-free utf8 bytestrings as the key length
102
defined for this index.
103
:param references: An iterable of iterables of keys. Each is a
104
reference to another key.
105
:param value: The value to associate with the key. It may be any
106
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.
108
191
self._check_key(key)
109
192
if _newline_null_re.search(value) is not None:
111
194
if len(references) != self.reference_lists:
112
195
raise errors.BadIndexValue(references)
197
absent_references = []
114
198
for reference_list in references:
115
199
for reference in reference_list:
116
self._check_key(reference)
200
# If reference *is* in self._nodes, then we know it has already
117
202
if reference not in self._nodes:
118
self._nodes[reference] = ('a', (), '')
203
self._check_key(reference)
204
absent_references.append(reference)
119
205
node_refs.append(tuple(reference_list))
120
if key in self._nodes and self._nodes[key][0] == '':
206
return tuple(node_refs), absent_references
208
def add_node(self, key, value, references=()):
209
"""Add a node to the index.
211
:param key: The key. keys are non-empty tuples containing
212
as many whitespace-free utf8 bytestrings as the key length
213
defined for this index.
214
:param references: An iterable of iterables of keys. Each is a
215
reference to another key.
216
:param value: The value to associate with the key. It may be any
217
bytes as long as it does not contain \0 or \n.
220
absent_references) = self._check_key_ref_value(key, references, value)
221
if key in self._nodes and self._nodes[key][0] != 'a':
121
222
raise errors.BadIndexDuplicateKey(key, self)
122
self._nodes[key] = ('', tuple(node_refs), value)
223
for reference in absent_references:
224
# There may be duplicates, but I don't think it is worth worrying
226
self._nodes[reference] = ('a', (), '')
227
self._nodes[key] = ('', node_refs, value)
123
228
self._keys.add(key)
124
if self._key_length > 1:
125
key_dict = self._nodes_by_key
126
if self.reference_lists:
127
key_value = key, value, tuple(node_refs)
129
key_value = key, value
130
# possibly should do this on-demand, but it seems likely it is
132
# For a key of (foo, bar, baz) create
133
# _nodes_by_key[foo][bar][baz] = key_value
134
for subkey in key[:-1]:
135
key_dict = key_dict.setdefault(subkey, {})
136
key_dict[key[-1]] = key_value
229
if self._nodes_by_key is not None and self._key_length > 1:
230
self._update_nodes_by_key(key, value, node_refs)
138
232
def finish(self):
139
233
lines = [_SIGNATURE]
219
313
raise errors.BzrError('Failed index creation. Internal error:'
220
314
' mismatched output length and expected length: %d %d' %
221
315
(len(result.getvalue()), expected_bytes))
222
return StringIO(''.join(lines))
318
def set_optimize(self, for_size=True):
319
"""Change how the builder tries to optimize the result.
321
:param for_size: Tell the builder to try and make the index as small as
325
# GraphIndexBuilder itself doesn't pay attention to the flag yet, but
327
self._optimize_for_size = for_size
225
330
class GraphIndex(object):
226
331
"""An index for data with embedded graphs.
228
333
The index maps keys to a list of key reference lists, and a value.
229
334
Each node has the same number of key reference lists. Each key reference
230
335
list can be empty or an arbitrary length. The value is an opaque NULL
231
terminated string without any newlines. The storage of the index is
336
terminated string without any newlines. The storage of the index is
232
337
hidden in the interface: keys and key references are always tuples of
233
338
bytestrings, never the internal representation (e.g. dictionary offsets).
284
391
def __ne__(self, other):
285
392
return not self.__eq__(other)
287
def _buffer_all(self):
395
return "%s(%r)" % (self.__class__.__name__,
396
self._transport.abspath(self._name))
398
def _buffer_all(self, stream=None):
288
399
"""Buffer all the index data.
290
401
Mutates self._nodes and self.keys_by_offset.
403
if self._nodes is not None:
404
# We already did this
292
406
if 'index' in debug.debug_flags:
293
407
mutter('Reading entire index %s', self._transport.abspath(self._name))
294
stream = self._transport.get(self._name)
409
stream = self._transport.get(self._name)
295
410
self._read_prefix(stream)
296
411
self._expected_elements = 3 + self._key_length
315
430
node_value = value
316
431
self._nodes[key] = node_value
317
if self._key_length > 1:
318
subkey = list(reversed(key[:-1]))
319
key_dict = self._nodes_by_key
320
if self.node_ref_lists:
321
key_value = key, node_value[0], node_value[1]
323
key_value = key, node_value
324
# possibly should do this on-demand, but it seems likely it is
326
# For a key of (foo, bar, baz) create
327
# _nodes_by_key[foo][bar][baz] = key_value
328
for subkey in key[:-1]:
329
key_dict = key_dict.setdefault(subkey, {})
330
key_dict[key[-1]] = key_value
331
432
# cache the keys for quick set intersections
332
433
self._keys = set(self._nodes)
333
434
if trailers != 1:
334
435
# there must be one line - the empty trailer line.
335
436
raise errors.BadIndexData(self)
438
def external_references(self, ref_list_num):
439
"""Return references that are not present in this index.
442
if ref_list_num + 1 > self.node_ref_lists:
443
raise ValueError('No ref list %d, index has %d ref lists'
444
% (ref_list_num, self.node_ref_lists))
446
for key, (value, ref_lists) in self._nodes.iteritems():
447
ref_list = ref_lists[ref_list_num]
448
refs.update(ref_list)
449
return refs - self._keys
451
def _get_nodes_by_key(self):
452
if self._nodes_by_key is None:
454
if self.node_ref_lists:
455
for key, (value, references) in self._nodes.iteritems():
456
key_dict = nodes_by_key
457
for subkey in key[:-1]:
458
key_dict = key_dict.setdefault(subkey, {})
459
key_dict[key[-1]] = key, value, references
461
for key, value in self._nodes.iteritems():
462
key_dict = nodes_by_key
463
for subkey in key[:-1]:
464
key_dict = key_dict.setdefault(subkey, {})
465
key_dict[key[-1]] = key, value
466
self._nodes_by_key = nodes_by_key
467
return self._nodes_by_key
337
469
def iter_all_entries(self):
338
470
"""Iterate over all keys within the index.
464
596
keys supplied. No additional keys will be returned, and every
465
597
key supplied that is in the index will be returned.
467
# PERFORMANCE TODO: parse and bisect all remaining data at some
468
# threshold of total-index processing/get calling layers that expect to
469
# read the entire index to use the iter_all_entries method instead.
473
602
if self._size is None and self._nodes is None:
474
603
self._buffer_all()
605
# We fit about 20 keys per minimum-read (4K), so if we are looking for
606
# more than 1/20th of the index its likely (assuming homogenous key
607
# spread) that we'll read the entire index. If we're going to do that,
608
# buffer the whole thing. A better analysis might take key spread into
609
# account - but B+Tree indices are better anyway.
610
# We could look at all data read, and use a threshold there, which will
611
# trigger on ancestry walks, but that is not yet fully mapped out.
612
if self._nodes is None and len(keys) * 20 > self.key_count():
475
614
if self._nodes is not None:
476
615
return self._iter_entries_from_total_buffer(keys)
619
759
if self._bisect_nodes is None:
620
760
readv_ranges.append(_HEADER_READV)
621
761
self._read_and_parse(readv_ranges)
763
if self._nodes is not None:
764
# _read_and_parse triggered a _buffer_all because we requested the
766
for location, key in location_keys:
767
if key not in self._nodes: # not present
768
result.append(((location, key), False))
769
elif self.node_ref_lists:
770
value, refs = self._nodes[key]
771
result.append(((location, key),
772
(self, key, value, refs)))
774
result.append(((location, key),
775
(self, key, self._nodes[key])))
622
777
# generate results:
623
778
# - figure out <, >, missing, present
624
779
# - result present references so we can return them.
626
780
# keys that we cannot answer until we resolve references
627
781
pending_references = []
628
782
pending_locations = set()
679
833
readv_ranges.append((location, length))
680
834
self._read_and_parse(readv_ranges)
835
if self._nodes is not None:
836
# The _read_and_parse triggered a _buffer_all, grab the data and
838
for location, key in pending_references:
839
value, refs = self._nodes[key]
840
result.append(((location, key), (self, key, value, refs)))
681
842
for location, key in pending_references:
682
843
# answer key references we had to look-up-late.
683
index = self._parsed_key_index(key)
684
844
value, refs = self._bisect_nodes[key]
685
845
result.append(((location, key), (self, key,
686
846
value, self._resolve_references(refs))))
838
999
trim_end = data.rfind('\n') + 1
840
1001
trim_end = data.rfind('\n', None, trim_end) + 1
841
assert trim_end != 0, 'no \n was present'
1002
if not (trim_end != 0):
1003
raise AssertionError('no \n was present')
842
1004
# print 'removing end', offset, trim_end, repr(data[trim_end:])
843
1005
# adjust offset and data to the parseable data.
844
1006
trimmed_data = data[trim_start:trim_end]
845
assert trimmed_data, 'read unneeded data [%d:%d] from [%d:%d]' % (
846
trim_start, trim_end, offset, offset + len(data))
1007
if not (trimmed_data):
1008
raise AssertionError('read unneeded data [%d:%d] from [%d:%d]'
1009
% (trim_start, trim_end, offset, offset + len(data)))
848
1011
offset += trim_start
849
1012
# print "parsing", repr(trimmed_data)
868
1031
# must be at the end
870
assert self._size == pos + 1, "%s %s" % (self._size, pos)
1033
if not (self._size == pos + 1):
1034
raise AssertionError("%s %s" % (self._size, pos))
873
1037
elements = line.split('\0')
874
1038
if len(elements) != self._expected_elements:
875
1039
raise errors.BadIndexData(self)
877
key = tuple(elements[:self._key_length])
1040
# keys are tuples. Each element is a string that may occur many
1041
# times, so we intern them to save space. AB, RC, 200807
1042
key = tuple([intern(element) for element in elements[:self._key_length]])
878
1043
if first_key is None:
880
1045
absent, references, value = elements[-3:]
952
1117
:param readv_ranges: A prepared readv range list.
955
readv_data = self._transport.readv(self._name, readv_ranges, True,
958
for offset, data in readv_data:
959
if self._bisect_nodes is None:
960
# this must be the start
962
offset, data = self._parse_header_from_bytes(data)
963
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
964
self._parse_region(offset, data)
1119
if not readv_ranges:
1121
if self._nodes is None and self._bytes_read * 2 >= self._size:
1122
# We've already read more than 50% of the file and we are about to
1123
# request more data, just _buffer_all() and be done
1127
readv_data = self._transport.readv(self._name, readv_ranges, True,
1130
for offset, data in readv_data:
1131
self._bytes_read += len(data)
1132
if offset == 0 and len(data) == self._size:
1133
# We read the whole range, most likely because the
1134
# Transport upcast our readv ranges into one long request
1135
# for enough total data to grab the whole index.
1136
self._buffer_all(StringIO(data))
1138
if self._bisect_nodes is None:
1139
# this must be the start
1140
if not (offset == 0):
1141
raise AssertionError()
1142
offset, data = self._parse_header_from_bytes(data)
1143
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1144
self._parse_region(offset, data)
966
1146
def _signature(self):
967
1147
"""The file signature for this index type."""
1101
1297
seen_keys = set()
1102
for index in self._indices:
1103
for node in index.iter_entries_prefix(keys):
1104
if node[1] in seen_keys:
1106
seen_keys.add(node[1])
1300
for index in self._indices:
1301
for node in index.iter_entries_prefix(keys):
1302
if node[1] in seen_keys:
1304
seen_keys.add(node[1])
1307
except errors.NoSuchFile:
1308
self._reload_or_raise()
1109
1310
def key_count(self):
1110
1311
"""Return an estimate of the number of keys in this index.
1112
1313
For CombinedGraphIndex this is approximated by the sum of the keys of
1113
1314
the child indices. As child indices may have duplicate keys this can
1114
1315
have a maximum error of the number of child indices * largest number of
1115
1316
keys in any index.
1117
return sum((index.key_count() for index in self._indices), 0)
1320
return sum((index.key_count() for index in self._indices), 0)
1321
except errors.NoSuchFile:
1322
self._reload_or_raise()
1324
missing_keys = _missing_keys_from_parent_map
1326
def _reload_or_raise(self):
1327
"""We just got a NoSuchFile exception.
1329
Try to reload the indices, if it fails, just raise the current
1332
if self._reload_func is None:
1334
exc_type, exc_value, exc_traceback = sys.exc_info()
1335
trace.mutter('Trying to reload after getting exception: %s',
1337
if not self._reload_func():
1338
# We tried to reload, but nothing changed, so we fail anyway
1339
trace.mutter('_reload_func indicated nothing has changed.'
1340
' Raising original exception.')
1341
raise exc_type, exc_value, exc_traceback
1119
1343
def validate(self):
1120
1344
"""Validate that everything in the index can be accessed."""
1121
for index in self._indices:
1347
for index in self._indices:
1350
except errors.NoSuchFile:
1351
self._reload_or_raise()
1125
1354
class InMemoryGraphIndex(GraphIndexBuilder):