~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lru_cache.py

  • Committer: Robert Collins
  • Date: 2007-11-26 02:08:13 UTC
  • mto: This revision was merged to the branch mainline in revision 3029.
  • Revision ID: robertc@robertcollins.net-20071126020813-7sqwqvr0rucxv0oc
In the RemoteServer repository methods handle repositories that cannot be remotely locked like pack repositories, and add a read lock in SmartServerRepositoryStreamKnitDataForRevisions.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2006 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""A simple least-recently-used (LRU) cache."""
18
18
 
19
 
from bzrlib import (
20
 
    symbol_versioning,
21
 
    trace,
22
 
    )
23
 
 
24
 
_null_key = object()
25
 
 
26
 
class _LRUNode(object):
27
 
    """This maintains the linked-list which is the lru internals."""
28
 
 
29
 
    __slots__ = ('prev', 'next_key', 'key', 'value', 'cleanup', 'size')
30
 
 
31
 
    def __init__(self, key, value, cleanup=None):
32
 
        self.prev = None
33
 
        self.next_key = _null_key
34
 
        self.key = key
35
 
        self.value = value
36
 
        self.cleanup = cleanup
37
 
        # TODO: We could compute this 'on-the-fly' like we used to, and remove
38
 
        #       one pointer from this object, we just need to decide if it
39
 
        #       actually costs us much of anything in normal usage
40
 
        self.size = None
41
 
 
42
 
    def __repr__(self):
43
 
        if self.prev is None:
44
 
            prev_key = None
45
 
        else:
46
 
            prev_key = self.prev.key
47
 
        return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
48
 
                                     self.next_key, prev_key)
49
 
 
50
 
    def run_cleanup(self):
51
 
        try:
52
 
            if self.cleanup is not None:
53
 
                self.cleanup(self.key, self.value)
54
 
        finally:
55
 
            # cleanup might raise an exception, but we want to make sure
56
 
            # to break refcycles, etc
57
 
            self.cleanup = None
58
 
            self.value = None
 
19
from collections import deque
 
20
import gc
59
21
 
60
22
 
61
23
class LRUCache(object):
62
24
    """A class which manages a cache of entries, removing unused ones."""
63
25
 
64
 
    def __init__(self, max_cache=100, after_cleanup_count=None,
65
 
                 after_cleanup_size=symbol_versioning.DEPRECATED_PARAMETER):
66
 
        if symbol_versioning.deprecated_passed(after_cleanup_size):
67
 
            symbol_versioning.warn('LRUCache.__init__(after_cleanup_size) was'
68
 
                                   ' deprecated in 1.11. Use'
69
 
                                   ' after_cleanup_count instead.',
70
 
                                   DeprecationWarning)
71
 
            after_cleanup_count = after_cleanup_size
 
26
    def __init__(self, max_cache=100, after_cleanup_size=None):
 
27
        self._max_cache = max_cache
 
28
        if after_cleanup_size is None:
 
29
            self._after_cleanup_size = self._max_cache
 
30
        else:
 
31
            self._after_cleanup_size = min(after_cleanup_size, self._max_cache)
 
32
 
 
33
        self._compact_queue_length = 4*self._max_cache
 
34
 
72
35
        self._cache = {}
73
 
        # The "HEAD" of the lru linked list
74
 
        self._most_recently_used = None
75
 
        # The "TAIL" of the lru linked list
76
 
        self._least_recently_used = None
77
 
        self._update_max_cache(max_cache, after_cleanup_count)
 
36
        self._cleanup = {}
 
37
        self._queue = deque() # Track when things are accessed
 
38
        self._refcount = {} # number of entries in self._queue for each key
78
39
 
79
40
    def __contains__(self, key):
80
41
        return key in self._cache
81
42
 
82
43
    def __getitem__(self, key):
83
 
        cache = self._cache
84
 
        node = cache[key]
85
 
        # Inlined from _record_access to decrease the overhead of __getitem__
86
 
        # We also have more knowledge about structure if __getitem__ is
87
 
        # succeeding, then we know that self._most_recently_used must not be
88
 
        # None, etc.
89
 
        mru = self._most_recently_used
90
 
        if node is mru:
91
 
            # Nothing to do, this node is already at the head of the queue
92
 
            return node.value
93
 
        # Remove this node from the old location
94
 
        node_prev = node.prev
95
 
        next_key = node.next_key
96
 
        # benchmarking shows that the lookup of _null_key in globals is faster
97
 
        # than the attribute lookup for (node is self._least_recently_used)
98
 
        if next_key is _null_key:
99
 
            # 'node' is the _least_recently_used, because it doesn't have a
100
 
            # 'next' item. So move the current lru to the previous node.
101
 
            self._least_recently_used = node_prev
102
 
        else:
103
 
            node_next = cache[next_key]
104
 
            node_next.prev = node_prev
105
 
        node_prev.next_key = next_key
106
 
        # Insert this node at the front of the list
107
 
        node.next_key = mru.key
108
 
        mru.prev = node
109
 
        self._most_recently_used = node
110
 
        node.prev = None
111
 
        return node.value
 
44
        val = self._cache[key]
 
45
        self._record_access(key)
 
46
        return val
112
47
 
113
48
    def __len__(self):
114
49
        return len(self._cache)
115
50
 
116
 
    def _walk_lru(self):
117
 
        """Walk the LRU list, only meant to be used in tests."""
118
 
        node = self._most_recently_used
119
 
        if node is not None:
120
 
            if node.prev is not None:
121
 
                raise AssertionError('the _most_recently_used entry is not'
122
 
                                     ' supposed to have a previous entry'
123
 
                                     ' %s' % (node,))
124
 
        while node is not None:
125
 
            if node.next_key is _null_key:
126
 
                if node is not self._least_recently_used:
127
 
                    raise AssertionError('only the last node should have'
128
 
                                         ' no next value: %s' % (node,))
129
 
                node_next = None
130
 
            else:
131
 
                node_next = self._cache[node.next_key]
132
 
                if node_next.prev is not node:
133
 
                    raise AssertionError('inconsistency found, node.next.prev'
134
 
                                         ' != node: %s' % (node,))
135
 
            if node.prev is None:
136
 
                if node is not self._most_recently_used:
137
 
                    raise AssertionError('only the _most_recently_used should'
138
 
                                         ' not have a previous node: %s'
139
 
                                         % (node,))
140
 
            else:
141
 
                if node.prev.next_key != node.key:
142
 
                    raise AssertionError('inconsistency found, node.prev.next'
143
 
                                         ' != node: %s' % (node,))
144
 
            yield node
145
 
            node = node_next
146
 
 
147
51
    def add(self, key, value, cleanup=None):
148
52
        """Add a new value to the cache.
