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