~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/index.py

  • Committer: INADA Naoki
  • Date: 2011-05-18 06:27:34 UTC
  • mfrom: (5887 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5894.
  • Revision ID: songofacandy@gmail.com-20110518062734-1ilhll0rrqyyp8um
merge from lp:bzr and resolve conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2007-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
31
31
 
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
 
34
from bzrlib import (
 
35
    bisect_multi,
 
36
    revision as _mod_revision,
 
37
    trace,
 
38
    )
38
39
""")
39
40
from bzrlib import (
40
41
    debug,
41
42
    errors,
42
43
    )
 
44
from bzrlib.static_tuple import StaticTuple
43
45
 
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.
93
95
        """
94
96
        self.reference_lists = reference_lists
95
 
        self._keys = set()
96
97
        # A dict of {key: (absent, ref_lists, value)}
97
98
        self._nodes = {}
 
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
102
105
 
103
106
    def _check_key(self, key):
104
107
        """Raise BadIndexKey if key is not a valid key for this index."""
105
 
        if type(key) != tuple:
 
108
        if type(key) not in (tuple, StaticTuple):
106
109
            raise errors.BadIndexKey(key)
107
110
        if self._key_length != len(key):
108
111
            raise errors.BadIndexKey(key)
164
167
            return
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)
168
171
        else:
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
188
191
                                This may contain duplicates if the same key is
189
192
                                referenced in multiple lists.
190
193
        """
 
194
        as_st = StaticTuple.from_sequence
191
195
        self._check_key(key)
192
196
        if _newline_null_re.search(value) is not None:
193
197
            raise errors.BadIndexValue(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
207
213
 
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
225
231
            # about
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)
228
 
        self._keys.add(key)
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)
231
238
 
 
239
    def clear_cache(self):
 
240
        """See GraphIndex.clear_cache()
 
241
 
 
242
        This is a no-op, but we need the api to conform to a generic 'Index'
 
243
        abstraction.
 
244
        """
 
245
        
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
369
384
    """
370
385
 
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.
373
388
 
374
389
        :param transport: A bzrlib.transport.Transport.
380
395
            avoided by having it supplied. If size is None, then bisection
381
396
            support will be disabled and accessing the index will just stream
382
397
            all the data.
 
398
        :param offset: Instead of starting the index data at offset 0, start it
 
399
            at an arbitrary offset.
383
400
        """
384
401
        self._transport = transport
385
402
        self._name = name
402
419
        self._size = size
403
420
        # The number of bytes we've read so far in trying to process this file
404
421
        self._bytes_read = 0
 
422
        self._base_offset = offset
405
423
 
406
424
    def __eq__(self, other):
407
425
        """Equal when self and other were created with the same parameters."""
427
445
            # We already did this
428
446
            return
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
435
458
        line_count = 0
441
464
        trailers = 0
442
465
        pos = stream.tell()
443
466
        lines = stream.read().split('\n')
 
467
        # GZ 2009-09-20: Should really use a try/finally block to ensure close
 
468
        stream.close()
444
469
        del lines[-1]
445
470
        _, _, _, trailers = self._parse_lines(lines, pos)
446
471
        for key, absent, references, value in self._keys_by_offset.itervalues():
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)
460
484
 
 
485
    def clear_cache(self):
 
486
        """Clear out any cached/memoized values.
 
487
 
 
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
 
490
        from this index.
 
491
        """
 
492
 
461
493
    def external_references(self, ref_list_num):
462
494
        """Return references that are not present in this index.
463
495
        """
466
498
            raise ValueError('No ref list %d, index has %d ref lists'
467
499
                % (ref_list_num, self.node_ref_lists))
468
500
        refs = set()
469
 
        for key, (value, ref_lists) in self._nodes.iteritems():
 
501
        nodes = self._nodes
 
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])
 
505
        return refs
473
506
 
474
507
    def _get_nodes_by_key(self):
475
508
        if self._nodes_by_key is None:
602
635
 
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
 
640
        nodes = self._nodes
 
641
        keys = [key for key in keys if key in nodes]
606
642
        if self.node_ref_lists:
607
643
            for key in keys:
608
 
                value, node_refs = self._nodes[key]
 
644
                value, node_refs = nodes[key]
609
645
                yield self, key, value, node_refs
610
646
        else:
611
647
            for key in keys:
612
 
                yield self, key, self._nodes[key]
 
648
                yield self, key, nodes[key]
613
649
 
614
650
    def iter_entries(self, keys):
615
651
        """Iterate over keys within the index.
