##// END OF EJS Templates
caches: use safer method of purging keys from memory dict. During some concurrency tests...
marcink -
r2931:474abf70 default
parent child Browse files
Show More
@@ -1,199 +1,201 b''
1 1 # -*- coding: utf-8 -*-
2 2
3 3 # Copyright (C) 2015-2018 RhodeCode GmbH
4 4 #
5 5 # This program is free software: you can redistribute it and/or modify
6 6 # it under the terms of the GNU Affero General Public License, version 3
7 7 # (only), as published by the Free Software Foundation.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU Affero General Public License
15 15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 16 #
17 17 # This program is dual-licensed. If you wish to learn more about the
18 18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20 20 import time
21 21 import errno
22 22 import logging
23 23
24 24 import gevent
25 25
26 26 from dogpile.cache.backends import memory as memory_backend
27 27 from dogpile.cache.backends import file as file_backend
28 28 from dogpile.cache.backends import redis as redis_backend
29 29 from dogpile.cache.backends.file import NO_VALUE, compat, FileLock
30 30 from dogpile.cache.util import memoized_property
31 31 from lru import LRU as LRUDict
32 32
33 33
34 34 _default_max_size = 1024
35 35
36 36 log = logging.getLogger(__name__)
37 37
38 38
39 39 class LRUMemoryBackend(memory_backend.MemoryBackend):
40 40 pickle_values = False
41 41
42 42 def __init__(self, arguments):
43 43 max_size = arguments.pop('max_size', _default_max_size)
44 44 callback = None
45 45 if arguments.pop('log_max_size_reached', None):
46 46 def evicted(key, value):
47 47 log.debug(
48 48 'LRU: evicting key `%s` due to max size %s reach', key, max_size)
49 49 callback = evicted
50 50
51 51 arguments['cache_dict'] = LRUDict(max_size, callback=callback)
52 52 super(LRUMemoryBackend, self).__init__(arguments)
53 53
54 54 def delete(self, key):
55 if self._cache.has_key(key):
55 try:
56 56 del self._cache[key]
57 except KeyError:
58 # we don't care if key isn't there at deletion
59 pass
57 60
58 61 def delete_multi(self, keys):
59 62 for key in keys:
60 if self._cache.has_key(key):
61 del self._cache[key]
63 self.delete(key)
62 64
63 65
64 66 class Serializer(object):
65 67 def _dumps(self, value, safe=False):
66 68 try:
67 69 return compat.pickle.dumps(value)
68 70 except Exception:
69 71 if safe:
70 72 return NO_VALUE
71 73 else:
72 74 raise
73 75
74 76 def _loads(self, value, safe=True):
75 77 try:
76 78 return compat.pickle.loads(value)
77 79 except Exception:
78 80 if safe:
79 81 return NO_VALUE
80 82 else:
81 83 raise
82 84
83 85
84 86 class CustomLockFactory(FileLock):
85 87
86 88 @memoized_property
87 89 def _module(self):
88 90 import fcntl
89 91 flock_org = fcntl.flock
90 92
91 93 def gevent_flock(fd, operation):
92 94 """
93 95 Gevent compatible flock
94 96 """
95 97 # set non-blocking, this will cause an exception if we cannot acquire a lock
96 98 operation |= fcntl.LOCK_NB
97 99 start_lock_time = time.time()
98 100 timeout = 60 * 5 # 5min
99 101 while True:
100 102 try:
101 103 flock_org(fd, operation)
102 104 # lock has been acquired
103 105 break
104 106 except (OSError, IOError) as e:
105 107 # raise on other errors than Resource temporarily unavailable
106 108 if e.errno != errno.EAGAIN:
107 109 raise
108 110 elif (time.time() - start_lock_time) > timeout:
109 111 # waited to much time on a lock, better fail than loop for ever
110 112 raise
111 113
112 114 log.debug('Failed to acquire lock, retry in 0.1')
113 115 gevent.sleep(0.1)
114 116
115 117 fcntl.flock = gevent_flock
116 118 return fcntl
117 119
118 120
119 121 class FileNamespaceBackend(Serializer, file_backend.DBMBackend):
120 122
121 123 def __init__(self, arguments):
122 124 arguments['lock_factory'] = CustomLockFactory
123 125 super(FileNamespaceBackend, self).__init__(arguments)
124 126
125 127 def list_keys(self, prefix=''):
126 128 def cond(v):
127 129 if not prefix:
128 130 return True
129 131
130 132 if v.startswith(prefix):
131 133 return True
132 134 return False
133 135
134 136 with self._dbm_file(True) as dbm:
135 137
136 138 return filter(cond, dbm.keys())
137 139
138 140 def get_store(self):
139 141 return self.filename
140 142
141 143 def get(self, key):
142 144 with self._dbm_file(False) as dbm:
143 145 if hasattr(dbm, 'get'):
144 146 value = dbm.get(key, NO_VALUE)
145 147 else:
146 148 # gdbm objects lack a .get method
147 149 try:
148 150 value = dbm[key]
149 151 except KeyError:
150 152 value = NO_VALUE
151 153 if value is not NO_VALUE:
152 154 value = self._loads(value)
153 155 return value
154 156
155 157 def set(self, key, value):
156 158 with self._dbm_file(True) as dbm:
157 159 dbm[key] = self._dumps(value)
158 160
159 161 def set_multi(self, mapping):
160 162 with self._dbm_file(True) as dbm:
161 163 for key, value in mapping.items():
162 164 dbm[key] = self._dumps(value)
163 165
164 166
165 167 class RedisPickleBackend(Serializer, redis_backend.RedisBackend):
166 168 def list_keys(self, prefix=''):
167 169 if prefix:
168 170 prefix = prefix + '*'
169 171 return self.client.keys(prefix)
170 172
171 173 def get_store(self):
172 174 return self.client.connection_pool
173 175
174 176 def get(self, key):
175 177 value = self.client.get(key)
176 178 if value is None:
177 179 return NO_VALUE
178 180 return self._loads(value)
179 181
180 182 def set(self, key, value):
181 183 if self.redis_expiration_time:
182 184 self.client.setex(key, self.redis_expiration_time,
183 185 self._dumps(value))
184 186 else:
185 187 self.client.set(key, self._dumps(value))
186 188
187 189 def set_multi(self, mapping):
188 190 mapping = dict(
189 191 (k, self._dumps(v))
190 192 for k, v in mapping.items()
191 193 )
192 194
193 195 if not self.redis_expiration_time:
194 196 self.client.mset(mapping)
195 197 else:
196 198 pipe = self.client.pipeline()
197 199 for key, value in mapping.items():
198 200 pipe.setex(key, self.redis_expiration_time, value)
199 201 pipe.execute()
General Comments 0
You need to be logged in to leave comments. Login now