149
53
 
150
 
        Also, if the entry is ever removed from the cache, call
151
 
        cleanup(key, value).
 
54
        Also, if the entry is ever removed from the queue, call cleanup.
 
55
        Passing it the key and value being removed.
152
56
 
153
57
        :param key: The key to store it under
154
58
        :param value: The object to store
155
59
        :param cleanup: None or a function taking (key, value) to indicate
156
 
                        'value' should be cleaned up.
 
60
                        'value' sohuld be cleaned up.
157
61
        """
158
 
        if key is _null_key:
159
 
            raise ValueError('cannot use _null_key as a key')
160
62
        if key in self._cache:
161
 
            node = self._cache[key]
162
 
            try:
163
 
                node.run_cleanup()
164
 
            finally:
165
 
                # Maintain the LRU properties, even if cleanup raises an
166
 
                # exception
167
 
                node.value = value
168
 
                node.cleanup = cleanup
169
 
                self._record_access(node)
170
 
        else:
171
 
            node = _LRUNode(key, value, cleanup=cleanup)
172
 
            self._cache[key] = node
173
 
            self._record_access(node)
 
63
            self._remove(key)
 
64
        self._cache[key] = value
 
65
        self._cleanup[key] = cleanup
 
66
        self._record_access(key)
174
67
 
175
68
        if len(self._cache) > self._max_cache:
176
69
            # Trigger the cleanup
177
70
            self.cleanup()
178
71
 
179
 
    def cache_size(self):
180
 
        """Get the number of entries we will cache."""
181
 
        return self._max_cache
182
 
 
183
 
    def get(self, key, default=None):
184
 
        node = self._cache.get(key, None)
185
 
        if node is None:
186
 
            return default
187
 
        self._record_access(node)
188
 
        return node.value
189
 
 
190
 
    def keys(self):
191
 
        """Get the list of keys currently cached.
192
 
 
193
 
        Note that values returned here may not be available by the time you
194
 
        request them later. This is simply meant as a peak into the current
195
 
        state.
196
 
 
197
 
        :return: An unordered list of keys that are currently cached.
198
 
        """
199
 
        return self._cache.keys()
200
 
 
201
 
    def items(self):
202
 
        """Get the key:value pairs as a dict."""
203
 
        return dict((k, n.value) for k, n in self._cache.iteritems())
204
 
 
205
72
    def cleanup(self):
206
73
        """Clear the cache until it shrinks to the requested size.
207
74
 
208
75
        This does not completely wipe the cache, just makes sure it is under
209
 
        the after_cleanup_count.
 
76
        the after_cleanup_size.
