├── .gitignore ├── LICENSE ├── README.md ├── celery_redis_cluster_backend ├── __init__.py └── redis_cluster.py ├── docker-compose.yml ├── example.py ├── redis.conf ├── requirments.txt └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | 162 | .vscode/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Hasan Basri Ateş 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # celery-backends-rediscluster 2 | 3 | [Celery](http://www.celeryproject.org/)'s custom result backend for [RedisCluster]. 4 | 5 | ## Usage 6 | 7 | 1. pip install -e git+git://github.com/hbasria/celery-redis-cluster-backend.git#egg=celery-redis-cluster-backend 8 | 9 | 2. Add the following to `celeryconfig.py`. 10 | 11 | ``` 12 | CELERY_RESULT_BACKEND = "celery_redis_cluster_backend.redis_cluster.RedisClusterBackend" 13 | CELERY_REDIS_CLUSTER_SETTINGS = { 'startup_nodes': [ 14 | {"host": "localhost", "port": "6379"}, 15 | {"host": "localhost", "port": "6380"}, 16 | {"host": "localhost", "port": "6381"} 17 | ]} 18 | ``` 19 | 20 | ## example usag 21 | 22 | start all containers 23 | 24 | ``` 25 | docker compose up -d 26 | ``` 27 | 28 | create and activate python environment 29 | 30 | ``` 31 | python -m venv .venv 32 | source .venv/bin/activate 33 | ``` 34 | 35 | install all requirements 36 | 37 | ``` 38 | pip install -r requirments.txt 39 | pip install . 40 | ``` 41 | 42 | start celery worker 43 | 44 | ``` 45 | celery -A example worker -B --loglevel=INFO 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /celery_redis_cluster_backend/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from .redis_cluster import RedisClusterBackend 3 | -------------------------------------------------------------------------------- /celery_redis_cluster_backend/redis_cluster.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | celery.backends.rediscluster 4 | ~~~~~~~~~~~~~~~~~~~~~ 5 | 6 | Redis cluster result store backend. 7 | 8 | CELERY_REDIS_CLUSTER_BACKEND_SETTINGS = { 9 | startup_nodes: [{"host": "127.0.0.1", "port": "6379"}] 10 | } 11 | """ 12 | from __future__ import absolute_import 13 | 14 | from functools import partial 15 | 16 | from kombu.utils import cached_property, retry_over_time 17 | 18 | from celery import states 19 | from celery.canvas import maybe_signature 20 | from celery.exceptions import ChordError, ImproperlyConfigured 21 | from celery.utils.serialization import strtobool 22 | from celery.utils.log import get_logger 23 | from celery.utils.time import humanize_seconds 24 | 25 | from celery.backends.base import KeyValueStoreBackend 26 | 27 | # try: 28 | from rediscluster.client import RedisCluster 29 | # from kombu.transport.redis import get_redis_error_classes 30 | # except ImportError: # pragma: no cover 31 | # RedisCluster = None # noqa 32 | # ConnectionError = None # noqa 33 | get_redis_error_classes = None # noqa 34 | 35 | __all__ = ['RedisClusterBackend'] 36 | 37 | REDIS_MISSING = """\ 38 | You need to install the redis-py-cluster library in order to use \ 39 | the Redis result store backend.""" 40 | 41 | logger = get_logger(__name__) 42 | error = logger.error 43 | 44 | 45 | class RedisClusterBackend(KeyValueStoreBackend): 46 | """Redis task result store.""" 47 | 48 | #: redis client module. 49 | redis = RedisCluster 50 | 51 | startup_nodes = None 52 | max_connections = None 53 | init_slot_cache = True 54 | 55 | supports_autoexpire = True 56 | supports_native_join = True 57 | implements_incr = True 58 | 59 | def __init__(self, *args, **kwargs): 60 | super(RedisClusterBackend, self).__init__(expires_type=int, **kwargs) 61 | conf = self.app.conf 62 | 63 | if self.redis is None: 64 | raise ImproperlyConfigured(REDIS_MISSING) 65 | 66 | # For compatibility with the old REDIS_* configuration keys. 67 | def _get(key): 68 | for prefix in 'CELERY_REDIS_{0}', 'REDIS_{0}': 69 | try: 70 | return conf[prefix.format(key)] 71 | except KeyError: 72 | pass 73 | 74 | self.conn_params = self.app.conf.get('CELERY_REDIS_CLUSTER_SETTINGS', { 75 | 'startup_nodes': [{'host': _get('HOST') or 'localhost', 'port': _get('PORT') or 6379}] 76 | }) 77 | 78 | if self.conn_params is not None: 79 | if not isinstance(self.conn_params, dict): 80 | raise ImproperlyConfigured( 81 | 'RedisCluster backend settings should be grouped in a dict') 82 | 83 | try: 84 | new_join = strtobool(self.conn_params.pop('new_join')) 85 | if new_join: 86 | self.apply_chord = self._new_chord_apply 87 | self.on_chord_part_return = self._new_chord_return 88 | 89 | except KeyError: 90 | pass 91 | 92 | self.expires = self.prepare_expires(None, type=int) 93 | self.connection_errors, self.channel_errors = ( 94 | get_redis_error_classes() if get_redis_error_classes 95 | else ((), ())) 96 | 97 | def get(self, key): 98 | return self.client.get(key) 99 | 100 | def mget(self, keys): 101 | return self.client.mget(keys) 102 | 103 | def ensure(self, fun, args, **policy): 104 | retry_policy = dict(self.retry_policy, **policy) 105 | max_retries = retry_policy.get('max_retries') 106 | return retry_over_time( 107 | fun, self.connection_errors, args, {}, 108 | partial(self.on_connection_error, max_retries), 109 | **retry_policy 110 | ) 111 | 112 | def on_connection_error(self, max_retries, exc, intervals, retries): 113 | tts = next(intervals) 114 | error('Connection to Redis lost: Retry (%s/%s) %s.', 115 | retries, max_retries or 'Inf', 116 | humanize_seconds(tts, 'in ')) 117 | return tts 118 | 119 | def set(self, key, value, **retry_policy): 120 | return self.ensure(self._set, (key, value), **retry_policy) 121 | 122 | def _set(self, key, value): 123 | self.client.set(key, value) 124 | 125 | if hasattr(self, 'expires'): 126 | self.client.expire(key, self.expires) 127 | 128 | def delete(self, key): 129 | self.client.delete(key) 130 | 131 | def incr(self, key): 132 | return self.client.incr(key) 133 | 134 | def expire(self, key, value): 135 | return self.client.expire(key, value) 136 | 137 | def add_to_chord(self, group_id, result): 138 | self.client.incr(self.get_key_for_group(group_id, '.t'), 1) 139 | 140 | def _unpack_chord_result(self, tup, decode, 141 | EXCEPTION_STATES=states.EXCEPTION_STATES, 142 | PROPAGATE_STATES=states.PROPAGATE_STATES): 143 | _, tid, state, retval = decode(tup) 144 | if state in EXCEPTION_STATES: 145 | retval = self.exception_to_python(retval) 146 | if state in PROPAGATE_STATES: 147 | raise ChordError('Dependency {0} raised {1!r}'.format(tid, retval)) 148 | return retval 149 | 150 | def _new_chord_apply(self, header, partial_args, group_id, body, 151 | result=None, options={}, **kwargs): 152 | # avoids saving the group in the redis db. 153 | options['task_id'] = group_id 154 | return header(*partial_args, **options or {}) 155 | 156 | def _new_chord_return(self, task, state, result, propagate=None, 157 | PROPAGATE_STATES=states.PROPAGATE_STATES): 158 | app = self.app 159 | if propagate is None: 160 | propagate = self.app.conf.CELERY_CHORD_PROPAGATES 161 | request = task.request 162 | tid, gid = request.id, request.group 163 | if not gid or not tid: 164 | return 165 | 166 | client = self.client 167 | jkey = self.get_key_for_group(gid, '.j') 168 | tkey = self.get_key_for_group(gid, '.t') 169 | result = self.encode_result(result, state) 170 | _, readycount, totaldiff, _, _ = client.pipeline() \ 171 | .rpush(jkey, self.encode([1, tid, state, result])) \ 172 | .llen(jkey) \ 173 | .get(tkey) \ 174 | .expire(jkey, 86400) \ 175 | .expire(tkey, 86400) \ 176 | .execute() 177 | 178 | totaldiff = int(totaldiff or 0) 179 | 180 | try: 181 | callback = maybe_signature(request.chord, app=app) 182 | total = callback['chord_size'] + totaldiff 183 | if readycount == total: 184 | decode, unpack = self.decode, self._unpack_chord_result 185 | resl, _, _ = client.pipeline() \ 186 | .lrange(jkey, 0, total) \ 187 | .delete(jkey) \ 188 | .delete(tkey) \ 189 | .execute() 190 | try: 191 | callback.delay([unpack(tup, decode) for tup in resl]) 192 | except Exception as exc: 193 | error('Chord callback for %r raised: %r', 194 | request.group, exc, exc_info=1) 195 | app._tasks[callback.task].backend.fail_from_current_stack( 196 | callback.id, 197 | exc=ChordError('Callback error: {0!r}'.format(exc)), 198 | ) 199 | except ChordError as exc: 200 | error('Chord %r raised: %r', request.group, exc, exc_info=1) 201 | app._tasks[callback.task].backend.fail_from_current_stack( 202 | callback.id, exc=exc, 203 | ) 204 | except Exception as exc: 205 | error('Chord %r raised: %r', request.group, exc, exc_info=1) 206 | app._tasks[callback.task].backend.fail_from_current_stack( 207 | callback.id, exc=ChordError('Join error: {0!r}'.format(exc)), 208 | ) 209 | 210 | @cached_property 211 | def client(self): 212 | return RedisCluster(**self.conn_params) 213 | 214 | def __reduce__(self, args=(), kwargs={}): 215 | return super(RedisClusterBackend, self).__reduce__( 216 | (self.conn_params['startup_nodes'], ), {'expires': self.expires}, 217 | ) 218 | 219 | 220 | if __name__ == '__main__': 221 | from celery import Celery 222 | 223 | class Config: 224 | CELERY_ENABLE_UTC = True 225 | CELERY_TIMEZONE = 'Europe/Istanbul' 226 | CELERY_REDIS_CLUSTER_SETTINGS = {'startup_nodes': [ 227 | {"host": "localhost", "port": "6379"}, 228 | {"host": "localhost", "port": "6380"}, 229 | {"host": "localhost", "port": "6381"} 230 | ]} 231 | 232 | app = Celery() 233 | app.config_from_object(Config) 234 | 235 | rb = RedisClusterBackend(app=app) 236 | rb.set('a', "deneme") 237 | print(rb.get('a')) 238 | print(rb.get('b')) 239 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | 4 | rabbitmq: 5 | image: rabbitmq:3-management-alpine 6 | ports: 7 | - 5672:5672 8 | - 15672:15672 9 | 10 | redis1: 11 | image: redis:7 12 | command: redis-server /etc/redis.conf 13 | ports: 14 | - 6379:6379 15 | volumes: 16 | - ./redis.conf:/etc/redis.conf 17 | 18 | redis2: 19 | image: redis:7 20 | command: redis-server /etc/redis.conf 21 | ports: 22 | - 6380:6379 23 | volumes: 24 | - ./redis.conf:/etc/redis.conf 25 | 26 | redis3: 27 | image: redis:7 28 | command: redis-server /etc/redis.conf 29 | ports: 30 | - 6381:6379 31 | volumes: 32 | - ./redis.conf:/etc/redis.conf 33 | 34 | redis4: 35 | image: redis:7 36 | command: redis-server /etc/redis.conf 37 | volumes: 38 | - ./redis.conf:/etc/redis.conf 39 | 40 | redis5: 41 | image: redis:7 42 | command: redis-server /etc/redis.conf 43 | volumes: 44 | - ./redis.conf:/etc/redis.conf 45 | 46 | redis6: 47 | image: redis:7 48 | command: redis-server /etc/redis.conf 49 | volumes: 50 | - ./redis.conf:/etc/redis.conf 51 | 52 | cluster-setup: 53 | image: redis:7 54 | depends_on: 55 | - redis1 56 | - redis2 57 | - redis3 58 | - redis4 59 | - redis5 60 | - redis6 61 | restart: "no" 62 | entrypoint: [ "bash", "-c", "redis-cli --cluster create redis1:6379 redis2:6379 redis3:6379 redis4:6379 redis5:6379 redis6:6379 --cluster-replicas 1 --cluster-yes"] -------------------------------------------------------------------------------- /example.py: -------------------------------------------------------------------------------- 1 | from celery import Celery 2 | 3 | app = Celery('hello', backend='celery_redis_cluster_backend.redis_cluster.RedisClusterBackend') 4 | 5 | @app.on_after_configure.connect 6 | def setup_periodic_tasks(sender, **kwargs): 7 | # Calls test('hello') every 10 seconds. 8 | sender.add_periodic_task(10.0, hello.s('world'), name='add every 10') 9 | 10 | 11 | @app.task 12 | def hello(arg): 13 | message = f'hello {arg}' 14 | print(message) 15 | return message -------------------------------------------------------------------------------- /redis.conf: -------------------------------------------------------------------------------- 1 | port 6379 2 | cluster-enabled yes 3 | cluster-config-file nodes.conf 4 | cluster-node-timeout 5000 5 | appendonly yes -------------------------------------------------------------------------------- /requirments.txt: -------------------------------------------------------------------------------- 1 | celery==5.2.7 2 | redis-py-cluster==2.1.3 -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup(name="celery-redis-cluster-backend", 4 | version='0.2.0', 5 | description="Celery redis cluster backend", 6 | license="MIT", 7 | author="Hasan Basri", 8 | author_email="hbasria@gmail.com", 9 | url="http://github.com/hbasria/celery-redis-cluster-backend", 10 | packages = find_packages(), 11 | keywords= "celery redis cluster", 12 | zip_safe = True) --------------------------------------------------------------------------------