backends.py
342 lines
| 9.9 KiB
| text/x-python
|
PythonLexer
r2845 | # -*- coding: utf-8 -*- | |||
r4306 | # Copyright (C) 2015-2020 RhodeCode GmbH | |||
r2845 | # | |||
# This program is free software: you can redistribute it and/or modify | ||||
# it under the terms of the GNU Affero General Public License, version 3 | ||||
# (only), as published by the Free Software Foundation. | ||||
# | ||||
# This program is distributed in the hope that it will be useful, | ||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||||
# GNU General Public License for more details. | ||||
# | ||||
# You should have received a copy of the GNU Affero General Public License | ||||
# along with this program. If not, see <http://www.gnu.org/licenses/>. | ||||
# | ||||
# This program is dual-licensed. If you wish to learn more about the | ||||
# RhodeCode Enterprise Edition, including its added features, Support services, | ||||
# and proprietary license terms, please see https://rhodecode.com/licenses/ | ||||
r3848 | ||||
r2878 | import time | |||
import errno | ||||
import logging | ||||
r3851 | import msgpack | |||
r2878 | import gevent | |||
r3930 | import redis | |||
r2845 | ||||
r3851 | from dogpile.cache.api import CachedValue | |||
r2845 | from dogpile.cache.backends import memory as memory_backend | |||
from dogpile.cache.backends import file as file_backend | ||||
from dogpile.cache.backends import redis as redis_backend | ||||
r2878 | from dogpile.cache.backends.file import NO_VALUE, compat, FileLock | |||
from dogpile.cache.util import memoized_property | ||||
r2945 | ||||
from rhodecode.lib.memory_lru_dict import LRUDict, LRUDictDebug | ||||
r2845 | ||||
_default_max_size = 1024 | ||||
r2878 | log = logging.getLogger(__name__) | |||
r2845 | ||||
class LRUMemoryBackend(memory_backend.MemoryBackend): | ||||
r3851 | key_prefix = 'lru_mem_backend' | |||
r2882 | pickle_values = False | |||
r2845 | ||||
def __init__(self, arguments): | ||||
max_size = arguments.pop('max_size', _default_max_size) | ||||
r2887 | ||||
r2945 | LRUDictClass = LRUDict | |||
if arguments.pop('log_key_count', None): | ||||
LRUDictClass = LRUDictDebug | ||||
arguments['cache_dict'] = LRUDictClass(max_size) | ||||
r2845 | super(LRUMemoryBackend, self).__init__(arguments) | |||
r2882 | def delete(self, key): | |||
r2931 | try: | |||
r2882 | del self._cache[key] | |||
r2931 | except KeyError: | |||
# we don't care if key isn't there at deletion | ||||
pass | ||||
r2882 | ||||
def delete_multi(self, keys): | ||||
for key in keys: | ||||
r2931 | self.delete(key) | |||
r2882 | ||||
r2845 | ||||
r3851 | class PickleSerializer(object): | |||
r2909 | def _dumps(self, value, safe=False): | |||
try: | ||||
return compat.pickle.dumps(value) | ||||
except Exception: | ||||
if safe: | ||||
return NO_VALUE | ||||
else: | ||||
raise | ||||
r2845 | ||||
r2909 | def _loads(self, value, safe=True): | |||
try: | ||||
return compat.pickle.loads(value) | ||||
except Exception: | ||||
if safe: | ||||
return NO_VALUE | ||||
else: | ||||
raise | ||||
r2845 | ||||
r3851 | class MsgPackSerializer(object): | |||
def _dumps(self, value, safe=False): | ||||
try: | ||||
return msgpack.packb(value) | ||||
except Exception: | ||||
if safe: | ||||
return NO_VALUE | ||||
else: | ||||
raise | ||||
def _loads(self, value, safe=True): | ||||
""" | ||||
pickle maintained the `CachedValue` wrapper of the tuple | ||||
msgpack does not, so it must be added back in. | ||||
""" | ||||
try: | ||||
value = msgpack.unpackb(value, use_list=False) | ||||
return CachedValue(*value) | ||||
except Exception: | ||||
if safe: | ||||
return NO_VALUE | ||||
else: | ||||
raise | ||||
r3417 | import fcntl | |||
flock_org = fcntl.flock | ||||
r2878 | class CustomLockFactory(FileLock): | |||
@memoized_property | ||||
def _module(self): | ||||
def gevent_flock(fd, operation): | ||||
""" | ||||
Gevent compatible flock | ||||
""" | ||||
# set non-blocking, this will cause an exception if we cannot acquire a lock | ||||
operation |= fcntl.LOCK_NB | ||||
start_lock_time = time.time() | ||||
r3334 | timeout = 60 * 15 # 15min | |||
r2878 | while True: | |||
try: | ||||
flock_org(fd, operation) | ||||
# lock has been acquired | ||||
break | ||||
except (OSError, IOError) as e: | ||||
# raise on other errors than Resource temporarily unavailable | ||||
if e.errno != errno.EAGAIN: | ||||
raise | ||||
elif (time.time() - start_lock_time) > timeout: | ||||
# waited to much time on a lock, better fail than loop for ever | ||||
r2947 | log.error('Failed to acquire lock on `%s` after waiting %ss', | |||
self.filename, timeout) | ||||
r2878 | raise | |||
r2947 | wait_timeout = 0.03 | |||
log.debug('Failed to acquire lock on `%s`, retry in %ss', | ||||
self.filename, wait_timeout) | ||||
gevent.sleep(wait_timeout) | ||||
r2878 | ||||
fcntl.flock = gevent_flock | ||||
return fcntl | ||||
r3851 | class FileNamespaceBackend(PickleSerializer, file_backend.DBMBackend): | |||
key_prefix = 'file_backend' | ||||
r2845 | ||||
def __init__(self, arguments): | ||||
r2878 | arguments['lock_factory'] = CustomLockFactory | |||
r4423 | db_file = arguments.get('filename') | |||
log.debug('initialing %s DB in %s', self.__class__.__name__, db_file) | ||||
try: | ||||
super(FileNamespaceBackend, self).__init__(arguments) | ||||
except Exception: | ||||
log.error('Failed to initialize db at: %s', db_file) | ||||
raise | ||||
r2845 | ||||
r3933 | def __repr__(self): | |||
return '{} `{}`'.format(self.__class__, self.filename) | ||||
r2846 | def list_keys(self, prefix=''): | |||
r3851 | prefix = '{}:{}'.format(self.key_prefix, prefix) | |||
r2846 | def cond(v): | |||
if not prefix: | ||||
return True | ||||
if v.startswith(prefix): | ||||
return True | ||||
return False | ||||
r2845 | with self._dbm_file(True) as dbm: | |||
r4701 | try: | |||
return filter(cond, dbm.keys()) | ||||
except Exception: | ||||
log.error('Failed to fetch DBM keys from DB: %s', self.get_store()) | ||||
raise | ||||
r2845 | ||||
def get_store(self): | ||||
return self.filename | ||||
r3992 | def _dbm_get(self, key): | |||
r2845 | with self._dbm_file(False) as dbm: | |||
if hasattr(dbm, 'get'): | ||||
value = dbm.get(key, NO_VALUE) | ||||
else: | ||||
# gdbm objects lack a .get method | ||||
try: | ||||
value = dbm[key] | ||||
except KeyError: | ||||
value = NO_VALUE | ||||
if value is not NO_VALUE: | ||||
value = self._loads(value) | ||||
return value | ||||
r3992 | def get(self, key): | |||
try: | ||||
return self._dbm_get(key) | ||||
except Exception: | ||||
log.error('Failed to fetch DBM key %s from DB: %s', key, self.get_store()) | ||||
raise | ||||
r2845 | def set(self, key, value): | |||
with self._dbm_file(True) as dbm: | ||||
dbm[key] = self._dumps(value) | ||||
def set_multi(self, mapping): | ||||
with self._dbm_file(True) as dbm: | ||||
for key, value in mapping.items(): | ||||
dbm[key] = self._dumps(value) | ||||
r3851 | class BaseRedisBackend(redis_backend.RedisBackend): | |||
r3930 | ||||
def _create_client(self): | ||||
args = {} | ||||
if self.url is not None: | ||||
args.update(url=self.url) | ||||
else: | ||||
args.update( | ||||
host=self.host, password=self.password, | ||||
port=self.port, db=self.db | ||||
) | ||||
connection_pool = redis.ConnectionPool(**args) | ||||
return redis.StrictRedis(connection_pool=connection_pool) | ||||
r2846 | def list_keys(self, prefix=''): | |||
r3851 | prefix = '{}:{}*'.format(self.key_prefix, prefix) | |||
r2846 | return self.client.keys(prefix) | |||
r2845 | ||||
def get_store(self): | ||||
return self.client.connection_pool | ||||
r2909 | def get(self, key): | |||
value = self.client.get(key) | ||||
if value is None: | ||||
return NO_VALUE | ||||
return self._loads(value) | ||||
r3851 | def get_multi(self, keys): | |||
if not keys: | ||||
return [] | ||||
values = self.client.mget(keys) | ||||
loads = self._loads | ||||
return [ | ||||
loads(v) if v is not None else NO_VALUE | ||||
for v in values] | ||||
r2845 | def set(self, key, value): | |||
if self.redis_expiration_time: | ||||
self.client.setex(key, self.redis_expiration_time, | ||||
self._dumps(value)) | ||||
else: | ||||
self.client.set(key, self._dumps(value)) | ||||
def set_multi(self, mapping): | ||||
r3851 | dumps = self._dumps | |||
r2845 | mapping = dict( | |||
r3851 | (k, dumps(v)) | |||
r2845 | for k, v in mapping.items() | |||
) | ||||
if not self.redis_expiration_time: | ||||
self.client.mset(mapping) | ||||
else: | ||||
pipe = self.client.pipeline() | ||||
for key, value in mapping.items(): | ||||
pipe.setex(key, self.redis_expiration_time, value) | ||||
pipe.execute() | ||||
r3466 | ||||
def get_mutex(self, key): | ||||
if self.distributed_lock: | ||||
r4705 | lock_key = redis_backend.u('_lock_{0}').format(key) | |||
r3466 | log.debug('Trying to acquire Redis lock for key %s', lock_key) | |||
r4714 | ||||
auto_renewal = True | ||||
lock_timeout = self.lock_timeout | ||||
if auto_renewal and not self.lock_timeout: | ||||
# set default timeout for auto_renewal | ||||
lock_timeout = 10 | ||||
return get_mutex_lock(self.client, lock_key, lock_timeout, | ||||
auto_renewal=auto_renewal) | ||||
r3466 | else: | |||
return None | ||||
r3851 | ||||
class RedisPickleBackend(PickleSerializer, BaseRedisBackend): | ||||
key_prefix = 'redis_pickle_backend' | ||||
pass | ||||
class RedisMsgPackBackend(MsgPackSerializer, BaseRedisBackend): | ||||
key_prefix = 'redis_msgpack_backend' | ||||
pass | ||||
r4714 | ||||
def get_mutex_lock(client, lock_key, lock_timeout, auto_renewal=False): | ||||
import redis_lock | ||||
class _RedisLockWrapper(object): | ||||
"""LockWrapper for redis_lock""" | ||||
def __init__(self): | ||||
pass | ||||
@property | ||||
def lock(self): | ||||
return redis_lock.Lock( | ||||
redis_client=client, | ||||
name=lock_key, | ||||
expire=lock_timeout, | ||||
auto_renewal=auto_renewal, | ||||
strict=True, | ||||
) | ||||
def acquire(self, wait=True): | ||||
return self.lock.acquire(wait) | ||||
def release(self): | ||||
try: | ||||
self.lock.release() | ||||
except redis_lock.NotAcquired: | ||||
pass | ||||
return _RedisLockWrapper() | ||||