base.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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, EagerResult
  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. from celery.exceptions import MaxRetriesExceededError, RetryTaskError
  12. class Task(object):
  13. """A task that can be delayed for execution by the ``celery`` daemon.
  14. All subclasses of :class:`Task` must define the :meth:`run` method,
  15. which is the actual method the ``celery`` daemon executes.
  16. The :meth:`run` method can take use of the default keyword arguments,
  17. as listed in the :meth:`run` documentation.
  18. The :meth:`run` method supports both positional, and keyword arguments.
  19. .. attribute:: name
  20. *REQUIRED* All subclasses of :class:`Task` has to define the
  21. :attr:`name` attribute. This is the name of the task, registered
  22. in the task registry, and passed to :func:`delay_task`.
  23. .. attribute:: type
  24. The type of task, currently this can be ``regular``, or ``periodic``,
  25. however if you want a periodic task, you should subclass
  26. :class:`PeriodicTask` instead.
  27. .. attribute:: routing_key
  28. Override the global default ``routing_key`` for this task.
  29. .. attribute:: exchange
  30. Override the global default ``exchange`` for this task.
  31. .. attribute:: mandatory
  32. If set, the message has mandatory routing. By default the message
  33. is silently dropped by the broker if it can't be routed to a queue.
  34. However - If the message is mandatory, an exception will be raised
  35. instead.
  36. .. attribute:: immediate:
  37. Request immediate delivery. If the message cannot be routed to a
  38. task worker immediately, an exception will be raised. This is
  39. instead of the default behaviour, where the broker will accept and
  40. queue the message, but with no guarantee that the message will ever
  41. be consumed.
  42. .. attribute:: priority:
  43. The message priority. A number from ``0`` to ``9``.
  44. .. attribute:: max_retries
  45. Maximum number of retries before giving up.
  46. .. attribute:: default_retry_delay
  47. Defeault time in seconds before a retry of the task should be
  48. executed. Default is a 1 minute delay.
  49. .. attribute:: ignore_result
  50. Don't store the status and return value. This means you can't
  51. use the :class:`celery.result.AsyncResult` to check if the task is
  52. done, or get its return value. Only use if you need the performance
  53. and is able live without these features. Any exceptions raised will
  54. store the return value/status as usual.
  55. .. attribute:: disable_error_emails
  56. Disable all error e-mails for this task (only applicable if
  57. ``settings.SEND_CELERY_ERROR_EMAILS`` is on.)
  58. :raises NotImplementedError: if the :attr:`name` attribute is not set.
  59. The resulting class is callable, which if called will apply the
  60. :meth:`run` method.
  61. Examples
  62. This is a simple task just logging a message,
  63. >>> from celery.task import tasks, Task
  64. >>> class MyTask(Task):
  65. ...
  66. ... def run(self, some_arg=None, **kwargs):
  67. ... logger = self.get_logger(**kwargs)
  68. ... logger.info("Running MyTask with arg some_arg=%s" %
  69. ... some_arg))
  70. ... return 42
  71. ... tasks.register(MyTask)
  72. You can delay the task using the classmethod :meth:`delay`...
  73. >>> result = MyTask.delay(some_arg="foo")
  74. >>> result.status # after some time
  75. 'DONE'
  76. >>> result.result
  77. 42
  78. ...or using the :func:`delay_task` function, by passing the name of
  79. the task.
  80. >>> from celery.task import delay_task
  81. >>> result = delay_task(MyTask.name, some_arg="foo")
  82. """
  83. name = None
  84. type = "regular"
  85. exchange = None
  86. routing_key = None
  87. immediate = False
  88. mandatory = False
  89. priority = None
  90. ignore_result = False
  91. disable_error_emails = False
  92. max_retries = 3
  93. default_retry_delay = 3 * 60
  94. MaxRetriesExceededError = MaxRetriesExceededError
  95. def __init__(self):
  96. if not self.__class__.name:
  97. self.__class__.name = get_full_cls_name(self.__class__)
  98. def __call__(self, *args, **kwargs):
  99. return self.run(*args, **kwargs)
  100. def run(self, *args, **kwargs):
  101. """The body of the task executed by the worker.
  102. The following standard keyword arguments are reserved and is passed
  103. by the worker if the function/method supports them:
  104. * task_id
  105. Unique id of the currently executing task.
  106. * task_name
  107. Name of the currently executing task (same as :attr:`name`)
  108. * task_retries
  109. How many times the current task has been retried
  110. (an integer starting at ``0``).
  111. * logfile
  112. Name of the worker log file.
  113. * loglevel
  114. The current loglevel, an integer mapping to one of the
  115. following values: ``logging.DEBUG``, ``logging.INFO``,
  116. ``logging.ERROR``, ``logging.CRITICAL``, ``logging.WARNING``,
  117. ``logging.FATAL``.
  118. Additional standard keyword arguments may be added in the future.
  119. To take these default arguments, the task can either list the ones
  120. it wants explicitly or just take an arbitrary list of keyword
  121. arguments (\*\*kwargs).
  122. Example using an explicit list of default arguments to take:
  123. .. code-block:: python
  124. def run(self, x, y, logfile=None, loglevel=None):
  125. self.get_logger(loglevel=loglevel, logfile=logfile)
  126. return x * y
  127. Example taking all default keyword arguments, and any extra arguments
  128. passed on by the caller:
  129. .. code-block:: python
  130. def run(self, x, y, **kwargs): # CORRECT!
  131. logger = self.get_logger(**kwargs)
  132. adjust = kwargs.get("adjust", 0)
  133. return x * y - adjust
  134. """
  135. raise NotImplementedError("Tasks must define a run method.")
  136. def get_logger(self, **kwargs):
  137. """Get process-aware logger object.
  138. See :func:`celery.log.setup_logger`.
  139. """
  140. logfile = kwargs.get("logfile")
  141. loglevel = kwargs.get("loglevel")
  142. return setup_logger(loglevel=loglevel, logfile=logfile)
  143. def get_publisher(self, connect_timeout=AMQP_CONNECTION_TIMEOUT):
  144. """Get a celery task message publisher.
  145. :rtype: :class:`celery.messaging.TaskPublisher`.
  146. Please be sure to close the AMQP connection when you're done
  147. with this object, i.e.:
  148. >>> publisher = self.get_publisher()
  149. >>> # do something with publisher
  150. >>> publisher.connection.close()
  151. """
  152. connection = DjangoBrokerConnection(connect_timeout=connect_timeout)
  153. return TaskPublisher(connection=connection,
  154. exchange=self.exchange,
  155. routing_key=self.routing_key)
  156. def get_consumer(self, connect_timeout=AMQP_CONNECTION_TIMEOUT):
  157. """Get a celery task message consumer.
  158. :rtype: :class:`celery.messaging.TaskConsumer`.
  159. Please be sure to close the AMQP connection when you're done
  160. with this object. i.e.:
  161. >>> consumer = self.get_consumer()
  162. >>> # do something with consumer
  163. >>> consumer.connection.close()
  164. """
  165. connection = DjangoBrokerConnection(connect_timeout=connect_timeout)
  166. return TaskConsumer(connection=connection, exchange=self.exchange,
  167. routing_key=self.routing_key)
  168. @classmethod
  169. def delay(cls, *args, **kwargs):
  170. """Delay this task for execution by the ``celery`` daemon(s).
  171. :param \*args: positional arguments passed on to the task.
  172. :param \*\*kwargs: keyword arguments passed on to the task.
  173. :rtype: :class:`celery.result.AsyncResult`
  174. See :func:`celery.execute.delay_task`.
  175. """
  176. return apply_async(cls, args, kwargs)
  177. @classmethod
  178. def apply_async(cls, args=None, kwargs=None, **options):
  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. :keyword \*\*options: Any keyword arguments to pass on to
  183. :func:`celery.execute.apply_async`.
  184. See :func:`celery.execute.apply_async` for more information.
  185. :rtype: :class:`celery.result.AsyncResult`
  186. """
  187. return apply_async(cls, args, kwargs, **options)
  188. def retry(self, args, kwargs, exc=None, throw=True, **options):
  189. """Retry the task.
  190. :param args: Positional arguments to retry with.
  191. :param kwargs: Keyword arguments to retry with.
  192. :keyword exc: Optional exception to raise instead of
  193. :exc:`MaxRestartsExceededError` when the max restart limit has
  194. been exceeded.
  195. :keyword throw: Do not raise the
  196. :exc:`celery.exceptions.RetryTaskError` exception,
  197. that tells the worker that the task is to be retried.
  198. :keyword countdown: Time in seconds to delay the retry for.
  199. :keyword eta: Explicit time and date to run the retry at (must be a
  200. :class:`datetime.datetime` instance).
  201. :keyword \*\*options: Any extra options to pass on to
  202. meth:`apply_async`. See :func:`celery.execute.apply_async`.
  203. :raises celery.exceptions.RetryTaskError: To tell the worker that the
  204. task has been re-sent for retry. This always happens except if
  205. the ``throw`` keyword argument has been explicitly set
  206. to ``False``.
  207. Example
  208. >>> class TwitterPostStatusTask(Task):
  209. ...
  210. ... def run(self, username, password, message, **kwargs):
  211. ... twitter = Twitter(username, password)
  212. ... try:
  213. ... twitter.post_status(message)
  214. ... except twitter.FailWhale, exc:
  215. ... # Retry in 5 minutes.
  216. ... self.retry([username, password, message], kwargs,
  217. ... countdown=60 * 5, exc=exc)
  218. """
  219. options["retries"] = kwargs.pop("task_retries", 0) + 1
  220. options["task_id"] = kwargs.pop("task_id", None)
  221. options["countdown"] = options.get("countdown",
  222. self.default_retry_delay)
  223. max_exc = exc or self.MaxRetriesExceededError(
  224. "Can't retry %s[%s] args:%s kwargs:%s" % (
  225. self.name, options["task_id"], args, kwargs))
  226. if options["retries"] > self.max_retries:
  227. raise max_exc
  228. # If task was executed eagerly using apply(),
  229. # then the retry must also be executed eagerly.
  230. if kwargs.get("task_is_eager", False):
  231. result = self.apply(args=args, kwargs=kwargs, **options)
  232. if isinstance(result, EagerResult):
  233. # get() propogates any exceptions.
  234. return result.get()
  235. return result
  236. self.apply_async(args=args, kwargs=kwargs, **options)
  237. if throw:
  238. message = "Retry in %d seconds." % options["countdown"]
  239. raise RetryTaskError(message, exc)
  240. def on_retry(self, exc):
  241. """Retry handler.
  242. This is run by the worker when the task is to be retried.
  243. :param exc: The exception sent to :meth:`retry`.
  244. """
  245. pass
  246. def on_failure(self, exc):
  247. """Error handler.
  248. This is run by the worker when the task fails.
  249. :param exc: The exception raised by the task.
  250. """
  251. pass
  252. def on_success(self, retval):
  253. """Success handler.
  254. This is run by the worker when the task executed successfully.
  255. :param retval: The return value of the task.
  256. """
  257. pass
  258. @classmethod
  259. def apply(cls, args=None, kwargs=None, **options):
  260. """Execute this task at once, by blocking until the task
  261. has finished executing.
  262. :param args: positional arguments passed on to the task.
  263. :param kwargs: keyword arguments passed on to the task.
  264. :rtype: :class:`celery.result.EagerResult`
  265. See :func:`celery.execute.apply`.
  266. """
  267. return apply(cls, args, kwargs, **options)
  268. class ExecuteRemoteTask(Task):
  269. """Execute an arbitrary function or object.
  270. *Note* You probably want :func:`execute_remote` instead, which this
  271. is an internal component of.
  272. The object must be pickleable, so you can't use lambdas or functions
  273. defined in the REPL (that is the python shell, or ``ipython``).
  274. """
  275. name = "celery.execute_remote"
  276. def run(self, ser_callable, fargs, fkwargs, **kwargs):
  277. """
  278. :param ser_callable: A pickled function or callable object.
  279. :param fargs: Positional arguments to apply to the function.
  280. :param fkwargs: Keyword arguments to apply to the function.
  281. """
  282. callable_ = pickle.loads(ser_callable)
  283. return callable_(*fargs, **fkwargs)
  284. tasks.register(ExecuteRemoteTask)
  285. class AsynchronousMapTask(Task):
  286. """Task used internally by :func:`dmap_async` and
  287. :meth:`TaskSet.map_async`. """
  288. name = "celery.map_async"
  289. def run(self, serfunc, args, **kwargs):
  290. """The method run by ``celeryd``."""
  291. timeout = kwargs.get("timeout")
  292. return TaskSet.map(pickle.loads(serfunc), args, timeout=timeout)
  293. tasks.register(AsynchronousMapTask)
  294. class TaskSet(object):
  295. """A task containing several subtasks, making it possible
  296. to track how many, or when all of the tasks has been completed.
  297. :param task: The task class or name.
  298. Can either be a fully qualified task name, or a task class.
  299. :param args: A list of args, kwargs pairs.
  300. e.g. ``[[args1, kwargs1], [args2, kwargs2], ..., [argsN, kwargsN]]``
  301. .. attribute:: task_name
  302. The name of the task.
  303. .. attribute:: arguments
  304. The arguments, as passed to the task set constructor.
  305. .. attribute:: total
  306. Total number of tasks in this task set.
  307. Example
  308. >>> from djangofeeds.tasks import RefreshFeedTask
  309. >>> taskset = TaskSet(RefreshFeedTask, args=[
  310. ... [], {"feed_url": "http://cnn.com/rss"},
  311. ... [], {"feed_url": "http://bbc.com/rss"},
  312. ... [], {"feed_url": "http://xkcd.com/rss"}])
  313. >>> taskset_result = taskset.run()
  314. >>> list_of_return_values = taskset.join()
  315. """
  316. def __init__(self, task, args):
  317. try:
  318. task_name = task.name
  319. task_obj = task
  320. except AttributeError:
  321. task_name = task
  322. task_obj = tasks[task_name]
  323. self.task = task_obj
  324. self.task_name = task_name
  325. self.arguments = args
  326. self.total = len(args)
  327. def run(self, connect_timeout=AMQP_CONNECTION_TIMEOUT):
  328. """Run all tasks in the taskset.
  329. :returns: A :class:`celery.result.TaskSetResult` instance.
  330. Example
  331. >>> ts = TaskSet(RefreshFeedTask, [
  332. ... ["http://foo.com/rss", {}],
  333. ... ["http://bar.com/rss", {}],
  334. ... )
  335. >>> result = ts.run()
  336. >>> result.taskset_id
  337. "d2c9b261-8eff-4bfb-8459-1e1b72063514"
  338. >>> result.subtask_ids
  339. ["b4996460-d959-49c8-aeb9-39c530dcde25",
  340. "598d2d18-ab86-45ca-8b4f-0779f5d6a3cb"]
  341. >>> result.waiting()
  342. True
  343. >>> time.sleep(10)
  344. >>> result.ready()
  345. True
  346. >>> result.successful()
  347. True
  348. >>> result.failed()
  349. False
  350. >>> result.join()
  351. [True, True]
  352. """
  353. taskset_id = gen_unique_id()
  354. from celery.conf import ALWAYS_EAGER
  355. if ALWAYS_EAGER:
  356. subtasks = [apply(self.task, args, kwargs)
  357. for args, kwargs in self.arguments]
  358. return TaskSetResult(taskset_id, subtasks)
  359. conn = DjangoBrokerConnection(connect_timeout=connect_timeout)
  360. publisher = TaskPublisher(connection=conn,
  361. exchange=self.task.exchange)
  362. subtasks = [apply_async(self.task, args, kwargs,
  363. taskset_id=taskset_id, publisher=publisher)
  364. for args, kwargs in self.arguments]
  365. publisher.close()
  366. conn.close()
  367. return TaskSetResult(taskset_id, subtasks)
  368. def join(self, timeout=None):
  369. """Gather the results for all of the tasks in the taskset,
  370. and return a list with them ordered by the order of which they
  371. were called.
  372. :keyword timeout: The time in seconds, how long
  373. it will wait for results, before the operation times out.
  374. :raises TimeoutError: if ``timeout`` is not ``None``
  375. and the operation takes longer than ``timeout`` seconds.
  376. If any of the tasks raises an exception, the exception
  377. will be reraised by :meth:`join`.
  378. :returns: list of return values for all tasks in the taskset.
  379. """
  380. return self.run().join(timeout=timeout)
  381. @classmethod
  382. def remote_execute(cls, func, args):
  383. """Apply ``args`` to function by distributing the args to the
  384. celery server(s)."""
  385. pickled = pickle.dumps(func)
  386. arguments = [[[pickled, arg, {}], {}] for arg in args]
  387. return cls(ExecuteRemoteTask, arguments)
  388. @classmethod
  389. def map(cls, func, args, timeout=None):
  390. """Distribute processing of the arguments and collect the results."""
  391. remote_task = cls.remote_execute(func, args)
  392. return remote_task.join(timeout=timeout)
  393. @classmethod
  394. def map_async(cls, func, args, timeout=None):
  395. """Distribute processing of the arguments and collect the results
  396. asynchronously.
  397. :returns: :class:`celery.result.AsyncResult` instance.
  398. """
  399. serfunc = pickle.dumps(func)
  400. return AsynchronousMapTask.delay(serfunc, args, timeout=timeout)
  401. class PeriodicTask(Task):
  402. """A periodic task is a task that behaves like a :manpage:`cron` job.
  403. .. attribute:: run_every
  404. *REQUIRED* Defines how often the task is run (its interval),
  405. it can be either a :class:`datetime.timedelta` object or an
  406. integer specifying the time in seconds.
  407. :raises NotImplementedError: if the :attr:`run_every` attribute is
  408. not defined.
  409. You have to register the periodic task in the task registry.
  410. Example
  411. >>> from celery.task import tasks, PeriodicTask
  412. >>> from datetime import timedelta
  413. >>> class MyPeriodicTask(PeriodicTask):
  414. ... name = "my_periodic_task"
  415. ... run_every = timedelta(seconds=30)
  416. ...
  417. ... def run(self, **kwargs):
  418. ... logger = self.get_logger(**kwargs)
  419. ... logger.info("Running MyPeriodicTask")
  420. >>> tasks.register(MyPeriodicTask)
  421. """
  422. run_every = timedelta(days=1)
  423. type = "periodic"
  424. def __init__(self):
  425. if not self.run_every:
  426. raise NotImplementedError(
  427. "Periodic tasks must have a run_every attribute")
  428. # If run_every is a integer, convert it to timedelta seconds.
  429. # Operate on the original class attribute so anyone accessing
  430. # it directly gets the right value.
  431. if isinstance(self.__class__.run_every, int):
  432. self.__class__.run_every = timedelta(seconds=self.run_every)
  433. super(PeriodicTask, self).__init__()