637
673
        if self._nodes is not None:
638
674
            return self._iter_entries_from_total_buffer(keys)
639
675
        else:
640
 
            return (result[1] for result in bisect_multi_bytes(
 
676
            return (result[1] for result in bisect_multi.bisect_multi_bytes(
641
677
                self._lookup_keys_via_location, self._size, keys))
642
678
 
643
679
    def iter_entries_prefix(self, keys):
1152
1188
            self._parsed_key_map.insert(index + 1, new_key)
1153
1189
 
1154
1190
    def _read_and_parse(self, readv_ranges):
1155
 
        """Read the the ranges and parse the resulting data.
 
1191
        """Read the ranges and parse the resulting data.
1156
1192
 
1157
1193
        :param readv_ranges: A prepared readv range list.
1158
1194
        """
1164
1200
            self._buffer_all()
1165
1201
            return
1166
1202
 
 
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,
1168
 
            self._size)
 
1209
            self._size + self._base_offset)
1169
1210
        # parse
1170
1211
        for offset, data in readv_data:
 
1212
            offset -= base_offset
1171
1213
            self._bytes_read += len(data)
 
1214
            if offset < 0:
 
1215
                # transport.readv() expanded to extra data which isn't part of
 
1216
                # this index
 
1217
                data = data[-offset:]
 
1218
                offset = 0
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
1201
1248
    static data.
1202
1249
 
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.
 
1255
    
 
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).
1208
1260
    """
1209
1261
 
1210
1262
    def __init__(self, indices, reload_func=None):
1217
1269
        """
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)
1220
1279
 
1221
1280
    def __repr__(self):
1222
1281
        return "%s(%s)" % (
1223
1282
                self.__class__.__name__,
1224
1283
                ', '.join(map(repr, self._indices)))
1225
1284
 
 
1285
    def clear_cache(self):
 
1286
        """See GraphIndex.clear_cache()"""
 
1287
        for index in self._indices:
 
1288
            index.clear_cache()
 
1289
 
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:[]}
1232
1296
        else:
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
1240
1304
 
1241
1305
    has_key = _has_key_from_parent_map
1242
1306
 
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.
1245
1309
 
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)
1248
1315
        """
1249
1316
        self._indices.insert(pos, index)
 
1317
        self._index_names.insert(pos, name)
1250
1318
 
1251
1319
    def iter_all_entries(self):
1252
1320
        """Iterate over all keys within the index
1277
1345
        value and are only reported once.
1278
1346
 
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.
1283
1351
        """
1284
1352
        keys = set(keys)
 
1353
        hit_indices = []
1285
1354
        while True:
1286
1355
            try:
1287
1356
                for index in self._indices:
1288
1357
                    if not keys:
1289
 
                        return
 
1358
                        break
 
1359
                    index_hit = False
1290
1360
                    for node in index.iter_entries(keys):
1291
1361
                        keys.remove(node[1])
1292
1362
                        yield node
1293
 
                return
 
1363
                        index_hit = True
 
1364
                    if index_hit:
 
1365
                        hit_indices.append(index)
 
1366
                break
1294
1367
            except errors.NoSuchFile:
1295
1368
                self._reload_or_raise()
 
1369
        self._move_to_front(hit_indices)
1296
1370
 
1297
1371
    def iter_entries_prefix(self, keys):
1298
1372
        """Iterate over keys within the index using prefix matching.
1318
1392
        if not keys:
1319
1393
            return
1320
1394
        seen_keys = set()
 
1395
        hit_indices = []
1321
1396
        while True:
1322
1397
            try:
1323
1398
                for index in self._indices:
 
1399
                    index_hit = False
1324
1400
                    for node in index.iter_entries_prefix(keys):
1325
1401
                        if node[1] in seen_keys:
1326
1402
                            continue
1327
1403
                        seen_keys.add(node[1])
1328
1404
                        yield node
1329
 
                return
 
1405
                        index_hit = True
 
1406
                    if index_hit:
 
1407
                        hit_indices.append(index)
 
1408
                break
1330
1409
            except errors.NoSuchFile:
1331
1410
                self._reload_or_raise()
 
1411
        self._move_to_front(hit_indices)
 
1412
 
 
1413
    def _move_to_front(self, hit_indices):
 
1414
        """Rearrange self._indices so that hit_indices are first.
 
1415
 
 
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
 
1419
        _move_to_front.
 
1420
 
 
1421
        _move_to_front propagates to all objects in self._sibling_indices by
 
1422
        calling _move_to_front_by_name.
 
1423
        """
 
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
 
1427
            return
 
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)
 
1431
 
 
1432
    def _move_to_front_by_index(self, hit_indices):
 
1433
        """Core logic for _move_to_front.
 
1434
        
 
1435
        Returns a list of names corresponding to the hit_indices param.
 
1436
        """
 
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)
 
1441
        hit_names = []
 
1442
        unhit_names = []
 
1443
        new_hit_indices = []
 
1444
        unhit_indices = []
 
1445
 
 
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
 
1452
                    # unhit
 
1453
                    unhit_names.extend(self._index_names[offset+1:])
 
1454
                    unhit_indices.extend(self._indices[offset+1:])
 
1455
                    break
 
1456
            else:
 
1457
                unhit_names.append(name)
 
1458
                unhit_indices.append(idx)
 
1459
 
 
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)
 
1464
        return hit_names
 
1465
 
 
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.
 
1469
        """
 
1470
        # Translate names to index instances, and then call
 
1471
        # _move_to_front_by_index.
 
1472
        indices_info = zip(self._index_names, self._indices)
 
1473
        hit_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)
1332
1478
 
1333
1479
    def find_ancestry(self, keys, ref_list_num):
1334
1480
        """Find the complete ancestry for the given set of keys.
1341
1487
            we care about.
1342
1488
        :return: (parent_map, missing_keys)
1343
1489
        """
 
1490
        # XXX: make this call _move_to_front?
1344
1491
        missing_keys = set()
1345
1492
        parent_map = {}
1346
1493
        keys_to_lookup = set(keys)
1426
1573
                         ' Raising original exception.')
