cassandra.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. # -* coding: utf-8 -*-
  2. """Apache Cassandra result store backend using the DataStax driver."""
  3. from celery import states
  4. from celery.exceptions import ImproperlyConfigured
  5. from celery.utils.log import get_logger
  6. from .base import BaseBackend
  7. try: # pragma: no cover
  8. import cassandra
  9. import cassandra.auth
  10. import cassandra.cluster
  11. except ImportError: # pragma: no cover
  12. cassandra = None # noqa
  13. __all__ = ['CassandraBackend']
  14. logger = get_logger(__name__)
  15. E_NO_CASSANDRA = """
  16. You need to install the cassandra-driver library to
  17. use the Cassandra backend. See https://github.com/datastax/python-driver
  18. """
  19. E_NO_SUCH_CASSANDRA_AUTH_PROVIDER = """
  20. CASSANDRA_AUTH_PROVIDER you provided is not a valid auth_provider class.
  21. See https://datastax.github.io/python-driver/api/cassandra/auth.html.
  22. """
  23. Q_INSERT_RESULT = """
  24. INSERT INTO {table} (
  25. task_id, status, result, date_done, traceback, children) VALUES (
  26. %s, %s, %s, %s, %s, %s) {expires};
  27. """
  28. Q_SELECT_RESULT = """
  29. SELECT status, result, date_done, traceback, children
  30. FROM {table}
  31. WHERE task_id=%s
  32. LIMIT 1
  33. """
  34. Q_CREATE_RESULT_TABLE = """
  35. CREATE TABLE {table} (
  36. task_id text,
  37. status text,
  38. result blob,
  39. date_done timestamp,
  40. traceback blob,
  41. children blob,
  42. PRIMARY KEY ((task_id), date_done)
  43. ) WITH CLUSTERING ORDER BY (date_done DESC);
  44. """
  45. Q_EXPIRES = """
  46. USING TTL {0}
  47. """
  48. def buf_t(x):
  49. return bytes(x, 'utf8')
  50. class CassandraBackend(BaseBackend):
  51. """Cassandra backend utilizing DataStax driver
  52. Raises:
  53. celery.exceptions.ImproperlyConfigured:
  54. if module :pypi:`cassandra-driver` is not available,
  55. or if the :setting:`cassandra_servers` setting is not set.
  56. """
  57. #: List of Cassandra servers with format: ``hostname``.
  58. servers = None
  59. supports_autoexpire = True # autoexpire supported via entry_ttl
  60. def __init__(self, servers=None, keyspace=None, table=None, entry_ttl=None,
  61. port=9042, **kwargs):
  62. super().__init__(**kwargs)
  63. if not cassandra:
  64. raise ImproperlyConfigured(E_NO_CASSANDRA)
  65. conf = self.app.conf
  66. self.servers = servers or conf.get('cassandra_servers', None)
  67. self.port = port or conf.get('cassandra_port', None)
  68. self.keyspace = keyspace or conf.get('cassandra_keyspace', None)
  69. self.table = table or conf.get('cassandra_table', None)
  70. if not self.servers or not self.keyspace or not self.table:
  71. raise ImproperlyConfigured('Cassandra backend not configured.')
  72. expires = entry_ttl or conf.get('cassandra_entry_ttl', None)
  73. self.cqlexpires = (
  74. Q_EXPIRES.format(expires) if expires is not None else '')
  75. read_cons = conf.get('cassandra_read_consistency') or 'LOCAL_QUORUM'
  76. write_cons = conf.get('cassandra_write_consistency') or 'LOCAL_QUORUM'
  77. self.read_consistency = getattr(
  78. cassandra.ConsistencyLevel, read_cons,
  79. cassandra.ConsistencyLevel.LOCAL_QUORUM)
  80. self.write_consistency = getattr(
  81. cassandra.ConsistencyLevel, write_cons,
  82. cassandra.ConsistencyLevel.LOCAL_QUORUM)
  83. self.auth_provider = None
  84. auth_provider = conf.get('cassandra_auth_provider', None)
  85. auth_kwargs = conf.get('cassandra_auth_kwargs', None)
  86. if auth_provider and auth_kwargs:
  87. auth_provider_class = getattr(cassandra.auth, auth_provider, None)
  88. if not auth_provider_class:
  89. raise ImproperlyConfigured(E_NO_SUCH_CASSANDRA_AUTH_PROVIDER)
  90. self.auth_provider = auth_provider_class(**auth_kwargs)
  91. self._connection = None
  92. self._session = None
  93. self._write_stmt = None
  94. self._read_stmt = None
  95. self._make_stmt = None
  96. def process_cleanup(self):
  97. if self._connection is not None:
  98. self._connection.shutdown() # also shuts down _session
  99. self._connection = None
  100. self._session = None
  101. def _get_connection(self, write=False):
  102. """Prepare the connection for action
  103. Arguments:
  104. write (bool): are we a writer?
  105. """
  106. if self._connection is not None:
  107. return
  108. try:
  109. self._connection = cassandra.cluster.Cluster(
  110. self.servers, port=self.port,
  111. auth_provider=self.auth_provider)
  112. self._session = self._connection.connect(self.keyspace)
  113. # We are forced to do concatenation below, as formatting would
  114. # blow up on superficial %s that will be processed by Cassandra
  115. self._write_stmt = cassandra.query.SimpleStatement(
  116. Q_INSERT_RESULT.format(
  117. table=self.table, expires=self.cqlexpires),
  118. )
  119. self._write_stmt.consistency_level = self.write_consistency
  120. self._read_stmt = cassandra.query.SimpleStatement(
  121. Q_SELECT_RESULT.format(table=self.table),
  122. )
  123. self._read_stmt.consistency_level = self.read_consistency
  124. if write:
  125. # Only possible writers "workers" are allowed to issue
  126. # CREATE TABLE. This is to prevent conflicting situations
  127. # where both task-creator and task-executor would issue it
  128. # at the same time.
  129. # Anyway; if you're doing anything critical, you should
  130. # have created this table in advance, in which case
  131. # this query will be a no-op (AlreadyExists)
  132. self._make_stmt = cassandra.query.SimpleStatement(
  133. Q_CREATE_RESULT_TABLE.format(table=self.table),
  134. )
  135. self._make_stmt.consistency_level = self.write_consistency
  136. try:
  137. self._session.execute(self._make_stmt)
  138. except cassandra.AlreadyExists:
  139. pass
  140. except cassandra.OperationTimedOut:
  141. # a heavily loaded or gone Cassandra cluster failed to respond.
  142. # leave this class in a consistent state
  143. if self._connection is not None:
  144. self._connection.shutdown() # also shuts down _session
  145. self._connection = None
  146. self._session = None
  147. raise # we did fail after all - reraise
  148. def _store_result(self, task_id, result, state,
  149. traceback=None, request=None, **kwargs):
  150. """Store return value and state of an executed task."""
  151. self._get_connection(write=True)
  152. self._session.execute(self._write_stmt, (
  153. task_id,
  154. state,
  155. buf_t(self.encode(result)),
  156. self.app.now(),
  157. buf_t(self.encode(traceback)),
  158. buf_t(self.encode(self.current_task_children(request)))
  159. ))
  160. def as_uri(self, include_password=True):
  161. return 'cassandra://'
  162. def _get_task_meta_for(self, task_id):
  163. """Get task meta-data for a task by id."""
  164. self._get_connection()
  165. res = self._session.execute(self._read_stmt, (task_id, ))
  166. if not res:
  167. return {'status': states.PENDING, 'result': None}
  168. status, result, date_done, traceback, children = res[0]
  169. return self.meta_from_decoded({
  170. 'task_id': task_id,
  171. 'status': status,
  172. 'result': self.decode(result),
  173. 'date_done': date_done.strftime('%Y-%m-%dT%H:%M:%SZ'),
  174. 'traceback': self.decode(traceback),
  175. 'children': self.decode(children),
  176. })
  177. def __reduce__(self, args=(), kwargs={}):
  178. kwargs.update(
  179. dict(servers=self.servers,
  180. keyspace=self.keyspace,
  181. table=self.table))
  182. return super().__reduce__(args, kwargs)