base.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. from carrot.connection import DjangoBrokerConnection
  2. from celery.conf import AMQP_CONNECTION_TIMEOUT
  3. from celery.messaging import TaskPublisher, TaskConsumer
  4. from celery.log import setup_logger
  5. from celery.result import TaskSetResult
  6. from celery.execute import apply_async, delay_task, apply
  7. from celery.utils import gen_unique_id, get_full_cls_name
  8. from datetime import timedelta
  9. from celery.registry import tasks
  10. from celery.serialization import pickle
  11. class Task(object):
  12. """A task that can be delayed for execution by the ``celery`` daemon.
  13. All subclasses of :class:`Task` must define the :meth:`run` method,
  14. which is the actual method the ``celery`` daemon executes.
  15. The :meth:`run` method supports both positional, and keyword arguments.
  16. .. attribute:: name
  17. *REQUIRED* All subclasses of :class:`Task` has to define the
  18. :attr:`name` attribute. This is the name of the task, registered
  19. in the task registry, and passed to :func:`delay_task`.
  20. .. attribute:: type
  21. The type of task, currently this can be ``regular``, or ``periodic``,
  22. however if you want a periodic task, you should subclass
  23. :class:`PeriodicTask` instead.
  24. .. attribute:: routing_key
  25. Override the global default ``routing_key`` for this task.
  26. .. attribute:: exchange
  27. Override the global default ``exchange`` for this task.
  28. .. attribute:: mandatory
  29. If set, the message has mandatory routing. By default the message
  30. is silently dropped by the broker if it can't be routed to a queue.
  31. However - If the message is mandatory, an exception will be raised
  32. instead.
  33. .. attribute:: immediate:
  34. Request immediate delivery. If the message cannot be routed to a
  35. task worker immediately, an exception will be raised. This is
  36. instead of the default behaviour, where the broker will accept and
  37. queue the message, but with no guarantee that the message will ever
  38. be consumed.
  39. .. attribute:: priority:
  40. The message priority. A number from ``0`` to ``9``.
  41. .. attribute:: ignore_result
  42. Don't store the status and return value. This means you can't
  43. use the :class:`celery.result.AsyncResult` to check if the task is
  44. done, or get its return value. Only use if you need the performance
  45. and is able live without these features. Any exceptions raised will
  46. store the return value/status as usual.
  47. .. attribute:: disable_error_emails
  48. Disable all error e-mails for this task (only applicable if
  49. ``settings.SEND_CELERY_ERROR_EMAILS`` is on.)
  50. :raises NotImplementedError: if the :attr:`name` attribute is not set.
  51. The resulting class is callable, which if called will apply the
  52. :meth:`run` method.
  53. Examples
  54. This is a simple task just logging a message,
  55. >>> from celery.task import tasks, Task
  56. >>> class MyTask(Task):
  57. ...
  58. ... def run(self, some_arg=None, **kwargs):
  59. ... logger = self.get_logger(**kwargs)
  60. ... logger.info("Running MyTask with arg some_arg=%s" %
  61. ... some_arg))
  62. ... return 42
  63. ... tasks.register(MyTask)
  64. You can delay the task using the classmethod :meth:`delay`...
  65. >>> result = MyTask.delay(some_arg="foo")
  66. >>> result.status # after some time
  67. 'DONE'
  68. >>> result.result
  69. 42
  70. ...or using the :func:`delay_task` function, by passing the name of
  71. the task.
  72. >>> from celery.task import delay_task
  73. >>> result = delay_task(MyTask.name, some_arg="foo")
  74. """
  75. name = None
  76. type = "regular"
  77. exchange = None
  78. routing_key = None
  79. immediate = False
  80. mandatory = False
  81. priority = None
  82. ignore_result = False
  83. disable_error_emails = False
  84. def __init__(self):
  85. if not self.__class__.name:
  86. self.__class__.name = get_full_cls_name(self.__class__)
  87. def __call__(self, *args, **kwargs):
  88. return self.run(*args, **kwargs)
  89. def run(self, *args, **kwargs):
  90. """*REQUIRED* The actual task.
  91. All subclasses of :class:`Task` must define the run method.
  92. :raises NotImplementedError: by default, so you have to override
  93. this method in your subclass.
  94. """
  95. raise NotImplementedError("Tasks must define a run method.")
  96. def get_logger(self, **kwargs):
  97. """Get process-aware logger object.
  98. See :func:`celery.log.setup_logger`.
  99. """
  100. return setup_logger(**kwargs)
  101. def get_publisher(self, connect_timeout=AMQP_CONNECTION_TIMEOUT):
  102. """Get a celery task message publisher.
  103. :rtype: :class:`celery.messaging.TaskPublisher`.
  104. Please be sure to close the AMQP connection when you're done
  105. with this object, i.e.:
  106. >>> publisher = self.get_publisher()
  107. >>> # do something with publisher
  108. >>> publisher.connection.close()
  109. """
  110. connection = DjangoBrokerConnection(connect_timeout=connect_timeout)
  111. return TaskPublisher(connection=connection,
  112. exchange=self.exchange,
  113. routing_key=self.routing_key)
  114. def get_consumer(self, connect_timeout=AMQP_CONNECTION_TIMEOUT):
  115. """Get a celery task message consumer.
  116. :rtype: :class:`celery.messaging.TaskConsumer`.
  117. Please be sure to close the AMQP connection when you're done
  118. with this object. i.e.:
  119. >>> consumer = self.get_consumer()
  120. >>> # do something with consumer
  121. >>> consumer.connection.close()
  122. """
  123. connection = DjangoBrokerConnection(connect_timeout=connect_timeout)
  124. return TaskConsumer(connection=connection, exchange=self.exchange,
  125. routing_key=self.routing_key)
  126. @classmethod
  127. def delay(cls, *args, **kwargs):
  128. """Delay this task for execution by the ``celery`` daemon(s).
  129. :param \*args: positional arguments passed on to the task.
  130. :param \*\*kwargs: keyword arguments passed on to the task.
  131. :rtype: :class:`celery.result.AsyncResult`
  132. See :func:`celery.execute.delay_task`.
  133. """
  134. return apply_async(cls, args, kwargs)
  135. @classmethod
  136. def apply_async(cls, args=None, kwargs=None, **options):
  137. """Delay this task for execution by the ``celery`` daemon(s).
  138. :param args: positional arguments passed on to the task.
  139. :param kwargs: keyword arguments passed on to the task.
  140. :rtype: :class:`celery.result.AsyncResult`
  141. See :func:`celery.execute.apply_async`.
  142. """
  143. return apply_async(cls, args, kwargs, **options)
  144. @classmethod
  145. def apply(cls, args=None, kwargs=None, **options):
  146. """Execute this task at once, by blocking until the task
  147. has finished executing.
  148. :param args: positional arguments passed on to the task.
  149. :param kwargs: keyword arguments passed on to the task.
  150. :rtype: :class:`celery.result.EagerResult`
  151. See :func:`celery.execute.apply`.
  152. """
  153. return apply(cls, args, kwargs, **options)
  154. class ExecuteRemoteTask(Task):
  155. """Execute an arbitrary function or object.
  156. *Note* You probably want :func:`execute_remote` instead, which this
  157. is an internal component of.
  158. The object must be pickleable, so you can't use lambdas or functions
  159. defined in the REPL (that is the python shell, or ``ipython``).
  160. """
  161. name = "celery.execute_remote"
  162. def run(self, ser_callable, fargs, fkwargs, **kwargs):
  163. """
  164. :param ser_callable: A pickled function or callable object.
  165. :param fargs: Positional arguments to apply to the function.
  166. :param fkwargs: Keyword arguments to apply to the function.
  167. """
  168. callable_ = pickle.loads(ser_callable)
  169. return callable_(*fargs, **fkwargs)
  170. tasks.register(ExecuteRemoteTask)
  171. class AsynchronousMapTask(Task):
  172. """Task used internally by :func:`dmap_async` and
  173. :meth:`TaskSet.map_async`. """
  174. name = "celery.map_async"
  175. def run(self, serfunc, args, **kwargs):
  176. """The method run by ``celeryd``."""
  177. timeout = kwargs.get("timeout")
  178. return TaskSet.map(pickle.loads(serfunc), args, timeout=timeout)
  179. tasks.register(AsynchronousMapTask)
  180. class TaskSet(object):
  181. """A task containing several subtasks, making it possible
  182. to track how many, or when all of the tasks has been completed.
  183. :param task: The task class or name.
  184. Can either be a fully qualified task name, or a task class.
  185. :param args: A list of args, kwargs pairs.
  186. e.g. ``[[args1, kwargs1], [args2, kwargs2], ..., [argsN, kwargsN]]``
  187. .. attribute:: task_name
  188. The name of the task.
  189. .. attribute:: arguments
  190. The arguments, as passed to the task set constructor.
  191. .. attribute:: total
  192. Total number of tasks in this task set.
  193. Example
  194. >>> from djangofeeds.tasks import RefreshFeedTask
  195. >>> taskset = TaskSet(RefreshFeedTask, args=[
  196. ... [], {"feed_url": "http://cnn.com/rss"},
  197. ... [], {"feed_url": "http://bbc.com/rss"},
  198. ... [], {"feed_url": "http://xkcd.com/rss"}])
  199. >>> taskset_result = taskset.run()
  200. >>> list_of_return_values = taskset.join()
  201. """
  202. def __init__(self, task, args):
  203. try:
  204. task_name = task.name
  205. task_obj = task
  206. except AttributeError:
  207. task_name = task
  208. task_obj = tasks[task_name]
  209. self.task = task_obj
  210. self.task_name = task_name
  211. self.arguments = args
  212. self.total = len(args)
  213. def run(self, connect_timeout=AMQP_CONNECTION_TIMEOUT):
  214. """Run all tasks in the taskset.
  215. :returns: A :class:`celery.result.TaskSetResult` instance.
  216. Example
  217. >>> ts = TaskSet(RefreshFeedTask, [
  218. ... ["http://foo.com/rss", {}],
  219. ... ["http://bar.com/rss", {}],
  220. ... )
  221. >>> result = ts.run()
  222. >>> result.taskset_id
  223. "d2c9b261-8eff-4bfb-8459-1e1b72063514"
  224. >>> result.subtask_ids
  225. ["b4996460-d959-49c8-aeb9-39c530dcde25",
  226. "598d2d18-ab86-45ca-8b4f-0779f5d6a3cb"]
  227. >>> result.waiting()
  228. True
  229. >>> time.sleep(10)
  230. >>> result.ready()
  231. True
  232. >>> result.successful()
  233. True
  234. >>> result.failed()
  235. False
  236. >>> result.join()
  237. [True, True]
  238. """
  239. taskset_id = gen_unique_id()
  240. from celery.conf import ALWAYS_EAGER
  241. if ALWAYS_EAGER:
  242. subtasks = [apply(self.task, args, kwargs)
  243. for args, kwargs in self.arguments]
  244. return TaskSetResult(taskset_id, subtasks)
  245. conn = DjangoBrokerConnection(connect_timeout=connect_timeout)
  246. publisher = TaskPublisher(connection=conn,
  247. exchange=self.task.exchange)
  248. subtasks = [apply_async(self.task, args, kwargs,
  249. taskset_id=taskset_id, publisher=publisher)
  250. for args, kwargs in self.arguments]
  251. publisher.close()
  252. conn.close()
  253. return TaskSetResult(taskset_id, subtasks)
  254. def join(self, timeout=None):
  255. """Gather the results for all of the tasks in the taskset,
  256. and return a list with them ordered by the order of which they
  257. were called.
  258. :keyword timeout: The time in seconds, how long
  259. it will wait for results, before the operation times out.
  260. :raises TimeoutError: if ``timeout`` is not ``None``
  261. and the operation takes longer than ``timeout`` seconds.
  262. If any of the tasks raises an exception, the exception
  263. will be reraised by :meth:`join`.
  264. :returns: list of return values for all tasks in the taskset.
  265. """
  266. return self.run().join(timeout=timeout)
  267. @classmethod
  268. def remote_execute(cls, func, args):
  269. """Apply ``args`` to function by distributing the args to the
  270. celery server(s)."""
  271. pickled = pickle.dumps(func)
  272. arguments = [[[pickled, arg, {}], {}] for arg in args]
  273. return cls(ExecuteRemoteTask, arguments)
  274. @classmethod
  275. def map(cls, func, args, timeout=None):
  276. """Distribute processing of the arguments and collect the results."""
  277. remote_task = cls.remote_execute(func, args)
  278. return remote_task.join(timeout=timeout)
  279. @classmethod
  280. def map_async(cls, func, args, timeout=None):
  281. """Distribute processing of the arguments and collect the results
  282. asynchronously.
  283. :returns: :class:`celery.result.AsyncResult` instance.
  284. """
  285. serfunc = pickle.dumps(func)
  286. return AsynchronousMapTask.delay(serfunc, args, timeout=timeout)
  287. class PeriodicTask(Task):
  288. """A periodic task is a task that behaves like a :manpage:`cron` job.
  289. .. attribute:: run_every
  290. *REQUIRED* Defines how often the task is run (its interval),
  291. it can be either a :class:`datetime.timedelta` object or an
  292. integer specifying the time in seconds.
  293. :raises NotImplementedError: if the :attr:`run_every` attribute is
  294. not defined.
  295. You have to register the periodic task in the task registry.
  296. Example
  297. >>> from celery.task import tasks, PeriodicTask
  298. >>> from datetime import timedelta
  299. >>> class MyPeriodicTask(PeriodicTask):
  300. ... name = "my_periodic_task"
  301. ... run_every = timedelta(seconds=30)
  302. ...
  303. ... def run(self, **kwargs):
  304. ... logger = self.get_logger(**kwargs)
  305. ... logger.info("Running MyPeriodicTask")
  306. >>> tasks.register(MyPeriodicTask)
  307. """
  308. run_every = timedelta(days=1)
  309. type = "periodic"
  310. def __init__(self):
  311. if not self.run_every:
  312. raise NotImplementedError(
  313. "Periodic tasks must have a run_every attribute")
  314. # If run_every is a integer, convert it to timedelta seconds.
  315. if isinstance(self.run_every, int):
  316. self.run_every = timedelta(seconds=self.run_every)
  317. super(PeriodicTask, self).__init__()