1
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
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
17
"""A simple least-recently-used (LRU) cache."""
26
class _LRUNode(object):
27
"""This maintains the linked-list which is the lru internals."""
29
__slots__ = ('prev', 'next_key', 'key', 'value')
31
def __init__(self, key, value):
33
self.next_key = _null_key
41
prev_key = self.prev.key
42
return '%s(%r n:%r p:%r)' % (self.__class__.__name__, self.key,
43
self.next_key, prev_key)
46
class LRUCache(object):
47
"""A class which manages a cache of entries, removing unused ones."""
49
def __init__(self, max_cache=100, after_cleanup_count=None):
51
# The "HEAD" of the lru linked list
52
self._most_recently_used = None
53
# The "TAIL" of the lru linked list
54
self._least_recently_used = None
55
self._update_max_cache(max_cache, after_cleanup_count)
57
def __contains__(self, key):
58
return key in self._cache
60
def __getitem__(self, key):
63
# Inlined from _record_access to decrease the overhead of __getitem__
64
# We also have more knowledge about structure if __getitem__ is
65
# succeeding, then we know that self._most_recently_used must not be
67
mru = self._most_recently_used
69
# Nothing to do, this node is already at the head of the queue
71
# Remove this node from the old location
73
next_key = node.next_key
74
# benchmarking shows that the lookup of _null_key in globals is faster
75
# than the attribute lookup for (node is self._least_recently_used)
76
if next_key is _null_key:
77
# 'node' is the _least_recently_used, because it doesn't have a
78
# 'next' item. So move the current lru to the previous node.
79
self._least_recently_used = node_prev
81
node_next = cache[next_key]
82
node_next.prev = node_prev
83
node_prev.next_key = next_key
84
# Insert this node at the front of the list
85
node.next_key = mru.key
87
self._most_recently_used = node
92
return len(self._cache)
94
@symbol_versioning.deprecated_method(
95
symbol_versioning.deprecated_in((2, 5, 0)))
96
def add(self, key, value, cleanup=None):
97
if cleanup is not None:
98
raise ValueError("Per-node cleanup functions no longer supported")
99
return self.__setitem__(key, value)
101
def __setitem__(self, key, value):
102
"""Add a new value to the cache"""
104
raise ValueError('cannot use _null_key as a key')
105
if key in self._cache:
106
node = self._cache[key]
108
self._record_access(node)
110
node = _LRUNode(key, value)
111
self._cache[key] = node
112
self._record_access(node)
114
if len(self._cache) > self._max_cache:
115
# Trigger the cleanup
118
def cache_size(self):
119
"""Get the number of entries we will cache."""
120
return self._max_cache
122
def get(self, key, default=None):
123
node = self._cache.get(key, None)
126
self._record_access(node)
130
"""Get the list of keys currently cached.
132
Note that values returned here may not be available by the time you
133
request them later. This is simply meant as a peak into the current
136
:return: An unordered list of keys that are currently cached.
138
return self._cache.keys()
141
"""Get a new dict with the same key:value pairs as the cache"""
142
return dict((k, n.value) for k, n in self._cache.iteritems())
144
items = symbol_versioning.deprecated_method(
145
symbol_versioning.deprecated_in((2, 5, 0)))(as_dict)
148
"""Clear the cache until it shrinks to the requested size.
150
This does not completely wipe the cache, just makes sure it is under
151
the after_cleanup_count.
153
# Make sure the cache is shrunk to the correct size
154
while len(self._cache) > self._after_cleanup_count:
157
def _record_access(self, node):
158
"""Record that key was accessed."""
159
# Move 'node' to the front of the queue
160
if self._most_recently_used is None:
161
self._most_recently_used = node
162
self._least_recently_used = node
164
elif node is self._most_recently_used:
165
# Nothing to do, this node is already at the head of the queue
167
# We've taken care of the tail pointer, remove the node, and insert it
170
if node is self._least_recently_used:
171
self._least_recently_used = node.prev
172
if node.prev is not None:
173
node.prev.next_key = node.next_key
174
if node.next_key is not _null_key:
175
node_next = self._cache[node.next_key]
176
node_next.prev = node.prev
178
node.next_key = self._most_recently_used.key
179
self._most_recently_used.prev = node
180
self._most_recently_used = node
183
def _remove_node(self, node):
184
if node is self._least_recently_used:
185
self._least_recently_used = node.prev
186
self._cache.pop(node.key)
187
# If we have removed all entries, remove the head pointer as well
188
if self._least_recently_used is None:
189
self._most_recently_used = None
190
if node.prev is not None:
191
node.prev.next_key = node.next_key
192
if node.next_key is not _null_key:
193
node_next = self._cache[node.next_key]
194
node_next.prev = node.prev
195
# And remove this node's pointers
197
node.next_key = _null_key
199
def _remove_lru(self):
200
"""Remove one entry from the lru, and handle consequences.
202
If there are no more references to the lru, then this entry should be
203
removed from the cache.
205
self._remove_node(self._least_recently_used)
208
"""Clear out all of the cache."""
209
# Clean up in LRU order
213
def resize(self, max_cache, after_cleanup_count=None):
214
"""Change the number of entries that will be cached."""
215
self._update_max_cache(max_cache,
216
after_cleanup_count=after_cleanup_count)
218
def _update_max_cache(self, max_cache, after_cleanup_count=None):
219
self._max_cache = max_cache
220
if after_cleanup_count is None:
221
self._after_cleanup_count = self._max_cache * 8 / 10
223
self._after_cleanup_count = min(after_cleanup_count,
228
class LRUSizeCache(LRUCache):
229
"""An LRUCache that removes things based on the size of the values.
231
This differs in that it doesn't care how many actual items there are,
232
it just restricts the cache to be cleaned up after so much data is stored.
234
The size of items added will be computed using compute_size(value), which
235
defaults to len() if not supplied.
238
def __init__(self, max_size=1024*1024, after_cleanup_size=None,
240
"""Create a new LRUSizeCache.
242
:param max_size: The max number of bytes to store before we start
243
clearing out entries.
244
:param after_cleanup_size: After cleaning up, shrink everything to this
246
:param compute_size: A function to compute the size of the values. We
247
use a function here, so that you can pass 'len' if you are just
248
using simple strings, or a more complex function if you are using
249
something like a list of strings, or even a custom object.
250
The function should take the form "compute_size(value) => integer".
251
If not supplied, it defaults to 'len()'
254
self._compute_size = compute_size
255
if compute_size is None:
256
self._compute_size = len
257
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
258
LRUCache.__init__(self, max_cache=max(int(max_size/512), 1))
260
def __setitem__(self, key, value):
261
"""Add a new value to the cache"""
263
raise ValueError('cannot use _null_key as a key')
264
node = self._cache.get(key, None)
265
value_len = self._compute_size(value)
266
if value_len >= self._after_cleanup_size:
267
# The new value is 'too big to fit', as it would fill up/overflow
268
# the cache all by itself
269
trace.mutter('Adding the key %r to an LRUSizeCache failed.'
270
' value %d is too big to fit in a the cache'
271
' with size %d %d', key, value_len,
272
self._after_cleanup_size, self._max_size)
274
# We won't be replacing the old node, so just remove it
275
self._remove_node(node)
278
node = _LRUNode(key, value)
279
self._cache[key] = node
281
self._value_size -= self._compute_size(node.value)
282
self._value_size += value_len
283
self._record_access(node)
285
if self._value_size > self._max_size:
290
"""Clear the cache until it shrinks to the requested size.
292
This does not completely wipe the cache, just makes sure it is under
293
the after_cleanup_size.
295
# Make sure the cache is shrunk to the correct size
296
while self._value_size > self._after_cleanup_size:
299
def _remove_node(self, node):
300
self._value_size -= self._compute_size(node.value)
301
LRUCache._remove_node(self, node)
303
def resize(self, max_size, after_cleanup_size=None):
304
"""Change the number of bytes that will be cached."""
305
self._update_max_size(max_size, after_cleanup_size=after_cleanup_size)
306
max_cache = max(int(max_size/512), 1)
307
self._update_max_cache(max_cache)
309
def _update_max_size(self, max_size, after_cleanup_size=None):
310
self._max_size = max_size
311
if after_cleanup_size is None:
312
self._after_cleanup_size = self._max_size * 8 / 10
314
self._after_cleanup_size = min(after_cleanup_size, self._max_size)