##// END OF EJS Templates
caches: reduce timeouts on flock, and provide error output about filename which we cannot lock at.
marcink -
r2941:49e7d41f default
parent child Browse files
Show More
@@ -1,201 +1,202 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 55 try:
56 56 del self._cache[key]
57 57 except KeyError:
58 58 # we don't care if key isn't there at deletion
59 59 pass
60 60
61 61 def delete_multi(self, keys):
62 62 for key in keys:
63 63 self.delete(key)
64 64
65 65
66 66 class Serializer(object):
67 67 def _dumps(self, value, safe=False):
68 68 try:
69 69 return compat.pickle.dumps(value)
70 70 except Exception:
71 71 if safe:
72 72 return NO_VALUE
73 73 else:
74 74 raise
75 75
76 76 def _loads(self, value, safe=True):
77 77 try:
78 78 return compat.pickle.loads(value)
79 79 except Exception:
80 80 if safe:
81 81 return NO_VALUE
82 82 else:
83 83 raise
84 84
85 85
86 86 class CustomLockFactory(FileLock):
87 87
88 88 @memoized_property
89 89 def _module(self):
90 90 import fcntl
91 91 flock_org = fcntl.flock
92 92
93 93 def gevent_flock(fd, operation):
94 94 """
95 95 Gevent compatible flock
96 96 """
97 97 # set non-blocking, this will cause an exception if we cannot acquire a lock
98 98 operation |= fcntl.LOCK_NB
99 99 start_lock_time = time.time()
100 100 timeout = 60 * 5 # 5min
101 101 while True:
102 102 try:
103 103 flock_org(fd, operation)
104 104 # lock has been acquired
105 105 break
106 106 except (OSError, IOError) as e:
107 107 # raise on other errors than Resource temporarily unavailable
108 108 if e.errno != errno.EAGAIN:
109 109 raise
110 110 elif (time.time() - start_lock_time) > timeout:
111 111 # waited to much time on a lock, better fail than loop for ever
112 log.error('Failed to acquire lock on %s file', self.filename)
112 113 raise
113 114
114 log.debug('Failed to acquire lock, retry in 0.1')
115 gevent.sleep(0.1)
115 log.debug('Failed to acquire lock, retry in 0.03')
116 gevent.sleep(0.03)
116 117
117 118 fcntl.flock = gevent_flock
118 119 return fcntl
119 120
120 121
121 122 class FileNamespaceBackend(Serializer, file_backend.DBMBackend):
122 123
123 124 def __init__(self, arguments):
124 125 arguments['lock_factory'] = CustomLockFactory
125 126 super(FileNamespaceBackend, self).__init__(arguments)
126 127
127 128 def list_keys(self, prefix=''):
128 129 def cond(v):
129 130 if not prefix:
130 131 return True
131 132
132 133 if v.startswith(prefix):
133 134 return True
134 135 return False
135 136
136 137 with self._dbm_file(True) as dbm:
137 138
138 139 return filter(cond, dbm.keys())
139 140
140 141 def get_store(self):
141 142 return self.filename
142 143
143 144 def get(self, key):
144 145 with self._dbm_file(False) as dbm:
145 146 if hasattr(dbm, 'get'):
146 147 value = dbm.get(key, NO_VALUE)
147 148 else:
148 149 # gdbm objects lack a .get method
149 150 try:
150 151 value = dbm[key]
151 152 except KeyError:
152 153 value = NO_VALUE
153 154 if value is not NO_VALUE:
154 155 value = self._loads(value)
155 156 return value
156 157
157 158 def set(self, key, value):
158 159 with self._dbm_file(True) as dbm:
159 160 dbm[key] = self._dumps(value)
160 161
161 162 def set_multi(self, mapping):
162 163 with self._dbm_file(True) as dbm:
163 164 for key, value in mapping.items():
164 165 dbm[key] = self._dumps(value)
165 166
166 167
167 168 class RedisPickleBackend(Serializer, redis_backend.RedisBackend):
168 169 def list_keys(self, prefix=''):
169 170 if prefix:
170 171 prefix = prefix + '*'
171 172 return self.client.keys(prefix)
172 173
173 174 def get_store(self):
174 175 return self.client.connection_pool
175 176
176 177 def get(self, key):
177 178 value = self.client.get(key)
178 179 if value is None:
179 180 return NO_VALUE
180 181 return self._loads(value)
181 182
182 183 def set(self, key, value):
183 184 if self.redis_expiration_time:
184 185 self.client.setex(key, self.redis_expiration_time,
185 186 self._dumps(value))
186 187 else:
187 188 self.client.set(key, self._dumps(value))
188 189
189 190 def set_multi(self, mapping):
190 191 mapping = dict(
191 192 (k, self._dumps(v))
192 193 for k, v in mapping.items()
193 194 )
194 195
195 196 if not self.redis_expiration_time:
196 197 self.client.mset(mapping)
197 198 else:
198 199 pipe = self.client.pipeline()
199 200 for key, value in mapping.items():
200 201 pipe.setex(key, self.redis_expiration_time, value)
201 202 pipe.execute()
General Comments 0
You need to be logged in to leave comments. Login now