32
32
from bzrlib.lazy_import import lazy_import
33
33
lazy_import(globals(), """
34
from bzrlib import trace
35
from bzrlib.bisect_multi import bisect_multi_bytes
36
from bzrlib.revision import NULL_REVISION
37
from bzrlib.trace import mutter
36
revision as _mod_revision,
39
40
from bzrlib import (
44
from bzrlib.static_tuple import StaticTuple
44
46
_HEADER_READV = (0, 200)
45
47
_OPTION_KEY_ELEMENTS = "key_elements="
92
94
:param key_elements: The number of bytestrings in each key.
94
96
self.reference_lists = reference_lists
96
97
# A dict of {key: (absent, ref_lists, value)}
99
# Keys that are referenced but not actually present in this index
100
self._absent_keys = set()
98
101
self._nodes_by_key = None
99
102
self._key_length = key_elements
100
103
self._optimize_for_size = False
165
168
key_dict = self._nodes_by_key
166
169
if self.reference_lists:
167
key_value = key, value, node_refs
170
key_value = StaticTuple(key, value, node_refs)
169
key_value = key, value
172
key_value = StaticTuple(key, value)
170
173
for subkey in key[:-1]:
171
174
key_dict = key_dict.setdefault(subkey, {})
172
175
key_dict[key[-1]] = key_value
202
206
if reference not in self._nodes:
203
207
self._check_key(reference)
204
208
absent_references.append(reference)
205
node_refs.append(tuple(reference_list))
206
return tuple(node_refs), absent_references
209
reference_list = as_st([as_st(ref).intern()
210
for ref in reference_list])
211
node_refs.append(reference_list)
212
return as_st(node_refs), absent_references
208
214
def add_node(self, key, value, references=()):
209
215
"""Add a node to the index.
224
230
# There may be duplicates, but I don't think it is worth worrying
226
232
self._nodes[reference] = ('a', (), '')
233
self._absent_keys.update(absent_references)
234
self._absent_keys.discard(key)
227
235
self._nodes[key] = ('', node_refs, value)
229
236
if self._nodes_by_key is not None and self._key_length > 1:
230
237
self._update_nodes_by_key(key, value, node_refs)
239
def clear_cache(self):
240
"""See GraphIndex.clear_cache()
242
This is a no-op, but we need the api to conform to a generic 'Index'
232
246
def finish(self):
233
247
lines = [_SIGNATURE]
234
248
lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
235
249
lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
236
lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
250
key_count = len(self._nodes) - len(self._absent_keys)
251
lines.append(_OPTION_LEN + str(key_count) + '\n')
237
252
prefix_length = sum(len(x) for x in lines)
238
253
# references are byte offsets. To avoid having to do nasty
239
254
# polynomial work to resolve offsets (references to later in the
368
383
suitable for production use. :XXX
371
def __init__(self, transport, name, size):
386
def __init__(self, transport, name, size, unlimited_cache=False, offset=0):
372
387
"""Open an index called name on transport.
374
389
:param transport: A bzrlib.transport.Transport.
427
445
# We already did this
429
447
if 'index' in debug.debug_flags:
430
mutter('Reading entire index %s', self._transport.abspath(self._name))
448
trace.mutter('Reading entire index %s',
449
self._transport.abspath(self._name))
431
450
if stream is None:
432
451
stream = self._transport.get(self._name)
452
if self._base_offset != 0:
453
# This is wasteful, but it is better than dealing with
454
# adjusting all the offsets, etc.
455
stream = StringIO(stream.read()[self._base_offset:])
433
456
self._read_prefix(stream)
434
457
self._expected_elements = 3 + self._key_length
453
478
node_value = value
454
479
self._nodes[key] = node_value
455
480
# cache the keys for quick set intersections
456
self._keys = set(self._nodes)
457
481
if trailers != 1:
458
482
# there must be one line - the empty trailer line.
459
483
raise errors.BadIndexData(self)
485
def clear_cache(self):
486
"""Clear out any cached/memoized values.
488
This can be called at any time, but generally it is used when we have
489
extracted some information, but don't expect to be requesting any more
461
493
def external_references(self, ref_list_num):
462
494
"""Return references that are not present in this index.
466
498
raise ValueError('No ref list %d, index has %d ref lists'
467
499
% (ref_list_num, self.node_ref_lists))
469
for key, (value, ref_lists) in self._nodes.iteritems():
502
for key, (value, ref_lists) in nodes.iteritems():
470
503
ref_list = ref_lists[ref_list_num]
471
refs.update(ref_list)
472
return refs - self._keys
504
refs.update([ref for ref in ref_list if ref not in nodes])
474
507
def _get_nodes_by_key(self):
475
508
if self._nodes_by_key is None:
603
636
def _iter_entries_from_total_buffer(self, keys):
604
637
"""Iterate over keys when the entire index is parsed."""
605
keys = keys.intersection(self._keys)
638
# Note: See the note in BTreeBuilder.iter_entries for why we don't use
639
# .intersection() here
641
keys = [key for key in keys if key in nodes]
606
642
if self.node_ref_lists:
608
value, node_refs = self._nodes[key]
644
value, node_refs = nodes[key]
609
645
yield self, key, value, node_refs
612
yield self, key, self._nodes[key]
648
yield self, key, nodes[key]
614
650
def iter_entries(self, keys):
615
651
"""Iterate over keys within the index.
1164
1200
self._buffer_all()
1203
base_offset = self._base_offset
1204
if base_offset != 0:
1205
# Rewrite the ranges for the offset
1206
readv_ranges = [(start+base_offset, size)
1207
for start, size in readv_ranges]
1167
1208
readv_data = self._transport.readv(self._name, readv_ranges, True,
1209
self._size + self._base_offset)
1170
1211
for offset, data in readv_data:
1212
offset -= base_offset
1171
1213
self._bytes_read += len(data)
1215
# transport.readv() expanded to extra data which isn't part of
1217
data = data[-offset:]
1172
1219
if offset == 0 and len(data) == self._size:
1173
1220
# We read the whole range, most likely because the
1174
1221
# Transport upcast our readv ranges into one long request
1203
1250
Queries against the combined index will be made against the first index,
1204
and then the second and so on. The order of index's can thus influence
1251
and then the second and so on. The order of indices can thus influence
1205
1252
performance significantly. For example, if one index is on local disk and a
1206
1253
second on a remote server, the local disk index should be before the other
1207
1254
in the index list.
1256
Also, queries tend to need results from the same indices as previous
1257
queries. So the indices will be reordered after every query to put the
1258
indices that had the result(s) of that query first (while otherwise
1259
preserving the relative ordering).
1210
1262
def __init__(self, indices, reload_func=None):
1218
1270
self._indices = indices
1219
1271
self._reload_func = reload_func
1272
# Sibling indices are other CombinedGraphIndex that we should call
1273
# _move_to_front_by_name on when we auto-reorder ourself.
1274
self._sibling_indices = []
1275
# A list of names that corresponds to the instances in self._indices,
1276
# so _index_names[0] is always the name for _indices[0], etc. Sibling
1277
# indices must all use the same set of names as each other.
1278
self._index_names = [None] * len(self._indices)
1221
1280
def __repr__(self):
1222
1281
return "%s(%s)" % (
1223
1282
self.__class__.__name__,
1224
1283
', '.join(map(repr, self._indices)))
1285
def clear_cache(self):
1286
"""See GraphIndex.clear_cache()"""
1287
for index in self._indices:
1226
1290
def get_parent_map(self, keys):
1227
1291
"""See graph.StackedParentsProvider.get_parent_map"""
1228
1292
search_keys = set(keys)
1229
if NULL_REVISION in search_keys:
1230
search_keys.discard(NULL_REVISION)
1231
found_parents = {NULL_REVISION:[]}
1293
if _mod_revision.NULL_REVISION in search_keys:
1294
search_keys.discard(_mod_revision.NULL_REVISION)
1295
found_parents = {_mod_revision.NULL_REVISION:[]}
1233
1297
found_parents = {}
1234
1298
for index, key, value, refs in self.iter_entries(search_keys):
1235
1299
parents = refs[0]
1236
1300
if not parents:
1237
parents = (NULL_REVISION,)
1301
parents = (_mod_revision.NULL_REVISION,)
1238
1302
found_parents[key] = parents
1239
1303
return found_parents
1241
1305
has_key = _has_key_from_parent_map
1243
def insert_index(self, pos, index):
1307
def insert_index(self, pos, index, name=None):
1244
1308
"""Insert a new index in the list of indices to query.
1246
1310
:param pos: The position to insert the index.
1247
1311
:param index: The index to insert.
1312
:param name: a name for this index, e.g. a pack name. These names can
1313
be used to reflect index reorderings to related CombinedGraphIndex
1314
instances that use the same names. (see set_sibling_indices)
1249
1316
self._indices.insert(pos, index)
1317
self._index_names.insert(pos, name)
1251
1319
def iter_all_entries(self):
1252
1320
"""Iterate over all keys within the index
1277
1345
value and are only reported once.
1279
1347
:param keys: An iterable providing the keys to be retrieved.
1280
:return: An iterable of (index, key, reference_lists, value). There is no
1281
defined order for the result iteration - it will be in the most
1348
:return: An iterable of (index, key, reference_lists, value). There is
1349
no defined order for the result iteration - it will be in the most
1282
1350
efficient order for the index.
1284
1352
keys = set(keys)
1287
1356
for index in self._indices:
1290
1360
for node in index.iter_entries(keys):
1291
1361
keys.remove(node[1])
1365
hit_indices.append(index)
1294
1367
except errors.NoSuchFile:
1295
1368
self._reload_or_raise()
1369
self._move_to_front(hit_indices)
1297
1371
def iter_entries_prefix(self, keys):
1298
1372
"""Iterate over keys within the index using prefix matching.
1320
1394
seen_keys = set()
1323
1398
for index in self._indices:
1324
1400
for node in index.iter_entries_prefix(keys):
1325
1401
if node[1] in seen_keys:
1327
1403
seen_keys.add(node[1])
1407
hit_indices.append(index)
1330
1409
except errors.NoSuchFile:
1331
1410
self._reload_or_raise()
1411
self._move_to_front(hit_indices)
1413
def _move_to_front(self, hit_indices):
1414
"""Rearrange self._indices so that hit_indices are first.
1416
Order is maintained as much as possible, e.g. the first unhit index
1417
will be the first index in _indices after the hit_indices, and the
1418
hit_indices will be present in exactly the order they are passed to
1421
_move_to_front propagates to all objects in self._sibling_indices by
1422
calling _move_to_front_by_name.
1424
if self._indices[:len(hit_indices)] == hit_indices:
1425
# The 'hit_indices' are already at the front (and in the same
1426
# order), no need to re-order
1428
hit_names = self._move_to_front_by_index(hit_indices)
1429
for sibling_idx in self._sibling_indices:
1430
sibling_idx._move_to_front_by_name(hit_names)
1432
def _move_to_front_by_index(self, hit_indices):
1433
"""Core logic for _move_to_front.
1435
Returns a list of names corresponding to the hit_indices param.
1437
indices_info = zip(self._index_names, self._indices)
1438
if 'index' in debug.debug_flags:
1439
trace.mutter('CombinedGraphIndex reordering: currently %r, '
1440
'promoting %r', indices_info, hit_indices)
1443
new_hit_indices = []
1446
for offset, (name, idx) in enumerate(indices_info):
1447
if idx in hit_indices:
1448
hit_names.append(name)
1449
new_hit_indices.append(idx)
1450
if len(new_hit_indices) == len(hit_indices):
1451
# We've found all of the hit entries, everything else is
1453
unhit_names.extend(self._index_names[offset+1:])
1454
unhit_indices.extend(self._indices[offset+1:])
1457
unhit_names.append(name)
1458
unhit_indices.append(idx)
1460
self._indices = new_hit_indices + unhit_indices
1461
self._index_names = hit_names + unhit_names
1462
if 'index' in debug.debug_flags:
1463
trace.mutter('CombinedGraphIndex reordered: %r', self._indices)
1466
def _move_to_front_by_name(self, hit_names):
1467
"""Moves indices named by 'hit_names' to front of the search order, as
1468
described in _move_to_front.
1470
# Translate names to index instances, and then call
1471
# _move_to_front_by_index.
1472
indices_info = zip(self._index_names, self._indices)
1474
for name, idx in indices_info:
1475
if name in hit_names:
1476
hit_indices.append(idx)
1477
self._move_to_front_by_index(hit_indices)
1333
1479
def find_ancestry(self, keys, ref_list_num):
1334
1480
"""Find the complete ancestry for the given set of keys.
1484
1636
defined order for the result iteration - it will be in the most
1485
1637
efficient order for the index (keys iteration order in this case).
1639
# Note: See BTreeBuilder.iter_entries for an explanation of why we
1640
# aren't using set().intersection() here
1642
keys = [key for key in keys if key in nodes]
1488
1643
if self.reference_lists:
1489
for key in keys.intersection(self._keys):
1490
node = self._nodes[key]
1491
1646
if not node[0]:
1492
1647
yield self, key, node[2], node[1]
1494
for key in keys.intersection(self._keys):
1495
node = self._nodes[key]
1496
1651
if not node[0]:
1497
1652
yield self, key, node[2]