|
| 1 | +""" |
| 2 | +Backend for django cache |
| 3 | +""" |
| 4 | +from django.core.cache import InvalidCacheBackendError |
| 5 | +from django.core.cache.backends.memcached import PyLibMCCache |
| 6 | +from django.utils.functional import cached_property |
| 7 | +from .cluster_utils import get_cluster_info |
| 8 | + |
| 9 | + |
| 10 | +class ElastiCache(PyLibMCCache): |
| 11 | + """ |
| 12 | + backend for Amazon ElastiCache (memcached) with auto discovery mode |
| 13 | + it used pylibmc in binary mode |
| 14 | + """ |
| 15 | + def __init__(self, server, params): |
| 16 | + self.update_params(params) |
| 17 | + super(ElastiCache, self).__init__(server, params) |
| 18 | + if len(self._servers) > 1: |
| 19 | + raise InvalidCacheBackendError( |
| 20 | + 'ElastiCache should be configured with only one server ' |
| 21 | + '(Configuration Endpoint)') |
| 22 | + if len(self._servers[0].split(':')) != 2: |
| 23 | + raise InvalidCacheBackendError( |
| 24 | + 'Server configuration should be in format IP:port') |
| 25 | + |
| 26 | + def update_params(self, params): |
| 27 | + """ |
| 28 | + update connection params to maximize performance |
| 29 | + """ |
| 30 | + if not params.get('BINARY', True): |
| 31 | + raise Warning('To increase performance please use ElastiCache' |
| 32 | + ' in binary mode') |
| 33 | + else: |
| 34 | + params['BINARY'] = True # patch params, set binary mode |
| 35 | + if not 'OPTIONS' in params: |
| 36 | + # set special 'behaviors' pylibmc attributes |
| 37 | + params['OPTIONS'] = { |
| 38 | + 'tcp_nodelay': True, |
| 39 | + 'ketama': True |
| 40 | + } |
| 41 | + |
| 42 | + @cached_property |
| 43 | + def get_cluster_nodes(self): |
| 44 | + """ |
| 45 | + return list with all nodes in cluster |
| 46 | + """ |
| 47 | + server, port = self._servers[0].split(':') |
| 48 | + return get_cluster_info(server, port)['nodes'] |
| 49 | + |
| 50 | + @property |
| 51 | + def _cache(self): |
| 52 | + # PylibMC uses cache options as the 'behaviors' attribute. |
| 53 | + # It also needs to use threadlocals, because some versions of |
| 54 | + # PylibMC don't play well with the GIL. |
| 55 | + client = getattr(self._local, 'client', None) |
| 56 | + if client: |
| 57 | + return client |
| 58 | + |
| 59 | + client = self._lib.Client(self.get_cluster_nodes) |
| 60 | + if self._options: |
| 61 | + client.behaviors = self._options |
| 62 | + |
| 63 | + self._local.client = client |
| 64 | + |
| 65 | + return client |
0 commit comments