210
77
        """
211
78
        # Make sure the cache is shrunk to the correct size
212
 
        while len(self._cache) > self._after_cleanup_count:
 
79
        while len(self._cache) > self._after_cleanup_size:
213
80
            self._remove_lru()
214
81
 
215
82
    def __setitem__(self, key, value):
216
83
        """Add a value to the cache, there will be no cleanup function."""
217
84
        self.add(key, value, cleanup=None)
218
85
 
219
 
    def _record_access(self, node):
 
86
    def _record_access(self, key):
220
87
        """Record that key was accessed."""
221
 
        # Move 'node' to the front of the queue
222
 
        if self._most_recently_used is None:
223
 
            self._most_recently_used = node
224
 
            self._least_recently_used = node
225
 
            return
226
 
        elif node is self._most_recently_used:
227
 
            # Nothing to do, this node is already at the head of the queue
228
 
            return
229
 
        # We've taken care of the tail pointer, remove the node, and insert it
230
 
        # at the front
231
 
        # REMOVE
232
 
        if node is self._least_recently_used:
233
 
            self._least_recently_used = node.prev
234
 
        if node.prev is not None:
235
 
            node.prev.next_key = node.next_key
236
 
        if node.next_key is not _null_key:
237
 
            node_next = self._cache[node.next_key]
238
 
            node_next.prev = node.prev
239
 
        # INSERT
240
 
        node.next_key = self._most_recently_used.key
241
 
        self._most_recently_used.prev = node
242
 
        self._most_recently_used = node
243
 
        node.prev = None
244
 
 
245
 
    def _remove_node(self, node):
246
 
        if node is self._least_recently_used:
247
 
            self._least_recently_used = node.prev
248
 
        self._cache.pop(node.key)
249
 
        # If we have removed all entries, remove the head pointer as well
250
 
        if self._least_recently_used is None:
251
 
            self._most_recently_used = None
252
 
        try:
253
 
            node.run_cleanup()
254
 
        finally:
255
 
            # cleanup might raise an exception, but we want to make sure to
256
 
            # maintain the linked list
257
 
            if node.prev is not None:
258
 
                node.prev.next_key = node.next_key
259
 
            if node.next_key is not _null_key:
260
 
                node_next = self._cache[node.next_key]
261
 
                node_next.prev = node.prev
262
 
            # And remove this node's pointers
263
 
            node.prev = None
264
 
            node.next_key = _null_key
 
88
        self._queue.append(key)
 
89
        # Can't use setdefault because you can't += 1 the result
 
90
        self._refcount[key] = self._refcount.get(key, 0) + 1
 
91
 
 
92
        # If our access queue is too large, clean it up too
 
93
        if len(self._queue) > self._compact_queue_length:
 
94
            self._compact_queue()
 
95
 
 
96
    def _compact_queue(self):
 
97
        """Compact the queue, leaving things in sorted last appended order."""
 
98
        new_queue = deque()
 
99
        for item in self._queue:
 
100
            if self._refcount[item] == 1:
 
101
                new_queue.append(item)
 
102
            else:
 
103
                self._refcount[item] -= 1
 
104
        self._queue = new_queue
 
105
        # All entries should be of the same size. There should be one entry in
 
106
        # queue for each entry in cache, and all refcounts should == 1
 
107
        assert (len(self._queue) == len(self._cache) ==
 
108
                len(self._refcount) == sum(self._refcount.itervalues()))
 
109
 
 
110
    def _remove(self, key):
 
111
        """Remove an entry, making sure to maintain the invariants."""
 
112
        cleanup = self._cleanup.pop(key)
 
113
        val = self._cache.pop(key)
 
114
        if cleanup is not None:
 
115
            cleanup(key, val)
 
116
        return val
265
117
 
266
118
    def _remove_lru(self):
267
119
        """Remove one entry from the lru, and handle consequences.
269
121
        If there are no more references to the lru, then this entry should be
270
122
        removed from the cache.
271
123
        """
272
 
        self._remove_node(self._least_recently_used)
 
124
        key = self._queue.popleft()
 
125
        self._refcount[key] -= 1
 
126
        if not self._refcount[key]:
 
127
            del self._refcount[key]
 
128
            self._remove(key)
273
129
 
274
130
    def clear(self):
275
131
        """Clear out all of the cache."""
277
133
        while self._cache:
278
134
            self._remove_lru()
279
135
 
280
 
    def resize(self, max_cache, after_cleanup_count=None):
281
 
        """Change the number of entries that will be cached."""
282
 
        self._update_max_cache(max_cache,
283
 
                               after_cleanup_count=after_cleanup_count)
284
 
 
285
 
    def _update_max_cache(self, max_cache, after_cleanup_count=None):
286
 
        self._max_cache = max_cache
287
 
        if after_cleanup_count is None:
288
 
            self._after_cleanup_count = self._max_cache * 8 / 10
289
 
        else:
290
 
            self._after_cleanup_count = min(after_cleanup_count,
291
 
                                            self._max_cache)
292
 
        self.cleanup()
293
 
 
294
136
 
295
137
class LRUSizeCache(LRUCache):
296
138
    """An LRUCache that removes things based on the size of the values.