1427
1574
            raise exc_type, exc_value, exc_traceback
1428
1575
 
 
1576
    def set_sibling_indices(self, sibling_combined_graph_indices):
 
1577
        """Set the CombinedGraphIndex objects to reorder after reordering self.
 
1578
        """
 
1579
        self._sibling_indices = sibling_combined_graph_indices
 
1580
 
1429
1581
    def validate(self):
1430
1582
        """Validate that everything in the index can be accessed."""
1431
1583
        while True:
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).
1486
1638
        """
1487
 
        keys = set(keys)
 
1639
        # Note: See BTreeBuilder.iter_entries for an explanation of why we
 
1640
        #       aren't using set().intersection() here
 
1641
        nodes = self._nodes
 
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]
 
1644
            for key in keys:
 
1645
                node = nodes[key]
1491
1646
                if not node[0]:
1492
1647
                    yield self, key, node[2], node[1]
1493
1648
        else:
1494
 
            for key in keys.intersection(self._keys):
1495
 
                node = self._nodes[key]
 
1649
            for key in keys:
 
1650
                node = nodes[key]
1496
1651
                if not node[0]:
1497
1652
                    yield self, key, node[2]
1498
1653
 
1572
1727
 
1573
1728
        For InMemoryGraphIndex the estimate is exact.
1574
1729
        """
1575
 
        return len(self._keys)
 
1730
        return len(self._nodes) - len(self._absent_keys)
1576
1731
 
1577
1732
    def validate(self):
1578
1733
        """In memory index's have no known corruption at the moment."""