mongodb.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. # -*- coding: utf-8 -*-
  2. """
  3. celery.backends.mongodb
  4. ~~~~~~~~~~~~~~~~~~~~~~~
  5. MongoDB result store backend.
  6. """
  7. from __future__ import absolute_import
  8. from datetime import datetime
  9. try:
  10. import pymongo
  11. except ImportError: # pragma: no cover
  12. pymongo = None # noqa
  13. if pymongo:
  14. try:
  15. from bson.binary import Binary
  16. except ImportError: # pragma: no cover
  17. from pymongo.binary import Binary # noqa
  18. else: # pragma: no cover
  19. Binary = None # noqa
  20. from kombu.syn import detect_environment
  21. from kombu.utils import cached_property
  22. from celery import states
  23. from celery.exceptions import ImproperlyConfigured
  24. from celery.five import string_t
  25. from celery.utils.timeutils import maybe_timedelta
  26. from .base import BaseBackend
  27. __all__ = ['MongoBackend']
  28. class Bunch(object):
  29. def __init__(self, **kw):
  30. self.__dict__.update(kw)
  31. class MongoBackend(BaseBackend):
  32. host = 'localhost'
  33. port = 27017
  34. user = None
  35. password = None
  36. database_name = 'celery'
  37. taskmeta_collection = 'celery_taskmeta'
  38. max_pool_size = 10
  39. options = None
  40. supports_autoexpire = False
  41. _connection = None
  42. def __init__(self, *args, **kwargs):
  43. """Initialize MongoDB backend instance.
  44. :raises celery.exceptions.ImproperlyConfigured: if
  45. module :mod:`pymongo` is not available.
  46. """
  47. self.options = {}
  48. super(MongoBackend, self).__init__(*args, **kwargs)
  49. self.expires = kwargs.get('expires') or maybe_timedelta(
  50. self.app.conf.CELERY_TASK_RESULT_EXPIRES)
  51. if not pymongo:
  52. raise ImproperlyConfigured(
  53. 'You need to install the pymongo library to use the '
  54. 'MongoDB backend.')
  55. config = self.app.conf.get('CELERY_MONGODB_BACKEND_SETTINGS')
  56. if config is not None:
  57. if not isinstance(config, dict):
  58. raise ImproperlyConfigured(
  59. 'MongoDB backend settings should be grouped in a dict')
  60. config = dict(config) # do not modify original
  61. self.host = config.pop('host', self.host)
  62. self.port = int(config.pop('port', self.port))
  63. self.user = config.pop('user', self.user)
  64. self.password = config.pop('password', self.password)
  65. self.database_name = config.pop('database', self.database_name)
  66. self.taskmeta_collection = config.pop(
  67. 'taskmeta_collection', self.taskmeta_collection,
  68. )
  69. self.options = dict(config, **config.pop('options', None) or {})
  70. # Set option defaults
  71. self.options.setdefault('ssl', self.app.conf.BROKER_USE_SSL)
  72. self.options.setdefault('max_pool_size', self.max_pool_size)
  73. self.options.setdefault('auto_start_request', False)
  74. url = kwargs.get('url')
  75. if url:
  76. # Specifying backend as an URL
  77. self.host = url
  78. def _get_connection(self):
  79. """Connect to the MongoDB server."""
  80. if self._connection is None:
  81. from pymongo import MongoClient
  82. # The first pymongo.Connection() argument (host) can be
  83. # a list of ['host:port'] elements or a mongodb connection
  84. # URI. If this is the case, don't use self.port
  85. # but let pymongo get the port(s) from the URI instead.
  86. # This enables the use of replica sets and sharding.
  87. # See pymongo.Connection() for more info.
  88. url = self.host
  89. if isinstance(url, string_t) \
  90. and not url.startswith('mongodb://'):
  91. url = 'mongodb://{0}:{1}'.format(url, self.port)
  92. if url == 'mongodb://':
  93. url = url + 'localhost'
  94. if detect_environment() != 'default':
  95. self.options['use_greenlets'] = True
  96. self._connection = MongoClient(host=url, **self.options)
  97. return self._connection
  98. def process_cleanup(self):
  99. if self._connection is not None:
  100. # MongoDB connection will be closed automatically when object
  101. # goes out of scope
  102. del(self.collection)
  103. del(self.database)
  104. self._connection = None
  105. def _store_result(self, task_id, result, status,
  106. traceback=None, request=None, **kwargs):
  107. """Store return value and status of an executed task."""
  108. meta = {'_id': task_id,
  109. 'status': status,
  110. 'result': Binary(self.encode(result)),
  111. 'date_done': datetime.utcnow(),
  112. 'traceback': Binary(self.encode(traceback)),
  113. 'children': Binary(self.encode(
  114. self.current_task_children(request),
  115. ))}
  116. self.collection.save(meta)
  117. return result
  118. def _get_task_meta_for(self, task_id):
  119. """Get task metadata for a task by id."""
  120. obj = self.collection.find_one({'_id': task_id})
  121. if not obj:
  122. return {'status': states.PENDING, 'result': None}
  123. meta = {
  124. 'task_id': obj['_id'],
  125. 'status': obj['status'],
  126. 'result': self.decode(obj['result']),
  127. 'date_done': obj['date_done'],
  128. 'traceback': self.decode(obj['traceback']),
  129. 'children': self.decode(obj['children']),
  130. }
  131. return meta
  132. def _save_group(self, group_id, result):
  133. """Save the group result."""
  134. meta = {'_id': group_id,
  135. 'result': Binary(self.encode(result)),
  136. 'date_done': datetime.utcnow()}
  137. self.collection.save(meta)
  138. return result
  139. def _restore_group(self, group_id):
  140. """Get the result for a group by id."""
  141. obj = self.collection.find_one({'_id': group_id})
  142. if not obj:
  143. return
  144. meta = {
  145. 'task_id': obj['_id'],
  146. 'result': self.decode(obj['result']),
  147. 'date_done': obj['date_done'],
  148. }
  149. return meta
  150. def _delete_group(self, group_id):
  151. """Delete a group by id."""
  152. self.collection.remove({'_id': group_id})
  153. def _forget(self, task_id):
  154. """
  155. Remove result from MongoDB.
  156. :raises celery.exceptions.OperationsError: if the task_id could not be
  157. removed.
  158. """
  159. # By using safe=True, this will wait until it receives a response from
  160. # the server. Likewise, it will raise an OperationsError if the
  161. # response was unable to be completed.
  162. self.collection.remove({'_id': task_id})
  163. def cleanup(self):
  164. """Delete expired metadata."""
  165. self.collection.remove(
  166. {'date_done': {'$lt': self.app.now() - self.expires}},
  167. )
  168. def __reduce__(self, args=(), kwargs={}):
  169. kwargs.update(
  170. dict(expires=self.expires))
  171. return super(MongoBackend, self).__reduce__(args, kwargs)
  172. def _get_database(self):
  173. conn = self._get_connection()
  174. db = conn[self.database_name]
  175. if self.user and self.password:
  176. if not db.authenticate(self.user,
  177. self.password):
  178. raise ImproperlyConfigured(
  179. 'Invalid MongoDB username or password.')
  180. return db
  181. @cached_property
  182. def database(self):
  183. """Get database from MongoDB connection and perform authentication
  184. if necessary."""
  185. return self._get_database()
  186. @cached_property
  187. def collection(self):
  188. """Get the metadata task collection."""
  189. collection = self.database[self.taskmeta_collection]
  190. # Ensure an index on date_done is there, if not process the index
  191. # in the background. Once completed cleanup will be much faster
  192. collection.ensure_index('date_done', background='true')
  193. return collection