mongodb.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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('max_pool_size', self.max_pool_size)
  72. self.options.setdefault('auto_start_request', False)
  73. url = kwargs.get('url')
  74. if url:
  75. # Specifying backend as an URL
  76. self.host = url
  77. def _get_connection(self):
  78. """Connect to the MongoDB server."""
  79. if self._connection is None:
  80. from pymongo import MongoClient
  81. # The first pymongo.Connection() argument (host) can be
  82. # a list of ['host:port'] elements or a mongodb connection
  83. # URI. If this is the case, don't use self.port
  84. # but let pymongo get the port(s) from the URI instead.
  85. # This enables the use of replica sets and sharding.
  86. # See pymongo.Connection() for more info.
  87. url = self.host
  88. if isinstance(url, string_t) \
  89. and not url.startswith('mongodb://'):
  90. url = 'mongodb://{0}:{1}'.format(url, self.port)
  91. if url == 'mongodb://':
  92. url = url + 'localhost'
  93. if detect_environment() != 'default':
  94. self.options['use_greenlets'] = True
  95. self._connection = MongoClient(host=url, **self.options)
  96. return self._connection
  97. def process_cleanup(self):
  98. if self._connection is not None:
  99. # MongoDB connection will be closed automatically when object
  100. # goes out of scope
  101. del(self.collection)
  102. del(self.database)
  103. self._connection = None
  104. def _store_result(self, task_id, result, status,
  105. traceback=None, request=None, **kwargs):
  106. """Store return value and status of an executed task."""
  107. meta = {'_id': task_id,
  108. 'status': status,
  109. 'result': Binary(self.encode(result)),
  110. 'date_done': datetime.utcnow(),
  111. 'traceback': Binary(self.encode(traceback)),
  112. 'children': Binary(self.encode(
  113. self.current_task_children(request),
  114. ))}
  115. self.collection.save(meta)
  116. return result
  117. def _get_task_meta_for(self, task_id):
  118. """Get task metadata for a task by id."""
  119. obj = self.collection.find_one({'_id': task_id})
  120. if not obj:
  121. return {'status': states.PENDING, 'result': None}
  122. meta = {
  123. 'task_id': obj['_id'],
  124. 'status': obj['status'],
  125. 'result': self.decode(obj['result']),
  126. 'date_done': obj['date_done'],
  127. 'traceback': self.decode(obj['traceback']),
  128. 'children': self.decode(obj['children']),
  129. }
  130. return meta
  131. def _save_group(self, group_id, result):
  132. """Save the group result."""
  133. meta = {'_id': group_id,
  134. 'result': Binary(self.encode(result)),
  135. 'date_done': datetime.utcnow()}
  136. self.collection.save(meta)
  137. return result
  138. def _restore_group(self, group_id):
  139. """Get the result for a group by id."""
  140. obj = self.collection.find_one({'_id': group_id})
  141. if not obj:
  142. return
  143. meta = {
  144. 'task_id': obj['_id'],
  145. 'result': self.decode(obj['result']),
  146. 'date_done': obj['date_done'],
  147. }
  148. return meta
  149. def _delete_group(self, group_id):
  150. """Delete a group by id."""
  151. self.collection.remove({'_id': group_id})
  152. def _forget(self, task_id):
  153. """
  154. Remove result from MongoDB.
  155. :raises celery.exceptions.OperationsError: if the task_id could not be
  156. removed.
  157. """
  158. # By using safe=True, this will wait until it receives a response from
  159. # the server. Likewise, it will raise an OperationsError if the
  160. # response was unable to be completed.
  161. self.collection.remove({'_id': task_id})
  162. def cleanup(self):
  163. """Delete expired metadata."""
  164. self.collection.remove(
  165. {'date_done': {'$lt': self.app.now() - self.expires}},
  166. )
  167. def __reduce__(self, args=(), kwargs={}):
  168. kwargs.update(
  169. dict(expires=self.expires))
  170. return super(MongoBackend, self).__reduce__(args, kwargs)
  171. def _get_database(self):
  172. conn = self._get_connection()
  173. db = conn[self.database_name]
  174. if self.user and self.password:
  175. if not db.authenticate(self.user,
  176. self.password):
  177. raise ImproperlyConfigured(
  178. 'Invalid MongoDB username or password.')
  179. return db
  180. @cached_property
  181. def database(self):
  182. """Get database from MongoDB connection and perform authentication
  183. if necessary."""
  184. return self._get_database()
  185. @cached_property
  186. def collection(self):
  187. """Get the metadata task collection."""
  188. collection = self.database[self.taskmeta_collection]
  189. # Ensure an index on date_done is there, if not process the index
  190. # in the background. Once completed cleanup will be much faster
  191. collection.ensure_index('date_done', background='true')
  192. return collection