~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/lru_cache.py

  • Committer: Patch Queue Manager
  • Date: 2011-09-15 15:37:20 UTC
  • mfrom: (6140.1.3 trunk)
  • Revision ID: pqm@pqm.ubuntu.com-20110915153720-n17t6m5oh5bblqad
(vila) Open 2.5b2 for bugfixes (Vincent Ladeuil)

Show diffs side-by-side

added added

removed removed

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