1
# Copyright (C) 2008, 2009 Canonical Ltd
1
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
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
57
from bzrlib.static_tuple import StaticTuple
57
60
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
58
61
# out, it takes 3.1MB to cache the layer.
59
62
_PAGE_CACHE_SIZE = 4*1024*1024
60
# We are caching bytes so len(value) is perfectly accurate
61
_page_cache = lru_cache.LRUSizeCache(_PAGE_CACHE_SIZE)
63
# Per thread caches for 2 reasons:
64
# - in the server we may be serving very different content, so we get less
66
# - we avoid locking on every cache lookup.
67
_thread_caches = threading.local()
69
_thread_caches.page_cache = None
72
"""Get the per-thread page cache.
74
We need a function to do this because in a new thread the _thread_caches
75
threading.local object does not have the cache initialized yet.
77
page_cache = getattr(_thread_caches, 'page_cache', None)
78
if page_cache is None:
79
# We are caching bytes so len(value) is perfectly accurate
80
page_cache = lru_cache.LRUSizeCache(_PAGE_CACHE_SIZE)
81
_thread_caches.page_cache = page_cache
63
89
# If a ChildNode falls below this many bytes, we check for a remap
64
90
_INTERESTING_NEW_SIZE = 50
65
91
# If a ChildNode shrinks by more than this amount, we check for a remap
66
92
_INTERESTING_SHRINKAGE_LIMIT = 20
67
# If we delete more than this many nodes applying a delta, we check for a remap
68
_INTERESTING_DELETES_LIMIT = 5
71
95
def _search_key_plain(key):
80
104
class CHKMap(object):
81
105
"""A persistent map from string to string backed by a CHK store."""
107
__slots__ = ('_store', '_root_node', '_search_key_func')
83
109
def __init__(self, store, root_key, search_key_func=None):
84
110
"""Create a CHKMap object.
107
133
into the map; if old_key is not None, then the old mapping
108
134
of old_key is removed.
111
137
# Check preconditions first.
112
new_items = set([key for (old, key, value) in delta if key is not None
138
as_st = StaticTuple.from_sequence
139
new_items = set([as_st(key) for (old, key, value) in delta
140
if key is not None and old is None])
114
141
existing_new = list(self.iteritems(key_filter=new_items))
116
143
raise errors.InconsistentDeltaDelta(delta,
119
146
for old, new, value in delta:
120
147
if old is not None and old != new:
121
148
self.unmap(old, check_remap=False)
123
150
for old, new, value in delta:
124
151
if new is not None:
125
152
self.map(new, value)
126
if delete_count > _INTERESTING_DELETES_LIMIT:
127
trace.mutter("checking remap as %d deletions", delete_count)
128
154
self._check_remap()
129
155
return self._save()
131
157
def _ensure_root(self):
132
158
"""Ensure that the root node is an object not a key."""
133
if type(self._root_node) is tuple:
159
if type(self._root_node) is StaticTuple:
134
160
# Demand-load the root
135
161
self._root_node = self._get_node(self._root_node)
144
170
:param node: A tuple key or node object.
145
171
:return: A node object.
147
if type(node) is tuple:
173
if type(node) is StaticTuple:
148
174
bytes = self._read_bytes(node)
149
175
return _deserialise(bytes, node,
150
176
search_key_func=self._search_key_func)
154
180
def _read_bytes(self, key):
156
return _page_cache[key]
182
return _get_cache()[key]
158
184
stream = self._store.get_record_stream([key], 'unordered', True)
159
185
bytes = stream.next().get_bytes_as('fulltext')
160
_page_cache[key] = bytes
186
_get_cache()[key] = bytes
163
189
def _dump_tree(self, include_keys=False):
191
217
for key, value in sorted(node._items.iteritems()):
192
218
# Don't use prefix nor indent here to line up when used in
193
219
# tests in conjunction with assertEqualDiff
194
result.append(' %r %r' % (key, value))
220
result.append(' %r %r' % (tuple(key), value))
215
241
root_key = klass._create_directly(store, initial_value,
216
242
maximum_size=maximum_size, key_width=key_width,
217
243
search_key_func=search_key_func)
244
if type(root_key) is not StaticTuple:
245
raise AssertionError('we got a %s instead of a StaticTuple'
235
264
node = LeafNode(search_key_func=search_key_func)
236
265
node.set_maximum_size(maximum_size)
237
266
node._key_width = key_width
238
node._items = dict(initial_value)
267
as_st = StaticTuple.from_sequence
268
node._items = dict([(as_st(key), val) for key, val
269
in initial_value.iteritems()])
239
270
node._raw_size = sum([node._key_value_len(key, value)
240
for key,value in initial_value.iteritems()])
271
for key,value in node._items.iteritems()])
241
272
node._len = len(node._items)
242
273
node._compute_search_prefix()
243
274
node._compute_serialised_prefix()
479
510
def iteritems(self, key_filter=None):
480
511
"""Iterate over the entire CHKMap's contents."""
481
512
self._ensure_root()
513
if key_filter is not None:
514
as_st = StaticTuple.from_sequence
515
key_filter = [as_st(key) for key in key_filter]
482
516
return self._root_node.iteritems(self._store, key_filter=key_filter)
485
519
"""Return the key for this map."""
486
if type(self._root_node) is tuple:
520
if type(self._root_node) is StaticTuple:
487
521
return self._root_node
489
523
return self._root_node._key
498
532
:param key: A key to map.
499
533
:param value: The value to assign to key.
535
key = StaticTuple.from_sequence(key)
501
536
# Need a root object.
502
537
self._ensure_root()
503
538
prefix, node_details = self._root_node.map(self._store, key, value)
514
549
def _node_key(self, node):
515
550
"""Get the key for a node whether it's a tuple or node."""
516
551
if type(node) is tuple:
552
node = StaticTuple.from_sequence(node)
553
if type(node) is StaticTuple:
521
558
def unmap(self, key, check_remap=True):
522
559
"""remove key from the map."""
560
key = StaticTuple.from_sequence(key)
523
561
self._ensure_root()
524
562
if type(self._root_node) is InternalNode:
525
563
unmapped = self._root_node.unmap(self._store, key,
532
570
"""Check if nodes can be collapsed."""
533
571
self._ensure_root()
534
572
if type(self._root_node) is InternalNode:
535
self._root_node._check_remap(self._store)
573
self._root_node = self._root_node._check_remap(self._store)
538
576
"""Save the map completely.
540
578
:return: The key of the root node.
542
if type(self._root_node) is tuple:
580
if type(self._root_node) is StaticTuple:
544
582
return self._root_node
545
583
keys = list(self._root_node.serialise(self._store))
553
591
adding the header bytes, and without prefix compression.
594
__slots__ = ('_key', '_len', '_maximum_size', '_key_width',
595
'_raw_size', '_items', '_search_prefix', '_search_key_func'
556
598
def __init__(self, key_width=1):
557
599
"""Create a node.
647
689
the key/value pairs.
692
__slots__ = ('_common_serialised_prefix',)
650
694
def __init__(self, search_key_func=None):
651
695
Node.__init__(self)
652
696
# All of the keys in this leaf node share this common prefix
653
697
self._common_serialised_prefix = None
654
self._serialise_key = '\x00'.join
655
698
if search_key_func is None:
656
699
self._search_key_func = _search_key_plain
695
738
:param bytes: The bytes of the node.
696
739
:param key: The key that the serialised node has.
741
key = static_tuple.expect_static_tuple(key)
698
742
return _deserialise_leaf_node(bytes, key,
699
743
search_key_func=search_key_func)
840
884
raise AssertionError('%r must be known' % self._search_prefix)
841
885
return self._search_prefix, [("", self)]
887
_serialise_key = '\x00'.join
843
889
def serialise(self, store):
844
890
"""Serialise the LeafNode to store.
870
916
lines.append(serialized[prefix_len:])
871
917
lines.extend(value_lines)
872
918
sha1, _, _ = store.add_lines((None,), (), lines)
873
self._key = ("sha1:" + sha1,)
919
self._key = StaticTuple("sha1:" + sha1,).intern()
874
920
bytes = ''.join(lines)
875
921
if len(bytes) != self._current_size():
876
922
raise AssertionError('Invalid _current_size')
877
_page_cache.add(self._key, bytes)
923
_get_cache().add(self._key, bytes)
878
924
return [self._key]
944
990
LeafNode or InternalNode.
993
__slots__ = ('_node_width',)
947
995
def __init__(self, prefix='', search_key_func=None):
948
996
Node.__init__(self)
949
997
# The size of an internalnode with default values and no children.
991
1039
:param key: The key that the serialised node has.
992
1040
:return: An InternalNode instance.
1042
key = static_tuple.expect_static_tuple(key)
994
1043
return _deserialise_internal_node(bytes, key,
995
1044
search_key_func=search_key_func)
1021
1070
# for whatever we are missing
1022
1071
shortcut = True
1023
1072
for prefix, node in self._items.iteritems():
1024
if node.__class__ is tuple:
1073
if node.__class__ is StaticTuple:
1025
1074
keys[node] = (prefix, None)
1027
1076
yield node, None
1056
1105
# A given key can only match 1 child node, if it isn't
1057
1106
# there, then we can just return nothing
1059
if node.__class__ is tuple:
1108
if node.__class__ is StaticTuple:
1060
1109
keys[node] = (search_prefix, [key])
1062
1111
# This is loaded, and the only thing that can match,
1089
1138
# We can ignore this one
1091
1140
node_key_filter = prefix_to_keys[search_prefix]
1092
if node.__class__ is tuple:
1141
if node.__class__ is StaticTuple:
1093
1142
keys[node] = (search_prefix, node_key_filter)
1095
1144
yield node, node_key_filter
1104
1153
if sub_prefix in length_filter:
1105
1154
node_key_filter.extend(prefix_to_keys[sub_prefix])
1106
1155
if node_key_filter: # this key matched something, yield it
1107
if node.__class__ is tuple:
1156
if node.__class__ is StaticTuple:
1108
1157
keys[node] = (prefix, node_key_filter)
1110
1159
yield node, node_key_filter
1144
1193
prefix, node_key_filter = keys[record.key]
1145
1194
node_and_filters.append((node, node_key_filter))
1146
1195
self._items[prefix] = node
1147
_page_cache.add(record.key, bytes)
1196
_get_cache().add(record.key, bytes)
1148
1197
for info in node_and_filters:
1259
1308
lines.append('%s\n' % (self._search_prefix,))
1260
1309
prefix_len = len(self._search_prefix)
1261
1310
for prefix, node in sorted(self._items.items()):
1262
if type(node) is tuple:
1311
if type(node) is StaticTuple:
1265
1314
key = node._key[0]
1269
1318
% (serialised, self._search_prefix))
1270
1319
lines.append(serialised[prefix_len:])
1271
1320
sha1, _, _ = store.add_lines((None,), (), lines)
1272
self._key = ("sha1:" + sha1,)
1273
_page_cache.add(self._key, ''.join(lines))
1321
self._key = StaticTuple("sha1:" + sha1,).intern()
1322
_get_cache().add(self._key, ''.join(lines))
1274
1323
yield self._key
1276
1325
def _search_key(self, key):
1425
1474
def __init__(self, store, new_root_keys, old_root_keys,
1426
1475
search_key_func, pb=None):
1476
# TODO: Should we add a StaticTuple barrier here? It would be nice to
1477
# force callers to use StaticTuple, because there will often be
1478
# lots of keys passed in here. And even if we cast it locally,
1479
# that just meanst that we will have *both* a StaticTuple and a
1480
# tuple() in memory, referring to the same object. (so a net
1481
# increase in memory, not a decrease.)
1427
1482
self._store = store
1428
1483
self._new_root_keys = new_root_keys
1429
1484
self._old_root_keys = old_root_keys
1431
1486
# All uninteresting chks that we have seen. By the time they are added
1432
1487
# here, they should be either fully ignored, or queued up for
1489
# TODO: This might grow to a large size if there are lots of merge
1490
# parents, etc. However, it probably doesn't scale to O(history)
1491
# like _processed_new_refs does.
1434
1492
self._all_old_chks = set(self._old_root_keys)
1435
1493
# All items that we have seen from the old_root_keys
1436
1494
self._all_old_items = set()
1437
1495
# These are interesting items which were either read, or already in the
1438
1496
# interesting queue (so we don't need to walk them again)
1497
# TODO: processed_new_refs becomes O(all_chks), consider switching to
1439
1499
self._processed_new_refs = set()
1440
1500
self._search_key_func = search_key_func
1448
1508
self._state = None
1450
1510
def _read_nodes_from_store(self, keys):
1451
# We chose not to use _page_cache, because we think in terms of records
1452
# to be yielded. Also, we expect to touch each page only 1 time during
1453
# this code. (We may want to evaluate saving the raw bytes into the
1454
# page cache, which would allow a working tree update after the fetch
1455
# to not have to read the bytes again.)
1511
# We chose not to use _get_cache(), because we think in
1512
# terms of records to be yielded. Also, we expect to touch each page
1513
# only 1 time during this code. (We may want to evaluate saving the
1514
# raw bytes into the page cache, which would allow a working tree
1515
# update after the fetch to not have to read the bytes again.)
1516
as_st = StaticTuple.from_sequence
1456
1517
stream = self._store.get_record_stream(keys, 'unordered', True)
1457
1518
for record in stream:
1458
1519
if self._pb is not None:
1465
1526
if type(node) is InternalNode:
1466
1527
# Note we don't have to do node.refs() because we know that
1467
1528
# there are no children that have been pushed into this node
1529
# Note: Using as_st() here seemed to save 1.2MB, which would
1530
# indicate that we keep 100k prefix_refs around while
1531
# processing. They *should* be shorter lived than that...
1532
# It does cost us ~10s of processing time
1533
#prefix_refs = [as_st(item) for item in node._items.iteritems()]
1468
1534
prefix_refs = node._items.items()
1471
1537
prefix_refs = []
1538
# Note: We don't use a StaticTuple here. Profiling showed a
1539
# minor memory improvement (0.8MB out of 335MB peak 0.2%)
1540
# But a significant slowdown (15s / 145s, or 10%)
1472
1541
items = node._items.items()
1473
1542
yield record, node, prefix_refs, items
1482
1551
if p_r[1] not in all_old_chks]
1483
1552
new_refs = [p_r[1] for p_r in prefix_refs]
1484
1553
all_old_chks.update(new_refs)
1554
# TODO: This might be a good time to turn items into StaticTuple
1555
# instances and possibly intern them. However, this does not
1556
# impact 'initial branch' performance, so I'm not worrying
1485
1558
self._all_old_items.update(items)
1486
1559
# Queue up the uninteresting references
1487
1560
# Don't actually put them in the 'to-read' queue until we have
1540
1613
# current design allows for this, as callers will do the work
1541
1614
# to make the results unique. We might profile whether we
1542
1615
# gain anything by ensuring unique return values for items
1616
# TODO: This might be a good time to cast to StaticTuple, as
1617
# self._new_item_queue will hold the contents of multiple
1618
# records for an extended lifetime
1543
1619
new_items = [item for item in items
1544
1620
if item not in self._all_old_items]
1545
1621
self._new_item_queue.extend(new_items)
1571
1647
yield None, new_items
1572
1648
refs = refs.difference(all_old_chks)
1649
processed_new_refs.update(refs)
1651
# TODO: Using a SimpleSet for self._processed_new_refs and
1652
# saved as much as 10MB of peak memory. However, it requires
1653
# implementing a non-pyrex version.
1574
1654
next_refs = set()
1575
1655
next_refs_update = next_refs.update
1576
1656
# Inlining _read_nodes_from_store improves 'bzr branch bzr.dev'
1577
1657
# from 1m54s to 1m51s. Consider it.
1578
1658
for record, _, p_refs, items in self._read_nodes_from_store(refs):
1579
items = [item for item in items
1580
if item not in all_old_items]
1660
# using the 'if' check saves about 145s => 141s, when
1661
# streaming initial branch of Launchpad data.
1662
items = [item for item in items
1663
if item not in all_old_items]
1581
1664
yield record, items
1582
1665
next_refs_update([p_r[1] for p_r in p_refs])
1667
# set1.difference(set/dict) walks all of set1, and checks if it
1668
# exists in 'other'.
1669
# set1.difference(iterable) walks all of iterable, and does a
1670
# 'difference_update' on a clone of set1. Pick wisely based on the
1671
# expected sizes of objects.
1672
# in our case it is expected that 'new_refs' will always be quite
1583
1674
next_refs = next_refs.difference(all_old_chks)
1584
1675
next_refs = next_refs.difference(processed_new_refs)
1585
1676
processed_new_refs.update(next_refs)
1592
1683
self._old_queue = []
1593
1684
all_old_chks = self._all_old_chks
1594
1685
for record, _, prefix_refs, items in self._read_nodes_from_store(refs):
1686
# TODO: Use StaticTuple here?
1595
1687
self._all_old_items.update(items)
1596
1688
refs = [r for _,r in prefix_refs if r not in all_old_chks]
1597
1689
self._old_queue.extend(refs)
1634
1726
from bzrlib._chk_map_pyx import (
1635
1728
_search_key_16,
1636
1729
_search_key_255,
1637
1730
_deserialise_leaf_node,
1638
1731
_deserialise_internal_node,
1733
except ImportError, e:
1734
osutils.failed_to_load_extension(e)
1641
1735
from bzrlib._chk_map_py import (
1642
1737
_search_key_16,
1643
1738
_search_key_255,
1644
1739
_deserialise_leaf_node,
1647
1742
search_key_registry.register('hash-16-way', _search_key_16)
1648
1743
search_key_registry.register('hash-255-way', _search_key_255)
1746
def _check_key(key):
1747
"""Helper function to assert that a key is properly formatted.
1749
This generally shouldn't be used in production code, but it can be helpful
1752
if type(key) is not StaticTuple:
1753
raise TypeError('key %r is not StaticTuple but %s' % (key, type(key)))
1755
raise ValueError('key %r should have length 1, not %d' % (key, len(key),))
1756
if type(key[0]) is not str:
1757
raise TypeError('key %r should hold a str, not %r'
1758
% (key, type(key[0])))
1759
if not key[0].startswith('sha1:'):
1760
raise ValueError('key %r should point to a sha1:' % (key,))