task.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. """
  2. Working with tasks and task sets.
  3. """
  4. from carrot.connection import DjangoAMQPConnection
  5. from celery.log import setup_logger
  6. from celery.registry import tasks
  7. from celery.messaging import TaskPublisher, TaskConsumer
  8. from celery.models import TaskMeta
  9. from django.core.cache import cache
  10. from datetime import timedelta
  11. from celery.backends import default_backend
  12. from celery.datastructures import PositionQueue
  13. from celery.result import AsyncResult
  14. from celery.timer import TimeoutTimer
  15. import uuid
  16. import pickle
  17. def apply_async(task, args=None, kwargs=None, routing_key=None,
  18. immediate=None, mandatory=None, connect_timeout=None, priority=None):
  19. """Run a task asynchronously by the celery daemon(s).
  20. :param task: The task to run (a callable object, or a :class:`Task`
  21. instance
  22. :param args: The positional arguments to pass on to the task (a ``list``).
  23. :param kwargs: The keyword arguments to pass on to the task (a ``dict``)
  24. :keyword routing_key: The routing key used to route the task to a worker
  25. server.
  26. :keyword immediate: Request immediate delivery. Will raise an exception
  27. if the task cannot be routed to a worker immediately.
  28. :keyword mandatory: Mandatory routing. Raises an exception if there's
  29. no running workers able to take on this task.
  30. :keyword connect_timeout: The timeout in seconds, before we give up
  31. on establishing a connection to the AMQP server.
  32. :keyword priority: The task priority, a number between ``0`` and ``9``.
  33. """
  34. if not args:
  35. args = []
  36. if not kwargs:
  37. kwargs = []
  38. message_opts = {"routing_key": routing_key,
  39. "immediate": immediate,
  40. "mandatory": mandatory,
  41. "priority": priority}
  42. for option_name, option_value in message_opts.items():
  43. message_opts[option_name] = getattr(task, option_name, option_value)
  44. amqp_connection = DjangoAMQPConnection(connect_timeout=connect_timeout)
  45. publisher = TaskPublisher(connection=amqp_connection)
  46. task_id = publisher.delay_task(task.name, args, kwargs, **message_opts)
  47. amqp_connection.close()
  48. return AsyncResult(task_id)
  49. def delay_task(task_name, *args, **kwargs):
  50. """Delay a task for execution by the ``celery`` daemon.
  51. :param task_name: the name of a task registered in the task registry.
  52. :param \*args: positional arguments to pass on to the task.
  53. :param \*\*kwargs: keyword arguments to pass on to the task.
  54. :raises celery.registry.NotRegistered: exception if no such task
  55. has been registered in the task registry.
  56. :rtype: :class:`celery.result.AsyncResult`.
  57. Example
  58. >>> r = delay_task("update_record", name="George Constanza", age=32)
  59. >>> r.ready()
  60. True
  61. >>> r.result
  62. "Record was updated"
  63. """
  64. if task_name not in tasks:
  65. raise tasks.NotRegistered(
  66. "Task with name %s not registered in the task registry." % (
  67. task_name))
  68. task = tasks[task_name]
  69. return apply_async(task, args, kwargs)
  70. def discard_all():
  71. """Discard all waiting tasks.
  72. This will ignore all tasks waiting for execution, and they will
  73. be deleted from the messaging server.
  74. :returns: the number of tasks discarded.
  75. :rtype: int
  76. """
  77. amqp_connection = DjangoAMQPConnection()
  78. consumer = TaskConsumer(connection=amqp_connection)
  79. discarded_count = consumer.discard_all()
  80. amqp_connection.close()
  81. return discarded_count
  82. def is_done(task_id):
  83. """Returns ``True`` if task with ``task_id`` has been executed.
  84. :rtype: bool
  85. """
  86. return default_backend.is_done(task_id)
  87. class Task(object):
  88. """A task that can be delayed for execution by the ``celery`` daemon.
  89. All subclasses of :class:`Task` must define the :meth:`run` method,
  90. which is the actual method the ``celery`` daemon executes.
  91. The :meth:`run` method supports both positional, and keyword arguments.
  92. .. attribute:: name
  93. *REQUIRED* All subclasses of :class:`Task` has to define the
  94. :attr:`name` attribute. This is the name of the task, registered
  95. in the task registry, and passed to :func:`delay_task`.
  96. .. attribute:: type
  97. The type of task, currently this can be ``regular``, or ``periodic``,
  98. however if you want a periodic task, you should subclass
  99. :class:`PeriodicTask` instead.
  100. :raises NotImplementedError: if the :attr:`name` attribute is not set.
  101. The resulting class is callable, which if called will apply the
  102. :meth:`run` method.
  103. Examples
  104. This is a simple task just logging a message,
  105. >>> from celery.task import tasks, Task
  106. >>> class MyTask(Task):
  107. ... name = "mytask"
  108. ...
  109. ... def run(self, some_arg=None, **kwargs):
  110. ... logger = self.get_logger(**kwargs)
  111. ... logger.info("Running MyTask with arg some_arg=%s" %
  112. ... some_arg))
  113. ... return 42
  114. ... tasks.register(MyTask)
  115. You can delay the task using the classmethod :meth:`delay`...
  116. >>> result = MyTask.delay(some_arg="foo")
  117. >>> result.status # after some time
  118. 'DONE'
  119. >>> result.result
  120. 42
  121. ...or using the :func:`delay_task` function, by passing the name of
  122. the task.
  123. >>> from celery.task import delay_task
  124. >>> result = delay_task(MyTask.name, some_arg="foo")
  125. """
  126. name = None
  127. type = "regular"
  128. max_retries = 0 # unlimited
  129. retry_interval = timedelta(seconds=2)
  130. auto_retry = False
  131. routing_key = None
  132. immediate = False
  133. mandatory = False
  134. def __init__(self):
  135. if not self.name:
  136. raise NotImplementedError("Tasks must define a name attribute.")
  137. def __call__(self, *args, **kwargs):
  138. return self.run(*args, **kwargs)
  139. def run(self, *args, **kwargs):
  140. """*REQUIRED* The actual task.
  141. All subclasses of :class:`Task` must define the run method.
  142. :raises NotImplementedError: by default, so you have to override
  143. this method in your subclass.
  144. """
  145. raise NotImplementedError("Tasks must define a run method.")
  146. def get_logger(self, **kwargs):
  147. """Get process-aware logger object.
  148. See :func:`celery.log.setup_logger`.
  149. """
  150. return setup_logger(**kwargs)
  151. def get_publisher(self):
  152. """Get a celery task message publisher.
  153. :rtype: :class:`celery.messaging.TaskPublisher`.
  154. Please be sure to close the AMQP connection when you're done
  155. with this object, i.e.:
  156. >>> publisher = self.get_publisher()
  157. >>> # do something with publisher
  158. >>> publisher.connection.close()
  159. """
  160. return TaskPublisher(connection=DjangoAMQPConnection())
  161. def get_consumer(self):
  162. """Get a celery task message consumer.
  163. :rtype: :class:`celery.messaging.TaskConsumer`.
  164. Please be sure to close the AMQP connection when you're done
  165. with this object. i.e.:
  166. >>> consumer = self.get_consumer()
  167. >>> # do something with consumer
  168. >>> consumer.connection.close()
  169. """
  170. return TaskConsumer(connection=DjangoAMQPConnection())
  171. def requeue(self, task_id, args, kwargs):
  172. publisher = self.get_publisher()
  173. publisher.requeue_task(self.name, task_id, args, kwargs)
  174. publisher.connection.close()
  175. def retry(self, task_id, args, kwargs):
  176. retry_queue.put(self.name, task_id, args, kwargs)
  177. @classmethod
  178. def delay(cls, *args, **kwargs):
  179. """Delay this task for execution by the ``celery`` daemon(s).
  180. :param \*args: positional arguments passed on to the task.
  181. :param \*\*kwargs: keyword arguments passed on to the task.
  182. :rtype: :class:`celery.result.AsyncResult`
  183. See :func:`delay_task`.
  184. """
  185. return apply_async(cls, args, kwargs)
  186. @classmethod
  187. def apply_async(cls, args=None, kwargs=None, **options):
  188. """Delay this task for execution by the ``celery`` daemon(s).
  189. :param args: positional arguments passed on to the task.
  190. :param kwargs: keyword arguments passed on to the task.
  191. :rtype: :class:`celery.result.AsyncResult`
  192. See :func:`apply_async`.
  193. """
  194. return apply_async(cls, args, kwargs, **options)
  195. class TaskSet(object):
  196. """A task containing several subtasks, making it possible
  197. to track how many, or when all of the tasks has been completed.
  198. :param task: The task class or name.
  199. Can either be a fully qualified task name, or a task class.
  200. :param args: A list of args, kwargs pairs.
  201. e.g. ``[[args1, kwargs1], [args2, kwargs2], ..., [argsN, kwargsN]]``
  202. .. attribute:: task_name
  203. The name of the task.
  204. .. attribute:: arguments
  205. The arguments, as passed to the task set constructor.
  206. .. attribute:: total
  207. Total number of tasks in this task set.
  208. Example
  209. >>> from djangofeeds.tasks import RefreshFeedTask
  210. >>> taskset = TaskSet(RefreshFeedTask, args=[
  211. ... [], {"feed_url": "http://cnn.com/rss"},
  212. ... [], {"feed_url": "http://bbc.com/rss"},
  213. ... [], {"feed_url": "http://xkcd.com/rss"}])
  214. >>> taskset_id, subtask_ids = taskset.run()
  215. >>> list_of_return_values = taskset.join()
  216. """
  217. def __init__(self, task, args):
  218. try:
  219. task_name = task.name
  220. except AttributeError:
  221. task_name = task
  222. self.task_name = task_name
  223. self.arguments = args
  224. self.total = len(args)
  225. def run(self):
  226. """Run all tasks in the taskset.
  227. :returns: A tuple containing the taskset id, and a list
  228. of subtask ids.
  229. :rtype: tuple
  230. Example
  231. >>> ts = RefreshFeeds([
  232. ... ["http://foo.com/rss", {}],
  233. ... ["http://bar.com/rss", {}],
  234. ... )
  235. >>> taskset_id, subtask_ids = ts.run()
  236. >>> taskset_id
  237. "d2c9b261-8eff-4bfb-8459-1e1b72063514"
  238. >>> subtask_ids
  239. ["b4996460-d959-49c8-aeb9-39c530dcde25",
  240. "598d2d18-ab86-45ca-8b4f-0779f5d6a3cb"]
  241. >>> time.sleep(10)
  242. >>> is_done(taskset_id)
  243. True
  244. """
  245. taskset_id = str(uuid.uuid4())
  246. amqp_connection = DjangoAMQPConnection()
  247. publisher = TaskPublisher(connection=amqp_connection)
  248. subtask_ids = []
  249. for arg, kwarg in self.arguments:
  250. subtask_id = publisher.delay_task_in_set(task_name=self.task_name,
  251. taskset_id=taskset_id,
  252. task_args=arg,
  253. task_kwargs=kwarg)
  254. subtask_ids.append(subtask_id)
  255. amqp_connection.close()
  256. return taskset_id, subtask_ids
  257. def iterate(self):
  258. """Iterate over the results returned after calling :meth:`run`.
  259. If any of the tasks raises an exception, the exception will
  260. be re-raised.
  261. """
  262. taskset_id, subtask_ids = self.run()
  263. results = dict([(task_id, AsyncResult(task_id))
  264. for task_id in subtask_ids])
  265. while results:
  266. for task_id, pending_result in results.items():
  267. if pending_result.status == "DONE":
  268. del(results[task_id])
  269. yield pending_result.result
  270. elif pending_result.status == "FAILURE":
  271. raise pending_result.result
  272. def join(self, timeout=None):
  273. """Gather the results for all of the tasks in the taskset,
  274. and return a list with them ordered by the order of which they
  275. were called.
  276. :keyword timeout: The time in seconds, how long
  277. it will wait for results, before the operation times out.
  278. :raises celery.timer.TimeoutError: if ``timeout`` is not ``None``
  279. and the operation takes longer than ``timeout`` seconds.
  280. If any of the tasks raises an exception, the exception
  281. will be reraised by :meth:`join`.
  282. :returns: list of return values for all tasks in the taskset.
  283. """
  284. timeout_timer = TimeoutTimer(timeout) # Timeout timer starts here.
  285. taskset_id, subtask_ids = self.run()
  286. pending_results = map(AsyncResult, subtask_ids)
  287. results = PositionQueue(length=len(subtask_ids))
  288. while True:
  289. for position, pending_result in enumerate(pending_results):
  290. if pending_result.status == "DONE":
  291. results[position] = pending_result.result
  292. elif pending_result.status == "FAILURE":
  293. raise pending_result.result
  294. if results.full():
  295. # Make list copy, so the returned type is not a position
  296. # queue.
  297. return list(results)
  298. # This raises TimeoutError when timed out.
  299. timeout_timer.tick()
  300. @classmethod
  301. def remote_execute(cls, func, args):
  302. """Apply ``args`` to function by distributing the args to the
  303. celery server(s)."""
  304. pickled = pickle.dumps(func)
  305. arguments = [[[pickled, arg, {}], {}] for arg in args]
  306. return cls(ExecuteRemoteTask, arguments)
  307. @classmethod
  308. def map(cls, func, args, timeout=None):
  309. """Distribute processing of the arguments and collect the results."""
  310. remote_task = cls.remote_execute(func, args)
  311. return remote_task.join(timeout=timeout)
  312. @classmethod
  313. def map_async(cls, func, args, timeout=None):
  314. """Distribute processing of the arguments and collect the results
  315. asynchronously.
  316. :returns: :class:`celery.result.AsyncResult` instance.
  317. """
  318. serfunc = pickle.dumps(func)
  319. return AsynchronousMapTask.delay(serfunc, args, timeout=timeout)
  320. def dmap(func, args, timeout=None):
  321. """Distribute processing of the arguments and collect the results.
  322. Example
  323. >>> from celery.task import map
  324. >>> import operator
  325. >>> dmap(operator.add, [[2, 2], [4, 4], [8, 8]])
  326. [4, 8, 16]
  327. """
  328. return TaskSet.map(func, args, timeout=timeout)
  329. class AsynchronousMapTask(Task):
  330. """Task used internally by :func:`dmap_async` and
  331. :meth:`TaskSet.map_async`. """
  332. name = "celery.map_async"
  333. def run(self, serfunc, args, **kwargs):
  334. timeout = kwargs.get("timeout")
  335. return TaskSet.map(pickle.loads(serfunc), args, timeout=timeout)
  336. tasks.register(AsynchronousMapTask)
  337. def dmap_async(func, args, timeout=None):
  338. """Distribute processing of the arguments and collect the results
  339. asynchronously.
  340. :returns: :class:`celery.result.AsyncResult` object.
  341. Example
  342. >>> from celery.task import dmap_async
  343. >>> import operator
  344. >>> presult = dmap_async(operator.add, [[2, 2], [4, 4], [8, 8]])
  345. >>> presult
  346. <AsyncResult: 373550e8-b9a0-4666-bc61-ace01fa4f91d>
  347. >>> presult.status
  348. 'DONE'
  349. >>> presult.result
  350. [4, 8, 16]
  351. """
  352. return TaskSet.map_async(func, args, timeout=timeout)
  353. class PeriodicTask(Task):
  354. """A periodic task is a task that behaves like a :manpage:`cron` job.
  355. .. attribute:: run_every
  356. *REQUIRED* Defines how often the task is run (its interval),
  357. it can be either a :class:`datetime.timedelta` object or an
  358. integer specifying the time in seconds.
  359. :raises NotImplementedError: if the :attr:`run_every` attribute is
  360. not defined.
  361. You have to register the periodic task in the task registry.
  362. Example
  363. >>> from celery.task import tasks, PeriodicTask
  364. >>> from datetime import timedelta
  365. >>> class MyPeriodicTask(PeriodicTask):
  366. ... name = "my_periodic_task"
  367. ... run_every = timedelta(seconds=30)
  368. ...
  369. ... def run(self, **kwargs):
  370. ... logger = self.get_logger(**kwargs)
  371. ... logger.info("Running MyPeriodicTask")
  372. >>> tasks.register(MyPeriodicTask)
  373. """
  374. run_every = timedelta(days=1)
  375. type = "periodic"
  376. def __init__(self):
  377. if not self.run_every:
  378. raise NotImplementedError(
  379. "Periodic tasks must have a run_every attribute")
  380. # If run_every is a integer, convert it to timedelta seconds.
  381. if isinstance(self.run_every, int):
  382. self.run_every = timedelta(seconds=self.run_every)
  383. super(PeriodicTask, self).__init__()
  384. class ExecuteRemoteTask(Task):
  385. """Execute an arbitrary function or object.
  386. *Note* You probably want :func:`execute_remote` instead, which this
  387. is an internal component of.
  388. The object must be pickleable, so you can't use lambdas or functions
  389. defined in the REPL (that is the python shell, or ``ipython``).
  390. """
  391. name = "celery.execute_remote"
  392. def run(self, ser_callable, fargs, fkwargs, **kwargs):
  393. """
  394. :param ser_callable: A pickled function or callable object.
  395. :param fargs: Positional arguments to apply to the function.
  396. :param fkwargs: Keyword arguments to apply to the function.
  397. """
  398. callable_ = pickle.loads(ser_callable)
  399. return callable_(*fargs, **fkwargs)
  400. tasks.register(ExecuteRemoteTask)
  401. def execute_remote(func, *args, **kwargs):
  402. """Execute arbitrary function/object remotely.
  403. :param func: A callable function or object.
  404. :param \*args: Positional arguments to apply to the function.
  405. :param \*\*kwargs: Keyword arguments to apply to the function.
  406. The object must be picklable, so you can't use lambdas or functions
  407. defined in the REPL (the objects must have an associated module).
  408. :returns: class:`celery.result.AsyncResult`.
  409. """
  410. return ExecuteRemoteTask.delay(pickle.dumps(func), args, kwargs)
  411. class DeleteExpiredTaskMetaTask(PeriodicTask):
  412. """A periodic task that deletes expired task metadata every day.
  413. This runs the current backend's
  414. :meth:`celery.backends.base.BaseBackend.cleanup` method.
  415. """
  416. name = "celery.delete_expired_task_meta"
  417. run_every = timedelta(days=1)
  418. def run(self, **kwargs):
  419. logger = self.get_logger(**kwargs)
  420. logger.info("Deleting expired task meta objects...")
  421. default_backend.cleanup()
  422. tasks.register(DeleteExpiredTaskMetaTask)