##// END OF EJS Templates
core: cleanup pyproject and makefile
core: cleanup pyproject and makefile

File last commit:

r1313:cbb3f19b default
r1314:f2acd5ab default
Show More
backends.py
313 lines | 9.5 KiB | text/x-python | PythonLexer
caches: replaced beaker with dogpile cache.
r483 # RhodeCode VCSServer provides access to different vcs backends via network.
source-code: updated copyrights to 2023
r1126 # Copyright (C) 2014-2023 RhodeCode GmbH
caches: replaced beaker with dogpile cache.
r483 #
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
caches: use of global cache prefixes so we can keep compatability when switching from OLD rc to new python3 based
r1135 #import errno
ruff: code-cleanups
r1100 import fcntl
import functools
import logging
caches: synced with CE code
r1113 import os
ruff: code-cleanups
r1100 import pickle
caches: synced with CE code
r1113 #import time
caches: replaced beaker with dogpile cache.
r483
caches: synced with CE code
r1113 #import gevent
caches: don't use key_manglers instead prefix keys based on backend.
r734 import msgpack
caches: added redis pool for redis cache backend
r781 import redis
ruff: code-cleanups
r1100
caches: synced code with ce changes
r1062 flock_org = fcntl.flock
from typing import Union
caches: added redis pool for redis cache backend
r781
ruff: code-cleanups
r1100 from dogpile.cache.api import Deserializer, Serializer
from dogpile.cache.backends import file as file_backend
caches: replaced beaker with dogpile cache.
r483 from dogpile.cache.backends import memory as memory_backend
caches: added redis backend as an option
r733 from dogpile.cache.backends import redis as redis_backend
caches: synced code with ce changes
r1062 from dogpile.cache.backends.file import FileLock
caches: added redis backend as an option
r733 from dogpile.cache.util import memoized_property
caches: optimized defaults for safer more reliable behaviour
r951
chore(caches): cleanup rc_cache and implement cleanup_backend for filesystem
r1275 from ...lib.memory_lru_dict import LRUDict, LRUDictDebug
from ...lib.str_utils import safe_bytes, safe_str
from ...lib.type_utils import str2bool
caches: replaced beaker with dogpile cache.
r483
_default_max_size = 1024
log = logging.getLogger(__name__)
class LRUMemoryBackend(memory_backend.MemoryBackend):
caches: don't use key_manglers instead prefix keys based on backend.
r734 key_prefix = 'lru_mem_backend'
caches: replaced beaker with dogpile cache.
r483 pickle_values = False
def __init__(self, arguments):
caches: synced with CE code
r1113 self.max_size = arguments.pop('max_size', _default_max_size)
caches: replaced beaker with dogpile cache.
r483
caches: use repo.lru based Dict cache. This LRUDict uses Timing Algo to not have to use locking...
r497 LRUDictClass = LRUDict
if arguments.pop('log_key_count', None):
LRUDictClass = LRUDictDebug
caches: synced with CE code
r1113 arguments['cache_dict'] = LRUDictClass(self.max_size)
python3: fixes and code optimization for python3.11
r1114 super().__init__(arguments)
caches: replaced beaker with dogpile cache.
r483
caches: synced with CE code
r1113 def __repr__(self):
return f'{self.__class__}(maxsize=`{self.max_size}`)'
def __str__(self):
return self.__repr__()
caches: replaced beaker with dogpile cache.
r483 def delete(self, key):
caches: use repo.lru based Dict cache. This LRUDict uses Timing Algo to not have to use locking...
r497 try:
caches: replaced beaker with dogpile cache.
r483 del self._cache[key]
caches: use repo.lru based Dict cache. This LRUDict uses Timing Algo to not have to use locking...
r497 except KeyError:
# we don't care if key isn't there at deletion
pass
caches: replaced beaker with dogpile cache.
r483
fix(caches): synced rc_cache module with rhodecode-ce
r1206 def list_keys(self, prefix):
return list(self._cache.keys())
caches: replaced beaker with dogpile cache.
r483 def delete_multi(self, keys):
for key in keys:
caches: use repo.lru based Dict cache. This LRUDict uses Timing Algo to not have to use locking...
r497 self.delete(key)
caches: added redis backend as an option
r733
fix(caches): synced rc_cache module with rhodecode-ce
r1206 def delete_multi_by_prefix(self, prefix):
cache_keys = self.list_keys(prefix=prefix)
num_affected_keys = len(cache_keys)
if num_affected_keys:
self.delete_multi(cache_keys)
return num_affected_keys
caches: added redis backend as an option
r733
caches: synced code with ce changes
r1062 class PickleSerializer:
python3: fixes and code optimization for python3.11
r1114 serializer: None | Serializer = staticmethod( # type: ignore
caches: synced code with ce changes
r1062 functools.partial(pickle.dumps, protocol=pickle.HIGHEST_PROTOCOL)
)
python3: fixes and code optimization for python3.11
r1114 deserializer: None | Deserializer = staticmethod( # type: ignore
caches: synced code with ce changes
r1062 functools.partial(pickle.loads)
)
caches: added redis backend as an option
r733
lint: auto-fixes
r1152 class MsgPackSerializer:
python3: fixes and code optimization for python3.11
r1114 serializer: None | Serializer = staticmethod( # type: ignore
caches: synced code with ce changes
r1062 msgpack.packb
)
python3: fixes and code optimization for python3.11
r1114 deserializer: None | Deserializer = staticmethod( # type: ignore
caches: synced code with ce changes
r1062 functools.partial(msgpack.unpackb, use_list=False)
)
caches: added redis backend as an option
r733
class CustomLockFactory(FileLock):
pass
caches: don't use key_manglers instead prefix keys based on backend.
r734 class FileNamespaceBackend(PickleSerializer, file_backend.DBMBackend):
key_prefix = 'file_backend'
caches: added redis backend as an option
r733
def __init__(self, arguments):
arguments['lock_factory'] = CustomLockFactory
caches: improved locking problems with distributed lock new cache backend
r946 db_file = arguments.get('filename')
caches: synced with CE code
r1113 log.debug('initialing cache-backend=%s db in %s', self.__class__.__name__, db_file)
db_file_dir = os.path.dirname(db_file)
if not os.path.isdir(db_file_dir):
os.makedirs(db_file_dir)
caches: improved locking problems with distributed lock new cache backend
r946 try:
python3: fixes and code optimization for python3.11
r1114 super().__init__(arguments)
caches: improved locking problems with distributed lock new cache backend
r946 except Exception:
caches: fixed unicode error on non-ascii cache key
r1015 log.exception('Failed to initialize db at: %s', db_file)
caches: improved locking problems with distributed lock new cache backend
r946 raise
caches: added redis backend as an option
r733
caches: added redis pool for redis cache backend
r781 def __repr__(self):
caches: synced with CE code
r1113 return f'{self.__class__}(file=`{self.filename}`)'
def __str__(self):
return self.__repr__()
caches: added redis pool for redis cache backend
r781
caches: new cache + archive cache implementation
r1121 def _get_keys_pattern(self, prefix: bytes = b''):
return b'%b:%b' % (safe_bytes(self.key_prefix), safe_bytes(prefix))
caches: fixed dbm keys calls to use bytes
r1082 def list_keys(self, prefix: bytes = b''):
caches: new cache + archive cache implementation
r1121 prefix = self._get_keys_pattern(prefix)
caches: don't use key_manglers instead prefix keys based on backend.
r734
caches: fixed dbm keys calls to use bytes
r1082 def cond(dbm_key: bytes):
caches: added redis backend as an option
r733 if not prefix:
return True
caches: fixed dbm keys calls to use bytes
r1082 if dbm_key.startswith(prefix):
caches: added redis backend as an option
r733 return True
return False
with self._dbm_file(True) as dbm:
caches: improved locking problems with distributed lock new cache backend
r946 try:
caches: fixed dbm keys calls to use bytes
r1082 return list(filter(cond, dbm.keys()))
caches: improved locking problems with distributed lock new cache backend
r946 except Exception:
log.error('Failed to fetch DBM keys from DB: %s', self.get_store())
raise
caches: added redis backend as an option
r733
fix(caches): synced rc_cache module with rhodecode-ce
r1206 def delete_multi_by_prefix(self, prefix):
cache_keys = self.list_keys(prefix=prefix)
num_affected_keys = len(cache_keys)
if num_affected_keys:
self.delete_multi(cache_keys)
return num_affected_keys
caches: added redis backend as an option
r733 def get_store(self):
return self.filename
chore(caches): cleanup rc_cache and implement cleanup_backend for filesystem
r1275 def cleanup_store(self):
for ext in ("db", "dat", "pag", "dir"):
final_filename = self.filename + os.extsep + ext
if os.path.exists(final_filename):
os.remove(final_filename)
log.warning('Removed dbm file %s', final_filename)
caches: added redis backend as an option
r733
caches: don't use key_manglers instead prefix keys based on backend.
r734 class BaseRedisBackend(redis_backend.RedisBackend):
cache: allow controlling lock_auto_renewal via .ini config
r949 key_prefix = ''
def __init__(self, arguments):
caches: synced with CE code
r1113 self.db_conn = arguments.get('host', '') or arguments.get('url', '') or 'redis-host'
python3: fixes and code optimization for python3.11
r1114 super().__init__(arguments)
caches: synced with CE code
r1113
cache: allow controlling lock_auto_renewal via .ini config
r949 self._lock_timeout = self.lock_timeout
caches: synced with CE code
r1113 self._lock_auto_renewal = str2bool(arguments.pop("lock_auto_renewal", True))
cache: allow controlling lock_auto_renewal via .ini config
r949
feat(redis): added redis prefix support for cache backend
r1313 self._store_key_prefix = arguments.pop('key_prefix', '')
self.key_prefix = f'{self._store_key_prefix}{self.key_prefix}'
cache: allow controlling lock_auto_renewal via .ini config
r949 if self._lock_auto_renewal and not self._lock_timeout:
# set default timeout for auto_renewal
caches: optimized defaults for safer more reliable behaviour
r951 self._lock_timeout = 30
caches: added redis pool for redis cache backend
r781
caches: synced with CE code
r1113 def __repr__(self):
return f'{self.__class__}(conn=`{self.db_conn}`)'
def __str__(self):
return self.__repr__()
caches: added redis pool for redis cache backend
r781 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)
caches: synced code with ce changes
r1062 self.writer_client = redis.StrictRedis(
connection_pool=connection_pool
)
self.reader_client = self.writer_client
caches: added redis pool for redis cache backend
r781
caches: new cache + archive cache implementation
r1121 def _get_keys_pattern(self, prefix: bytes = b''):
return b'%b:%b*' % (safe_bytes(self.key_prefix), safe_bytes(prefix))
def list_keys(self, prefix: bytes = b''):
prefix = self._get_keys_pattern(prefix)
caches: synced code with ce changes
r1062 return self.reader_client.keys(prefix)
caches: added redis backend as an option
r733
fix(caches): synced rc_cache module with rhodecode-ce
r1206 def delete_multi_by_prefix(self, prefix, use_lua=False):
if use_lua:
# high efficient LUA script to delete ALL keys by prefix...
lua = """local keys = redis.call('keys', ARGV[1])
for i=1,#keys,5000 do
redis.call('del', unpack(keys, i, math.min(i+(5000-1), #keys)))
end
return #keys"""
num_affected_keys = self.writer_client.eval(
lua,
0,
f"{prefix}*")
else:
cache_keys = self.list_keys(prefix=prefix)
num_affected_keys = len(cache_keys)
if num_affected_keys:
self.delete_multi(cache_keys)
return num_affected_keys
caches: added redis backend as an option
r733 def get_store(self):
caches: synced code with ce changes
r1062 return self.reader_client.connection_pool
caches: added redis backend as an option
r733
def get_mutex(self, key):
if self.distributed_lock:
feat(redis): added redis prefix support for cache backend
r1313 lock_key = f'{self._store_key_prefix}_lock_{safe_str(key)}'
caches: synced code with ce changes
r1062 return get_mutex_lock(
self.writer_client, lock_key,
self._lock_timeout,
auto_renewal=self._lock_auto_renewal
)
caches: added redis backend as an option
r733 else:
return None
caches: don't use key_manglers instead prefix keys based on backend.
r734
class RedisPickleBackend(PickleSerializer, BaseRedisBackend):
key_prefix = 'redis_pickle_backend'
pass
class RedisMsgPackBackend(MsgPackSerializer, BaseRedisBackend):
key_prefix = 'redis_msgpack_backend'
pass
caches: improved locking problems with distributed lock new cache backend
r946
def get_mutex_lock(client, lock_key, lock_timeout, auto_renewal=False):
chore(caches): cleanup rc_cache and implement cleanup_backend for filesystem
r1275 from ...lib._vendor import redis_lock
caches: improved locking problems with distributed lock new cache backend
r946
lint: auto-fixes
r1152 class _RedisLockWrapper:
caches: improved locking problems with distributed lock new cache backend
r946 """LockWrapper for redis_lock"""
caches: further improvements on the lock implementations
r952 @classmethod
def get_lock(cls):
caches: improved locking problems with distributed lock new cache backend
r946 return redis_lock.Lock(
redis_client=client,
name=lock_key,
expire=lock_timeout,
auto_renewal=auto_renewal,
strict=True,
)
caches: updated logging and some timings
r958 def __repr__(self):
caches: synced with CE code
r1113 return f"{self.__class__.__name__}:{lock_key}"
caches: updated logging and some timings
r958
def __str__(self):
caches: synced with CE code
r1113 return f"{self.__class__.__name__}:{lock_key}"
caches: updated logging and some timings
r958
caches: further improvements on the lock implementations
r952 def __init__(self):
self.lock = self.get_lock()
caches: updated logging and some timings
r958 self.lock_key = lock_key
caches: further improvements on the lock implementations
r952
caches: improved locking problems with distributed lock new cache backend
r946 def acquire(self, wait=True):
caches: updated logging and some timings
r958 log.debug('Trying to acquire Redis lock for key %s', self.lock_key)
caches: further improvements on the lock implementations
r952 try:
caches: updated logging and some timings
r958 acquired = self.lock.acquire(wait)
log.debug('Got lock for key %s, %s', self.lock_key, acquired)
return acquired
caches: fixed wrong except
r953 except redis_lock.AlreadyAcquired:
caches: further improvements on the lock implementations
r952 return False
lock: handle refresh thread already started
r954 except redis_lock.AlreadyStarted:
# refresh thread exists, but it also means we acquired the lock
return True
caches: improved locking problems with distributed lock new cache backend
r946
def release(self):
try:
self.lock.release()
except redis_lock.NotAcquired:
pass
return _RedisLockWrapper()