mongodb.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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.utils import cached_property
  21. from celery import states
  22. from celery.exceptions import ImproperlyConfigured
  23. from celery.utils.timeutils import maybe_timedelta
  24. from .base import BaseDictBackend
  25. class Bunch(object):
  26. def __init__(self, **kw):
  27. self.__dict__.update(kw)
  28. class MongoBackend(BaseDictBackend):
  29. mongodb_host = 'localhost'
  30. mongodb_port = 27017
  31. mongodb_user = None
  32. mongodb_password = None
  33. mongodb_database = 'celery'
  34. mongodb_taskmeta_collection = 'celery_taskmeta'
  35. def __init__(self, *args, **kwargs):
  36. """Initialize MongoDB backend instance.
  37. :raises celery.exceptions.ImproperlyConfigured: if
  38. module :mod:`pymongo` is not available.
  39. """
  40. super(MongoBackend, self).__init__(*args, **kwargs)
  41. self.expires = kwargs.get('expires') or maybe_timedelta(
  42. self.app.conf.CELERY_TASK_RESULT_EXPIRES)
  43. if not pymongo:
  44. raise ImproperlyConfigured(
  45. 'You need to install the pymongo library to use the '
  46. 'MongoDB backend.')
  47. config = self.app.conf.get('CELERY_MONGODB_BACKEND_SETTINGS', None)
  48. if config is not None:
  49. if not isinstance(config, dict):
  50. raise ImproperlyConfigured(
  51. 'MongoDB backend settings should be grouped in a dict')
  52. self.mongodb_host = config.get('host', self.mongodb_host)
  53. self.mongodb_port = int(config.get('port', self.mongodb_port))
  54. self.mongodb_user = config.get('user', self.mongodb_user)
  55. self.mongodb_password = config.get(
  56. 'password', self.mongodb_password)
  57. self.mongodb_database = config.get(
  58. 'database', self.mongodb_database)
  59. self.mongodb_taskmeta_collection = config.get(
  60. 'taskmeta_collection', self.mongodb_taskmeta_collection)
  61. self._connection = None
  62. def _get_connection(self):
  63. """Connect to the MongoDB server."""
  64. if self._connection is None:
  65. from pymongo.connection import Connection
  66. # The first pymongo.Connection() argument (host) can be
  67. # a list of ['host:port'] elements or a mongodb connection
  68. # URI. If this is the case, don't use self.mongodb_port
  69. # but let pymongo get the port(s) from the URI instead.
  70. # This enables the use of replica sets and sharding.
  71. # See pymongo.Connection() for more info.
  72. args = [self.mongodb_host]
  73. if isinstance(self.mongodb_host, basestring) \
  74. and not self.mongodb_host.startswith('mongodb://'):
  75. args.append(self.mongodb_port)
  76. self._connection = Connection(*args)
  77. return self._connection
  78. def process_cleanup(self):
  79. if self._connection is not None:
  80. # MongoDB connection will be closed automatically when object
  81. # goes out of scope
  82. self._connection = None
  83. def _store_result(self, task_id, result, status, traceback=None):
  84. """Store return value and status of an executed task."""
  85. meta = {'_id': task_id,
  86. 'status': status,
  87. 'result': Binary(self.encode(result)),
  88. 'date_done': datetime.utcnow(),
  89. 'traceback': Binary(self.encode(traceback)),
  90. 'children': Binary(self.encode(self.current_task_children()))}
  91. self.collection.save(meta, safe=True)
  92. return result
  93. def _get_task_meta_for(self, task_id):
  94. """Get task metadata for a task by id."""
  95. obj = self.collection.find_one({'_id': task_id})
  96. if not obj:
  97. return {'status': states.PENDING, 'result': None}
  98. meta = {
  99. 'task_id': obj['_id'],
  100. 'status': obj['status'],
  101. 'result': self.decode(obj['result']),
  102. 'date_done': obj['date_done'],
  103. 'traceback': self.decode(obj['traceback']),
  104. 'children': self.decode(obj['children']),
  105. }
  106. return meta
  107. def _save_group(self, group_id, result):
  108. """Save the group result."""
  109. meta = {'_id': group_id,
  110. 'result': Binary(self.encode(result)),
  111. 'date_done': datetime.utcnow()}
  112. self.collection.save(meta, safe=True)
  113. return result
  114. def _restore_group(self, group_id):
  115. """Get the result for a group by id."""
  116. obj = self.collection.find_one({'_id': group_id})
  117. if not obj:
  118. return
  119. meta = {
  120. 'task_id': obj['_id'],
  121. 'result': self.decode(obj['result']),
  122. 'date_done': obj['date_done'],
  123. }
  124. return meta
  125. def _delete_group(self, group_id):
  126. """Delete a group by id."""
  127. self.collection.remove({'_id': group_id})
  128. def _forget(self, task_id):
  129. """
  130. Remove result from MongoDB.
  131. :raises celery.exceptions.OperationsError: if the task_id could not be
  132. removed.
  133. """
  134. # By using safe=True, this will wait until it receives a response from
  135. # the server. Likewise, it will raise an OperationsError if the
  136. # response was unable to be completed.
  137. self.collection.remove({'_id': task_id}, safe=True)
  138. def cleanup(self):
  139. """Delete expired metadata."""
  140. self.collection.remove({
  141. 'date_done': {
  142. '$lt': self.app.now() - self.expires,
  143. }
  144. })
  145. def __reduce__(self, args=(), kwargs={}):
  146. kwargs.update(
  147. dict(expires=self.expires))
  148. return super(MongoBackend, self).__reduce__(args, kwargs)
  149. def _get_database(self):
  150. conn = self._get_connection()
  151. db = conn[self.mongodb_database]
  152. if self.mongodb_user and self.mongodb_password:
  153. if not db.authenticate(self.mongodb_user,
  154. self.mongodb_password):
  155. raise ImproperlyConfigured(
  156. 'Invalid MongoDB username or password.')
  157. return db
  158. @cached_property
  159. def database(self):
  160. """Get database from MongoDB connection and perform authentication
  161. if necessary."""
  162. return self._get_database()
  163. @cached_property
  164. def collection(self):
  165. """Get the metadata task collection."""
  166. collection = self.database[self.mongodb_taskmeta_collection]
  167. # Ensure an index on date_done is there, if not process the index
  168. # in the background. Once completed cleanup will be much faster
  169. collection.ensure_index('date_done', background='true')
  170. return collection