52
54
_newline_null_re = re.compile('[\n\0]')
57
def _has_key_from_parent_map(self, key):
58
"""Check if this index has one key.
60
If it's possible to check for multiple keys at once through
61
calling get_parent_map that should be faster.
63
return (key in self.get_parent_map([key]))
66
def _missing_keys_from_parent_map(self, keys):
67
return set(keys) - set(self.get_parent_map(keys))
55
70
class GraphIndexBuilder(object):
56
71
"""A builder that can build a GraphIndex.
58
The resulting graph has the structure:
60
_SIGNATURE OPTIONS NODES NEWLINE
61
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
62
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
64
NODE := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
65
KEY := Not-whitespace-utf8
67
REFERENCES := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
68
REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
69
REFERENCE := DIGITS ; digits is the byte offset in the index of the
71
VALUE := no-newline-no-null-bytes
73
The resulting graph has the structure::
75
_SIGNATURE OPTIONS NODES NEWLINE
76
_SIGNATURE := 'Bazaar Graph Index 1' NEWLINE
77
OPTIONS := 'node_ref_lists=' DIGITS NEWLINE
79
NODE := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
80
KEY := Not-whitespace-utf8
82
REFERENCES := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
83
REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
84
REFERENCE := DIGITS ; digits is the byte offset in the index of the
86
VALUE := no-newline-no-null-bytes
74
89
def __init__(self, reference_lists=0, key_elements=1):
278
336
(len(result.getvalue()), expected_bytes))
339
def set_optimize(self, for_size=None, combine_backing_indices=None):
340
"""Change how the builder tries to optimize the result.
342
:param for_size: Tell the builder to try and make the index as small as
344
:param combine_backing_indices: If the builder spills to disk to save
345
memory, should the on-disk indices be combined. Set to True if you
346
are going to be probing the index, but to False if you are not. (If
347
you are not querying, then the time spent combining is wasted.)
350
# GraphIndexBuilder itself doesn't pay attention to the flag yet, but
352
if for_size is not None:
353
self._optimize_for_size = for_size
354
if combine_backing_indices is not None:
355
self._combine_backing_indices = combine_backing_indices
357
def find_ancestry(self, keys, ref_list_num):
358
"""See CombinedGraphIndex.find_ancestry()"""
364
for _, key, value, ref_lists in self.iter_entries(pending):
365
parent_keys = ref_lists[ref_list_num]
366
parent_map[key] = parent_keys
367
next_pending.update([p for p in parent_keys if p not in
369
missing_keys.update(pending.difference(parent_map))
370
pending = next_pending
371
return parent_map, missing_keys
282
374
class GraphIndex(object):
283
375
"""An index for data with embedded graphs.
285
377
The index maps keys to a list of key reference lists, and a value.
286
378
Each node has the same number of key reference lists. Each key reference
287
379
list can be empty or an arbitrary length. The value is an opaque NULL
288
terminated string without any newlines. The storage of the index is
380
terminated string without any newlines. The storage of the index is
289
381
hidden in the interface: keys and key references are always tuples of
290
382
bytestrings, never the internal representation (e.g. dictionary offsets).
1096
1250
class CombinedGraphIndex(object):
1097
1251
"""A GraphIndex made up from smaller GraphIndices.
1099
1253
The backing indices must implement GraphIndex, and are presumed to be
1102
1256
Queries against the combined index will be made against the first index,
1103
and then the second and so on. The order of index's can thus influence
1257
and then the second and so on. The order of indices can thus influence
1104
1258
performance significantly. For example, if one index is on local disk and a
1105
1259
second on a remote server, the local disk index should be before the other
1106
1260
in the index list.
1262
Also, queries tend to need results from the same indices as previous
1263
queries. So the indices will be reordered after every query to put the
1264
indices that had the result(s) of that query first (while otherwise
1265
preserving the relative ordering).
1109
def __init__(self, indices):
1268
def __init__(self, indices, reload_func=None):
1110
1269
"""Create a CombinedGraphIndex backed by indices.
1112
1271
:param indices: An ordered list of indices to query for data.
1272
:param reload_func: A function to call if we find we are missing an
1273
index. Should have the form reload_func() => True/False to indicate
1274
if reloading actually changed anything.
1114
1276
self._indices = indices
1277
self._reload_func = reload_func
1278
# Sibling indices are other CombinedGraphIndex that we should call
1279
# _move_to_front_by_name on when we auto-reorder ourself.
1280
self._sibling_indices = []
1281
# A list of names that corresponds to the instances in self._indices,
1282
# so _index_names[0] is always the name for _indices[0], etc. Sibling
1283
# indices must all use the same set of names as each other.
1284
self._index_names = [None] * len(self._indices)
1116
1286
def __repr__(self):
1117
1287
return "%s(%s)" % (
1118
1288
self.__class__.__name__,
1119
1289
', '.join(map(repr, self._indices)))
1121
@symbol_versioning.deprecated_method(symbol_versioning.one_one)
1122
def get_parents(self, revision_ids):
1123
"""See graph._StackedParentsProvider.get_parents.
1125
This implementation thunks the graph.Graph.get_parents api across to
1128
:param revision_ids: An iterable of graph keys for this graph.
1129
:return: A list of parent details for each key in revision_ids.
1130
Each parent details will be one of:
1131
* None when the key was missing
1132
* (NULL_REVISION,) when the key has no parents.
1133
* (parent_key, parent_key...) otherwise.
1135
parent_map = self.get_parent_map(revision_ids)
1136
return [parent_map.get(r, None) for r in revision_ids]
1291
def clear_cache(self):
1292
"""See GraphIndex.clear_cache()"""
1293
for index in self._indices:
1138
1296
def get_parent_map(self, keys):
1139
"""See graph._StackedParentsProvider.get_parent_map"""
1297
"""See graph.StackedParentsProvider.get_parent_map"""
1140
1298
search_keys = set(keys)
1141
if NULL_REVISION in search_keys:
1142
search_keys.discard(NULL_REVISION)
1143
found_parents = {NULL_REVISION:[]}
1299
if _mod_revision.NULL_REVISION in search_keys:
1300
search_keys.discard(_mod_revision.NULL_REVISION)
1301
found_parents = {_mod_revision.NULL_REVISION:[]}
1145
1303
found_parents = {}
1146
1304
for index, key, value, refs in self.iter_entries(search_keys):
1147
1305
parents = refs[0]
1148
1306
if not parents:
1149
parents = (NULL_REVISION,)
1307
parents = (_mod_revision.NULL_REVISION,)
1150
1308
found_parents[key] = parents
1151
1309
return found_parents
1153
def insert_index(self, pos, index):
1311
has_key = _has_key_from_parent_map
1313
def insert_index(self, pos, index, name=None):
1154
1314
"""Insert a new index in the list of indices to query.
1156
1316
:param pos: The position to insert the index.
1157
1317
:param index: The index to insert.
1318
:param name: a name for this index, e.g. a pack name. These names can
1319
be used to reflect index reorderings to related CombinedGraphIndex
1320
instances that use the same names. (see set_sibling_indices)
1159
1322
self._indices.insert(pos, index)
1323
self._index_names.insert(pos, name)
1161
1325
def iter_all_entries(self):
1162
1326
"""Iterate over all keys within the index
1220
1400
seen_keys = set()
1221
for index in self._indices:
1222
for node in index.iter_entries_prefix(keys):
1223
if node[1] in seen_keys:
1225
seen_keys.add(node[1])
1404
for index in self._indices:
1406
for node in index.iter_entries_prefix(keys):
1407
if node[1] in seen_keys:
1409
seen_keys.add(node[1])
1413
hit_indices.append(index)
1415
except errors.NoSuchFile:
1416
self._reload_or_raise()
1417
self._move_to_front(hit_indices)
1419
def _move_to_front(self, hit_indices):
1420
"""Rearrange self._indices so that hit_indices are first.
1422
Order is maintained as much as possible, e.g. the first unhit index
1423
will be the first index in _indices after the hit_indices, and the
1424
hit_indices will be present in exactly the order they are passed to
1427
_move_to_front propagates to all objects in self._sibling_indices by
1428
calling _move_to_front_by_name.
1430
if self._indices[:len(hit_indices)] == hit_indices:
1431
# The 'hit_indices' are already at the front (and in the same
1432
# order), no need to re-order
1434
hit_names = self._move_to_front_by_index(hit_indices)
1435
for sibling_idx in self._sibling_indices:
1436
sibling_idx._move_to_front_by_name(hit_names)
1438
def _move_to_front_by_index(self, hit_indices):
1439
"""Core logic for _move_to_front.
1441
Returns a list of names corresponding to the hit_indices param.
1443
indices_info = zip(self._index_names, self._indices)
1444
if 'index' in debug.debug_flags:
1445
trace.mutter('CombinedGraphIndex reordering: currently %r, '
1446
'promoting %r', indices_info, hit_indices)
1449
new_hit_indices = []
1452
for offset, (name, idx) in enumerate(indices_info):
1453
if idx in hit_indices:
1454
hit_names.append(name)
1455
new_hit_indices.append(idx)
1456
if len(new_hit_indices) == len(hit_indices):
1457
# We've found all of the hit entries, everything else is
1459
unhit_names.extend(self._index_names[offset+1:])
1460
unhit_indices.extend(self._indices[offset+1:])
1463
unhit_names.append(name)
1464
unhit_indices.append(idx)
1466
self._indices = new_hit_indices + unhit_indices
1467
self._index_names = hit_names + unhit_names
1468
if 'index' in debug.debug_flags:
1469
trace.mutter('CombinedGraphIndex reordered: %r', self._indices)
1472
def _move_to_front_by_name(self, hit_names):
1473
"""Moves indices named by 'hit_names' to front of the search order, as
1474
described in _move_to_front.
1476
# Translate names to index instances, and then call
1477
# _move_to_front_by_index.
1478
indices_info = zip(self._index_names, self._indices)
1480
for name, idx in indices_info:
1481
if name in hit_names:
1482
hit_indices.append(idx)
1483
self._move_to_front_by_index(hit_indices)
1485
def find_ancestry(self, keys, ref_list_num):
1486
"""Find the complete ancestry for the given set of keys.
1488
Note that this is a whole-ancestry request, so it should be used
1491
:param keys: An iterable of keys to look for
1492
:param ref_list_num: The reference list which references the parents
1494
:return: (parent_map, missing_keys)
1496
# XXX: make this call _move_to_front?
1497
missing_keys = set()
1499
keys_to_lookup = set(keys)
1501
while keys_to_lookup:
1502
# keys that *all* indexes claim are missing, stop searching them
1504
all_index_missing = None
1505
# print 'gen\tidx\tsub\tn_keys\tn_pmap\tn_miss'
1506
# print '%4d\t\t\t%4d\t%5d\t%5d' % (generation, len(keys_to_lookup),
1508
# len(missing_keys))
1509
for index_idx, index in enumerate(self._indices):
1510
# TODO: we should probably be doing something with
1511
# 'missing_keys' since we've already determined that
1512
# those revisions have not been found anywhere
1513
index_missing_keys = set()
1514
# Find all of the ancestry we can from this index
1515
# keep looking until the search_keys set is empty, which means
1516
# things we didn't find should be in index_missing_keys
1517
search_keys = keys_to_lookup
1519
# print ' \t%2d\t\t%4d\t%5d\t%5d' % (
1520
# index_idx, len(search_keys),
1521
# len(parent_map), len(index_missing_keys))
1524
# TODO: ref_list_num should really be a parameter, since
1525
# CombinedGraphIndex does not know what the ref lists
1527
search_keys = index._find_ancestors(search_keys,
1528
ref_list_num, parent_map, index_missing_keys)
1529
# print ' \t \t%2d\t%4d\t%5d\t%5d' % (
1530
# sub_generation, len(search_keys),
1531
# len(parent_map), len(index_missing_keys))
1532
# Now set whatever was missing to be searched in the next index
1533
keys_to_lookup = index_missing_keys
1534
if all_index_missing is None:
1535
all_index_missing = set(index_missing_keys)
1537
all_index_missing.intersection_update(index_missing_keys)
1538
if not keys_to_lookup:
1540
if all_index_missing is None:
1541
# There were no indexes, so all search keys are 'missing'
1542
missing_keys.update(keys_to_lookup)
1543
keys_to_lookup = None
1545
missing_keys.update(all_index_missing)
1546
keys_to_lookup.difference_update(all_index_missing)
1547
return parent_map, missing_keys
1228
1549
def key_count(self):
1229
1550
"""Return an estimate of the number of keys in this index.
1231
1552
For CombinedGraphIndex this is approximated by the sum of the keys of
1232
1553
the child indices. As child indices may have duplicate keys this can
1233
1554
have a maximum error of the number of child indices * largest number of
1234
1555
keys in any index.
1236
return sum((index.key_count() for index in self._indices), 0)
1559
return sum((index.key_count() for index in self._indices), 0)
1560
except errors.NoSuchFile:
1561
self._reload_or_raise()
1563
missing_keys = _missing_keys_from_parent_map
1565
def _reload_or_raise(self):
1566
"""We just got a NoSuchFile exception.
1568
Try to reload the indices, if it fails, just raise the current
1571
if self._reload_func is None:
1573
exc_type, exc_value, exc_traceback = sys.exc_info()
1574
trace.mutter('Trying to reload after getting exception: %s',
1576
if not self._reload_func():
1577
# We tried to reload, but nothing changed, so we fail anyway
1578
trace.mutter('_reload_func indicated nothing has changed.'
1579
' Raising original exception.')
1580
raise exc_type, exc_value, exc_traceback
1582
def set_sibling_indices(self, sibling_combined_graph_indices):
1583
"""Set the CombinedGraphIndex objects to reorder after reordering self.
1585
self._sibling_indices = sibling_combined_graph_indices
1238
1587
def validate(self):
1239
1588
"""Validate that everything in the index can be accessed."""
1240
for index in self._indices:
1591
for index in self._indices:
1594
except errors.NoSuchFile:
1595
self._reload_or_raise()
1244
1598
class InMemoryGraphIndex(GraphIndexBuilder):