298
140
    This differs in that it doesn't care how many actual items there are,
299
141
    it just restricts the cache to be cleaned up after so much data is stored.
300
142
 
301
 
    The size of items added will be computed using compute_size(value), which
302
 
    defaults to len() if not supplied.
 
143
    The values that are added must support len(value).
303
144
    """
304
145
 
305
146
    def __init__(self, max_size=1024*1024, after_cleanup_size=None,
317
158
            The function should take the form "compute_size(value) => integer".
318
159
            If not supplied, it defaults to 'len()'
319
160
        """
 
161
        # This approximates that texts are > 0.5k in size. It only really
 
162
        # effects when we clean up the queue, so we don't want it to be too
 
163
        # large.
 
164
        LRUCache.__init__(self, max_cache=int(max_size/512))
 
165
        self._max_size = max_size
 
166
        if after_cleanup_size is None:
 
167
            self._after_cleanup_size = self._max_size
 
168
        else:
 
169
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)
 
170
 
320
171
        self._value_size = 0
321
172
        self._compute_size = compute_size
322
173
        if compute_size is None:
323
174
            self._compute_size = len
324
 
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
325
 
        LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
326
175
 
327
176
    def add(self, key, value, cleanup=None):
328
177
        """Add a new value to the cache.
329
178
 
330
 
        Also, if the entry is ever removed from the cache, call
331
 
        cleanup(key, value).
 
179
        Also, if the entry is ever removed from the queue, call cleanup.
 
180
        Passing it the key and value being removed.
332
181
 
333
182
        :param key: The key to store it under
334
183
        :param value: The object to store
335
184
        :param cleanup: None or a function taking (key, value) to indicate
336
 
                        'value' should be cleaned up.
 
185
                        'value' sohuld be cleaned up.
337
186
        """
338
 
        if key is _null_key:
339
 
            raise ValueError('cannot use _null_key as a key')
340
 
        node = self._cache.get(key, None)
 
187
        if key in self._cache:
 
188
            self._remove(key)
341
189
        value_len = self._compute_size(value)
342
190
        if value_len >= self._after_cleanup_size:
343
 
            # The new value is 'too big to fit', as it would fill up/overflow
344
 
            # the cache all by itself
345
 
            trace.mutter('Adding the key %r to an LRUSizeCache failed.'
346
 
                         ' value %d is too big to fit in a the cache'
347
 
                         ' with size %d %d', key, value_len,
348
 
                         self._after_cleanup_size, self._max_size)
349
 
            if node is not None:
350
 
                # We won't be replacing the old node, so just remove it
351
 
                self._remove_node(node)
352
 
            if cleanup is not None:
353
 
                cleanup(key, value)
354
191
            return
355
 
        if node is None:
356
 
            node = _LRUNode(key, value, cleanup=cleanup)
357
 
            self._cache[key] = node
358
 
        else:
359
 
            self._value_size -= node.size
360
 
        node.size = value_len
361
192
        self._value_size += value_len
362
 
        self._record_access(node)
 
193
        self._cache[key] = value
 
194
        self._cleanup[key] = cleanup
 
195
        self._record_access(key)
363
196
 
364
197
        if self._value_size > self._max_size:
365
198
            # Time to cleanup
375
208
        while self._value_size > self._after_cleanup_size:
376
209
            self._remove_lru()
377
210
 
378
 
    def _remove_node(self, node):
379
 
        self._value_size -= node.size
380
 
        LRUCache._remove_node(self, node)
381
 
 
382
 
    def resize(self, max_size, after_cleanup_size=None):
383
 
        """Change the number of bytes that will be cached."""
384
 
        self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
385
 
        max_cache = max(int(max_size/512), 1)
386
 
        self._update_max_cache(max_cache)
387
 
 
388
 
    def _update_max_size(self, max_size, after_cleanup_size=None):
389
 
        self._max_size = max_size
390
 
        if after_cleanup_size is None:
391
 
            self._after_cleanup_size = self._max_size * 8 / 10
392
 
        else:
393
 
            self._after_cleanup_size = min(after_cleanup_size, self._max_size)
 
211
    def _remove(self, key):
 
212
        """Remove an entry, making sure to maintain the invariants."""
 
213
        val = LRUCache._remove(self, key)
 
214
        self._value_size -= self._compute_size(val)