112
88
if not element or _whitespace_re.search(element) is not None:
113
89
raise errors.BadIndexKey(element)
115
def _external_references(self):
116
"""Return references that are not present in this index.
120
# TODO: JAM 2008-11-21 This makes an assumption about how the reference
121
# lists are used. It is currently correct for pack-0.92 through
122
# 1.9, which use the node references (3rd column) second
123
# reference list as the compression parent. Perhaps this should
124
# be moved into something higher up the stack, since it
125
# makes assumptions about how the index is used.
126
if self.reference_lists > 1:
127
for node in self.iter_all_entries():
129
refs.update(node[3][1])
132
# If reference_lists == 0 there can be no external references, and
133
# if reference_lists == 1, then there isn't a place to store the
137
def _get_nodes_by_key(self):
138
if self._nodes_by_key is None:
140
if self.reference_lists:
141
for key, (absent, references, value) in self._nodes.iteritems():
144
key_dict = nodes_by_key
145
for subkey in key[:-1]:
146
key_dict = key_dict.setdefault(subkey, {})
147
key_dict[key[-1]] = key, value, references
149
for key, (absent, references, value) in self._nodes.iteritems():
152
key_dict = nodes_by_key
153
for subkey in key[:-1]:
154
key_dict = key_dict.setdefault(subkey, {})
155
key_dict[key[-1]] = key, value
156
self._nodes_by_key = nodes_by_key
157
return self._nodes_by_key
159
def _update_nodes_by_key(self, key, value, node_refs):
160
"""Update the _nodes_by_key dict with a new key.
162
For a key of (foo, bar, baz) create
163
_nodes_by_key[foo][bar][baz] = key_value
165
if self._nodes_by_key is None:
167
key_dict = self._nodes_by_key
168
if self.reference_lists:
169
key_value = StaticTuple(key, value, node_refs)
171
key_value = StaticTuple(key, value)
172
for subkey in key[:-1]:
173
key_dict = key_dict.setdefault(subkey, {})
174
key_dict[key[-1]] = key_value
176
def _check_key_ref_value(self, key, references, value):
177
"""Check that 'key' and 'references' are all valid.
179
:param key: A key tuple. Must conform to the key interface (be a tuple,
180
be of the right length, not have any whitespace or nulls in any key
182
:param references: An iterable of reference lists. Something like
183
[[(ref, key)], [(ref, key), (other, key)]]
184
:param value: The value associate with this key. Must not contain
185
newlines or null characters.
186
:return: (node_refs, absent_references)
187
node_refs basically a packed form of 'references' where all
189
absent_references reference keys that are not in self._nodes.
190
This may contain duplicates if the same key is
191
referenced in multiple lists.
193
as_st = StaticTuple.from_sequence
91
def add_node(self, key, value, references=()):
92
"""Add a node to the index.
94
:param key: The key. keys are non-empty tuples containing
95
as many whitespace-free utf8 bytestrings as the key length
96
defined for this index.
97
:param references: An iterable of iterables of keys. Each is a
98
reference to another key.
99
:param value: The value to associate with the key. It may be any
100
bytes as long as it does not contain \0 or \n.
194
102
self._check_key(key)
195
103
if _newline_null_re.search(value) is not None:
196
104
raise errors.BadIndexValue(value)
197
105
if len(references) != self.reference_lists:
198
106
raise errors.BadIndexValue(references)
200
absent_references = []
201
108
for reference_list in references:
202
109
for reference in reference_list:
203
# If reference *is* in self._nodes, then we know it has already
110
self._check_key(reference)
205
111
if reference not in self._nodes:
206
self._check_key(reference)
207
absent_references.append(reference)
208
reference_list = as_st([as_st(ref).intern()
209
for ref in reference_list])
210
node_refs.append(reference_list)
211
return as_st(node_refs), absent_references
213
def add_node(self, key, value, references=()):
214
"""Add a node to the index.
216
:param key: The key. keys are non-empty tuples containing
217
as many whitespace-free utf8 bytestrings as the key length
218
defined for this index.
219
:param references: An iterable of iterables of keys. Each is a
220
reference to another key.
221
:param value: The value to associate with the key. It may be any
222
bytes as long as it does not contain \0 or \n.
225
absent_references) = self._check_key_ref_value(key, references, value)
226
if key in self._nodes and self._nodes[key][0] != 'a':
112
self._nodes[reference] = ('a', (), '')
113
node_refs.append(tuple(reference_list))
114
if key in self._nodes and self._nodes[key][0] == '':
227
115
raise errors.BadIndexDuplicateKey(key, self)
228
for reference in absent_references:
229
# There may be duplicates, but I don't think it is worth worrying
231
self._nodes[reference] = ('a', (), '')
232
self._absent_keys.update(absent_references)
233
self._absent_keys.discard(key)
234
self._nodes[key] = ('', node_refs, value)
235
if self._nodes_by_key is not None and self._key_length > 1:
236
self._update_nodes_by_key(key, value, node_refs)
238
def clear_cache(self):
239
"""See GraphIndex.clear_cache()
241
This is a no-op, but we need the api to conform to a generic 'Index'
116
self._nodes[key] = ('', tuple(node_refs), value)
118
if self._key_length > 1:
119
key_dict = self._nodes_by_key
120
if self.reference_lists:
121
key_value = key, value, tuple(node_refs)
123
key_value = key, value
124
# possibly should do this on-demand, but it seems likely it is
126
# For a key of (foo, bar, baz) create
127
# _nodes_by_key[foo][bar][baz] = key_value
128
for subkey in key[:-1]:
129
key_dict = key_dict.setdefault(subkey, {})
130
key_dict[key[-1]] = key_value
245
132
def finish(self):
246
133
lines = [_SIGNATURE]
247
134
lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
248
135
lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
249
key_count = len(self._nodes) - len(self._absent_keys)
250
lines.append(_OPTION_LEN + str(key_count) + '\n')
136
lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
251
137
prefix_length = sum(len(x) for x in lines)
252
138
# references are byte offsets. To avoid having to do nasty
253
# polynomial work to resolve offsets (references to later in the
139
# polynomial work to resolve offsets (references to later in the
254
140
# file cannot be determined until all the inbetween references have
255
141
# been calculated too) we pad the offsets with 0's to make them be
256
142
# of consistent length. Using binary offsets would break the trivial
327
213
raise errors.BzrError('Failed index creation. Internal error:'
328
214
' mismatched output length and expected length: %d %d' %
329
215
(len(result.getvalue()), expected_bytes))
332
def set_optimize(self, for_size=None, combine_backing_indices=None):
333
"""Change how the builder tries to optimize the result.
335
:param for_size: Tell the builder to try and make the index as small as
337
:param combine_backing_indices: If the builder spills to disk to save
338
memory, should the on-disk indices be combined. Set to True if you
339
are going to be probing the index, but to False if you are not. (If
340
you are not querying, then the time spent combining is wasted.)
343
# GraphIndexBuilder itself doesn't pay attention to the flag yet, but
345
if for_size is not None:
346
self._optimize_for_size = for_size
347
if combine_backing_indices is not None:
348
self._combine_backing_indices = combine_backing_indices
350
def find_ancestry(self, keys, ref_list_num):
351
"""See CombinedGraphIndex.find_ancestry()"""
357
for _, key, value, ref_lists in self.iter_entries(pending):
358
parent_keys = ref_lists[ref_list_num]
359
parent_map[key] = parent_keys
360
next_pending.update([p for p in parent_keys if p not in
362
missing_keys.update(pending.difference(parent_map))
363
pending = next_pending
364
return parent_map, missing_keys
216
return StringIO(''.join(lines))
367
219
class GraphIndex(object):
368
220
"""An index for data with embedded graphs.
370
222
The index maps keys to a list of key reference lists, and a value.
371
223
Each node has the same number of key reference lists. Each key reference
372
224
list can be empty or an arbitrary length. The value is an opaque NULL
373
terminated string without any newlines. The storage of the index is
225
terminated string without any newlines. The storage of the index is
374
226
hidden in the interface: keys and key references are always tuples of
375
227
bytestrings, never the internal representation (e.g. dictionary offsets).
468
309
node_value = value
469
310
self._nodes[key] = node_value
311
if self._key_length > 1:
312
subkey = list(reversed(key[:-1]))
313
key_dict = self._nodes_by_key
314
if self.node_ref_lists:
315
key_value = key, node_value[0], node_value[1]
317
key_value = key, node_value
318
# possibly should do this on-demand, but it seems likely it is
320
# For a key of (foo, bar, baz) create
321
# _nodes_by_key[foo][bar][baz] = key_value
322
for subkey in key[:-1]:
323
key_dict = key_dict.setdefault(subkey, {})
324
key_dict[key[-1]] = key_value
470
325
# cache the keys for quick set intersections
326
self._keys = set(self._nodes)
471
327
if trailers != 1:
472
328
# there must be one line - the empty trailer line.
473
329
raise errors.BadIndexData(self)
475
def clear_cache(self):
476
"""Clear out any cached/memoized values.
478
This can be called at any time, but generally it is used when we have
479
extracted some information, but don't expect to be requesting any more
483
def external_references(self, ref_list_num):
484
"""Return references that are not present in this index.
487
if ref_list_num + 1 > self.node_ref_lists:
488
raise ValueError('No ref list %d, index has %d ref lists'
489
% (ref_list_num, self.node_ref_lists))
492
for key, (value, ref_lists) in nodes.iteritems():
493
ref_list = ref_lists[ref_list_num]
494
refs.update([ref for ref in ref_list if ref not in nodes])
497
def _get_nodes_by_key(self):
498
if self._nodes_by_key is None:
500
if self.node_ref_lists:
501
for key, (value, references) in self._nodes.iteritems():
502
key_dict = nodes_by_key
503
for subkey in key[:-1]:
504
key_dict = key_dict.setdefault(subkey, {})
505
key_dict[key[-1]] = key, value, references
507
for key, value in self._nodes.iteritems():
508
key_dict = nodes_by_key
509
for subkey in key[:-1]:
510
key_dict = key_dict.setdefault(subkey, {})
511
key_dict[key[-1]] = key, value
512
self._nodes_by_key = nodes_by_key
513
return self._nodes_by_key
515
331
def iter_all_entries(self):
516
332
"""Iterate over all keys within the index.
823
612
readv_ranges.append((location, length))
824
613
# read the header if needed
825
614
if self._bisect_nodes is None:
826
readv_ranges.append(_HEADER_READV)
615
readv_ranges.append((0, 200))
827
616
self._read_and_parse(readv_ranges)
829
if self._nodes is not None:
830
# _read_and_parse triggered a _buffer_all because we requested the
832
for location, key in location_keys:
833
if key not in self._nodes: # not present
834
result.append(((location, key), False))
835
elif self.node_ref_lists:
836
value, refs = self._nodes[key]
837
result.append(((location, key),
838
(self, key, value, refs)))
840
result.append(((location, key),
841
(self, key, self._nodes[key])))
843
617
# generate results:
844
618
# - figure out <, >, missing, present
845
619
# - result present references so we can return them.
846
621
# keys that we cannot answer until we resolve references
847
622
pending_references = []
848
623
pending_locations = set()
1178
942
self._parsed_key_map.insert(index + 1, new_key)
1180
944
def _read_and_parse(self, readv_ranges):
1181
"""Read the ranges and parse the resulting data.
945
"""Read the the ranges and parse the resulting data.
1183
947
:param readv_ranges: A prepared readv range list.
1185
if not readv_ranges:
1187
if self._nodes is None and self._bytes_read * 2 >= self._size:
1188
# We've already read more than 50% of the file and we are about to
1189
# request more data, just _buffer_all() and be done
1193
readv_data = self._transport.readv(self._name, readv_ranges, True,
1196
for offset, data in readv_data:
1197
self._bytes_read += len(data)
1198
if offset == 0 and len(data) == self._size:
1199
# We read the whole range, most likely because the
1200
# Transport upcast our readv ranges into one long request
1201
# for enough total data to grab the whole index.
1202
self._buffer_all(StringIO(data))
1204
if self._bisect_nodes is None:
1205
# this must be the start
1206
if not (offset == 0):
1207
raise AssertionError()
1208
offset, data = self._parse_header_from_bytes(data)
1209
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
1210
self._parse_region(offset, data)
950
readv_data = self._transport.readv(self._name, readv_ranges, True,
953
for offset, data in readv_data:
954
if self._bisect_nodes is None:
955
# this must be the start
957
offset, data = self._parse_header_from_bytes(data)
958
# print readv_ranges, "[%d:%d]" % (offset, offset + len(data))
959
self._parse_region(offset, data)
1212
961
def _signature(self):
1213
962
"""The file signature for this index type."""
1233
982
in the index list.
1236
def __init__(self, indices, reload_func=None):
985
def __init__(self, indices):
1237
986
"""Create a CombinedGraphIndex backed by indices.
1239
988
:param indices: An ordered list of indices to query for data.
1240
:param reload_func: A function to call if we find we are missing an
1241
index. Should have the form reload_func() => True/False to indicate
1242
if reloading actually changed anything.
1244
990
self._indices = indices
1245
self._reload_func = reload_func
1247
992
def __repr__(self):
1248
993
return "%s(%s)" % (
1249
994
self.__class__.__name__,
1250
995
', '.join(map(repr, self._indices)))
1252
def clear_cache(self):
1253
"""See GraphIndex.clear_cache()"""
1254
for index in self._indices:
1257
def get_parent_map(self, keys):
1258
"""See graph.StackedParentsProvider.get_parent_map"""
1259
search_keys = set(keys)
1260
if NULL_REVISION in search_keys:
1261
search_keys.discard(NULL_REVISION)
1262
found_parents = {NULL_REVISION:[]}
1265
for index, key, value, refs in self.iter_entries(search_keys):
1268
parents = (NULL_REVISION,)
1269
found_parents[key] = parents
1270
return found_parents
1272
has_key = _has_key_from_parent_map
1274
997
def insert_index(self, pos, index):
1275
998
"""Insert a new index in the list of indices to query.
1351
1064
seen_keys = set()
1354
for index in self._indices:
1355
for node in index.iter_entries_prefix(keys):
1356
if node[1] in seen_keys:
1358
seen_keys.add(node[1])
1361
except errors.NoSuchFile:
1362
self._reload_or_raise()
1364
def find_ancestry(self, keys, ref_list_num):
1365
"""Find the complete ancestry for the given set of keys.
1367
Note that this is a whole-ancestry request, so it should be used
1370
:param keys: An iterable of keys to look for
1371
:param ref_list_num: The reference list which references the parents
1373
:return: (parent_map, missing_keys)
1375
missing_keys = set()
1377
keys_to_lookup = set(keys)
1379
while keys_to_lookup:
1380
# keys that *all* indexes claim are missing, stop searching them
1382
all_index_missing = None
1383
# print 'gen\tidx\tsub\tn_keys\tn_pmap\tn_miss'
1384
# print '%4d\t\t\t%4d\t%5d\t%5d' % (generation, len(keys_to_lookup),
1386
# len(missing_keys))
1387
for index_idx, index in enumerate(self._indices):
1388
# TODO: we should probably be doing something with
1389
# 'missing_keys' since we've already determined that
1390
# those revisions have not been found anywhere
1391
index_missing_keys = set()
1392
# Find all of the ancestry we can from this index
1393
# keep looking until the search_keys set is empty, which means
1394
# things we didn't find should be in index_missing_keys
1395
search_keys = keys_to_lookup
1397
# print ' \t%2d\t\t%4d\t%5d\t%5d' % (
1398
# index_idx, len(search_keys),
1399
# len(parent_map), len(index_missing_keys))
1402
# TODO: ref_list_num should really be a parameter, since
1403
# CombinedGraphIndex does not know what the ref lists
1405
search_keys = index._find_ancestors(search_keys,
1406
ref_list_num, parent_map, index_missing_keys)
1407
# print ' \t \t%2d\t%4d\t%5d\t%5d' % (
1408
# sub_generation, len(search_keys),
1409
# len(parent_map), len(index_missing_keys))
1410
# Now set whatever was missing to be searched in the next index
1411
keys_to_lookup = index_missing_keys
1412
if all_index_missing is None:
1413
all_index_missing = set(index_missing_keys)
1415
all_index_missing.intersection_update(index_missing_keys)
1416
if not keys_to_lookup:
1418
if all_index_missing is None:
1419
# There were no indexes, so all search keys are 'missing'
1420
missing_keys.update(keys_to_lookup)
1421
keys_to_lookup = None
1423
missing_keys.update(all_index_missing)
1424
keys_to_lookup.difference_update(all_index_missing)
1425
return parent_map, missing_keys
1065
for index in self._indices:
1066
for node in index.iter_entries_prefix(keys):
1067
if node[1] in seen_keys:
1069
seen_keys.add(node[1])
1427
1072
def key_count(self):
1428
1073
"""Return an estimate of the number of keys in this index.
1430
1075
For CombinedGraphIndex this is approximated by the sum of the keys of
1431
1076
the child indices. As child indices may have duplicate keys this can
1432
1077
have a maximum error of the number of child indices * largest number of
1433
1078
keys in any index.
1437
return sum((index.key_count() for index in self._indices), 0)
1438
except errors.NoSuchFile:
1439
self._reload_or_raise()
1441
missing_keys = _missing_keys_from_parent_map
1443
def _reload_or_raise(self):
1444
"""We just got a NoSuchFile exception.
1446
Try to reload the indices, if it fails, just raise the current
1449
if self._reload_func is None:
1451
exc_type, exc_value, exc_traceback = sys.exc_info()
1452
trace.mutter('Trying to reload after getting exception: %s',
1454
if not self._reload_func():
1455
# We tried to reload, but nothing changed, so we fail anyway
1456
trace.mutter('_reload_func indicated nothing has changed.'
1457
' Raising original exception.')
1458
raise exc_type, exc_value, exc_traceback
1080
return sum((index.key_count() for index in self._indices), 0)
1460
1082
def validate(self):
1461
1083
"""Validate that everything in the index can be accessed."""
1464
for index in self._indices:
1467
except errors.NoSuchFile:
1468
self._reload_or_raise()
1084
for index in self._indices:
1471
1088
class InMemoryGraphIndex(GraphIndexBuilder):