whatsnew-2.6.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  1. .. _whatsnew-2.6:
  2. ==========================
  3. What's new in Celery 2.6
  4. ==========================
  5. Celery aims to be a flexible and reliable, best-of-breed solution
  6. to process vast amounts of messages in a distributed fashion, while
  7. providing operations with the tools to maintain such a system.
  8. Celery has a large and diverse community of users and contributors,
  9. you should come join us :ref:`on IRC <irc-channel>`
  10. or :ref:`our mailing-list <mailing-list>`.
  11. To read more about Celery you should visit our `website`_.
  12. While this version is backward compatible with previous versions
  13. it is important that you read the following section.
  14. If you use Celery in combination with Django you must also
  15. read the `django-celery changelog`_ and upgrade to `django-celery 2.6`_.
  16. This version is officially supported on CPython 2.5, 2.6, 2.7, 3.2 and 3.3,
  17. as well as PyPy and Jython.
  18. .. topic:: Highlights
  19. - A new and improved API, that is both simpler and more powerful.
  20. Everyone should read the new :ref:`first-steps` tutorial,
  21. and the new :ref:`next-steps` tutorial.
  22. - Documentation rewritten and updated to use the new API
  23. - The worker is now thread-less, giving great performance improvements.
  24. - This is the last version to support Python 2.5
  25. - The new "Canvas" makes it easy to define complex workflows.
  26. .. _`website`: http://celeryproject.org/
  27. .. _`django-celery changelog`: http://bit.ly/djcelery-26-changelog
  28. .. _`django-celery 2.6`: http://pypi.python.org/pypi/django-celery/
  29. .. contents::
  30. :local:
  31. :depth: 2
  32. .. _v260-important:
  33. Important Notes
  34. ===============
  35. Eventloop
  36. ---------
  37. The worker is now running *without threads* when used with AMQP or Redis as a
  38. broker, resulting in::
  39. - Much better performance overall.
  40. - Fixes several edge case race conditions.
  41. - Sub-millisecond timer precision.
  42. - Faster shutdown times.
  43. The transports supported are: ``amqplib``, ``librabbitmq``, and ``redis``
  44. Hopefully this can be extended to include additional broker transports
  45. in the future.
  46. For increased reliability the :setting:`CELERY_FORCE_EXECV` setting is enabled
  47. by default if the eventloop is not used.
  48. Now depends on :mod:`billiard`.
  49. -------------------------------
  50. Billiard is a fork of the multiprocessing containing
  51. the no-execv patch by sbt (http://bugs.python.org/issue8713),
  52. and also contains the pool improvements previously located in Celery.
  53. This fork was necessary as changes to the C extension code was required
  54. for the no-execv patch to work.
  55. - Issue #625
  56. - Issue #627
  57. - Issue #640
  58. - `django-celery #122 <http://github.com/celery/django-celery/issues/122`
  59. - `django-celery #124 <http://github.com/celery/django-celery/issues/122`
  60. Last version to support Python 2.5
  61. ----------------------------------
  62. The 2.6 series will be last series to support Python 2.5.
  63. With several other distributions taking the step to discontinue
  64. Python 2.5 support, we feel that it is time too.
  65. Python 2.6 should be widely available at this point, and we urge
  66. you to upgrade, but if that is not possible you still have the option
  67. to continue using the Celery 2.6 series, and important bug fixes
  68. introduced in Celery 2.7 will be back-ported to Celery 2.6 upon request.
  69. .. _v260-news:
  70. News
  71. ====
  72. Chaining Tasks
  73. --------------
  74. Tasks can now have callbacks and errbacks, and dependencies are recorded
  75. - The task message format have been updated with two new extension keys
  76. Both keys can be empty/undefined or a list of subtasks.
  77. - ``callbacks``
  78. Applied if the task exits successfully, with the result
  79. of the task as an argument.
  80. - ``errbacks``
  81. Applied if an error occurred while executing the task,
  82. with the uuid of the task as an argument. Since it may not be possible
  83. to serialize the exception instance, it passes the uuid of the task
  84. instead. The uuid can then be used to retrieve the exception and
  85. traceback of the task from the result backend.
  86. - ``link`` and ``link_error`` keyword arguments has been added
  87. to ``apply_async``.
  88. These add callbacks and errbacks to the task, and
  89. you can read more about them at :ref:`calling-links`.
  90. - We now track what subtasks a task sends, and some result backends
  91. supports retrieving this information.
  92. - task.request.children
  93. Contains the result instances of the subtasks
  94. the currently executing task has applied.
  95. - AsyncResult.children
  96. Returns the tasks dependencies, as a list of
  97. ``AsyncResult``/``ResultSet`` instances.
  98. - AsyncResult.iterdeps
  99. Recursively iterates over the tasks dependencies,
  100. yielding `(parent, node)` tuples.
  101. Raises IncompleteStream if any of the dependencies
  102. has not returned yet.
  103. - AsyncResult.graph
  104. A ``DependencyGraph`` of the tasks dependencies.
  105. This can also be used to convert to dot format:
  106. .. code-block:: python
  107. with open('graph.dot') as fh:
  108. result.graph.to_dot(fh)
  109. which can than be used to produce an image::
  110. $ dot -Tpng graph.dot -o graph.png
  111. - A new special subtask called ``chain`` is also included::
  112. .. code-block:: python
  113. >>> from celery import chain
  114. # (2 + 2) * 8 / 2
  115. >>> res = chain(add.subtask((2, 2)),
  116. mul.subtask((8, )),
  117. div.subtask((2,))).apply_async()
  118. >>> res.get() == 16
  119. >>> res.parent.get() == 32
  120. >>> res.parent.parent.get() == 4
  121. - Adds :meth:`AsyncResult.get_leaf`
  122. Waits and returns the result of the leaf subtask.
  123. That is the last node found when traversing the graph,
  124. but this means that the graph can be 1-dimensional only (in effect
  125. a list).
  126. - Adds ``subtask.link(subtask)`` + ``subtask.link_error(subtask)``
  127. Shortcut to ``s.options.setdefault('link', []).append(subtask)``
  128. - Adds ``subtask.flatten_links()``
  129. Returns a flattened list of all dependencies (recursively)
  130. `group`/`chord`/`chain` are now subtasks
  131. ----------------------------------------
  132. - The source code for these, including subtask, has been moved
  133. to new module celery.canvas.
  134. - group is no longer an alias to TaskSet, but new alltogether,
  135. since it was very difficult to migrate the TaskSet class to become
  136. a subtask.
  137. - A new shortcut has been added to tasks::
  138. >>> task.s(arg1, arg2, kw=1)
  139. as a shortcut to::
  140. >>> task.subtask((arg1, arg2), {'kw': 1})
  141. - Tasks can be chained by using the ``|`` operator::
  142. >>> (add.s(2, 2), pow.s(2)).apply_async()
  143. - Subtasks can be "evaluated" using the ``~`` operator::
  144. >>> ~add.s(2, 2)
  145. 4
  146. >>> ~(add.s(2, 2) | pow.s(2))
  147. is the same as::
  148. >>> chain(add.s(2, 2), pow.s(2)).apply_async().get()
  149. - A new subtask_type key has been added to the subtask dicts
  150. This can be the string "chord", "group", "chain", "chunks",
  151. "xmap", or "xstarmap".
  152. - maybe_subtask now uses subtask_type to reconstruct
  153. the object, to be used when using non-pickle serializers.
  154. - The logic for these operations have been moved to dedicated
  155. tasks celery.chord, celery.chain and celery.group.
  156. - subtask no longer inherits from AttributeDict.
  157. It's now a pure dict subclass with properties for attribute
  158. access to the relevant keys.
  159. - The repr's now outputs how the sequence would like imperatively::
  160. >>> from celery import chord
  161. >>> (chord([add.s(i, i) for i in xrange(10)], xsum.s())
  162. | pow.s(2))
  163. tasks.xsum([tasks.add(0, 0),
  164. tasks.add(1, 1),
  165. tasks.add(2, 2),
  166. tasks.add(3, 3),
  167. tasks.add(4, 4),
  168. tasks.add(5, 5),
  169. tasks.add(6, 6),
  170. tasks.add(7, 7),
  171. tasks.add(8, 8),
  172. tasks.add(9, 9)]) | tasks.pow(2)
  173. Additional control commands made public
  174. ---------------------------------------
  175. - ``add_consumer``/``cancel_consumer``
  176. Tells workers to consume from a new queue, or cancel consuming from a
  177. queue. This command has also been changed so that the worker remembers
  178. the queues added, so that the change will persist even if
  179. the connection is re-connected.
  180. These commands are available programmatically as
  181. :meth:`@control.add_consumer` / :meth:`@control.cancel_consumer`:
  182. .. code-block:: python
  183. >>> celery.control.add_consumer(queue_name,
  184. ... destination=['w1.example.com'])
  185. >>> celery.control.cancel_consumer(queue_name,
  186. ... destination=['w1.example.com'])
  187. or using the :program:`celery control` command::
  188. $ celery control -d w1.example.com add_consumer queue
  189. $ celery control -d w1.example.com cancel_consumer queue
  190. .. note::
  191. Remember that a control command without *destination* will be
  192. sent to **all workers**.
  193. - ``autoscale``
  194. Tells workers with `--autoscale` enabled to change autoscale
  195. max/min concurrency settings.
  196. This command is available programmatically as :meth:`@control.autoscale`:
  197. .. code-block:: python
  198. >>> celery.control.autoscale(max=10, min=5,
  199. ... destination=['w1.example.com'])
  200. or using the :program:`celery control` command::
  201. $ celery control -d w1.example.com autoscale 10 5
  202. - ``pool_grow``/``pool_shrink``
  203. Tells workers to add or remove pool processes.
  204. These commands are available programmatically as
  205. :meth:`@control.pool_grow` / :meth:`@control.pool_shrink`:
  206. .. code-block:: python
  207. >>> celery.control.pool_grow(2, destination=['w1.example.com'])
  208. >>> celery.contorl.pool_shrink(2, destination=['w1.example.com'])
  209. or using the :program:`celery control` command::
  210. $ celery control -d w1.example.com pool_grow 2
  211. $ celery control -d w1.example.com pool_shrink 2
  212. - :program:`celery control` now supports ``rate_limit`` & ``time_limit``
  213. commands.
  214. See ``celery control --help`` for details.
  215. Crontab now supports Day of Month, and Month of Year arguments
  216. --------------------------------------------------------------
  217. See the updated list of examples at :ref:`beat-crontab`.
  218. Immutable subtasks
  219. ------------------
  220. ``subtask``'s can now be immutable, which means that the arguments
  221. will not be modified when calling callbacks::
  222. >>> chain(add.s(2, 2), clear_static_electricity.si())
  223. means it will not receive the argument of the parent task,
  224. and ``.si()`` is a shortcut to::
  225. >>> clear_static_electricity.subtask(immutable=True)
  226. Logging Improvements
  227. --------------------
  228. Logging support now conforms better with best practices.
  229. - Classes used by the worker no longer uses app.get_default_logger, but uses
  230. `celery.utils.log.get_logger` which simply gets the logger not setting the
  231. level, and adds a NullHandler.
  232. - Loggers are no longer passed around, instead every module using logging
  233. defines a module global logger that is used throughout.
  234. - All loggers inherit from a common logger called "celery".
  235. - Before task.get_logger would setup a new logger for every task,
  236. and even set the loglevel. This is no longer the case.
  237. - Instead all task loggers now inherit from a common "celery.task" logger
  238. that is set up when programs call `setup_logging_subsystem`.
  239. - Instead of using LoggerAdapter to augment the formatter with
  240. the task_id and task_name field, the task base logger now use
  241. a special formatter adding these values at runtime from the
  242. currently executing task.
  243. - In fact, ``task.get_logger`` is no longer recommended, it is better
  244. to add module-level logger to your tasks module.
  245. For example, like this:
  246. .. code-block:: python
  247. from celery.utils.log import get_task_logger
  248. logger = get_task_logger(__name__)
  249. @celery.task()
  250. def add(x, y):
  251. logger.debug('Adding %r + %r' % (x, y))
  252. return x + y
  253. The resulting logger will then inherit from the ``"celery.task"`` logger
  254. so that the current task name and id is included in logging output.
  255. - Redirected output from stdout/stderr is now logged to a "celery.redirected"
  256. logger.
  257. - In addition a few warnings.warn have been replaced with logger.warn.
  258. - Now avoids the 'no handlers for logger multiprocessing' warning
  259. Task registry no longer global
  260. ------------------------------
  261. Every Celery instance now has its own task registry.
  262. You can make apps share registries by specifying it::
  263. >>> app1 = Celery()
  264. >>> app2 = Celery(tasks=app1.tasks)
  265. Note that tasks are shared between registries by default, so that
  266. tasks will be added to every subsequently created task registry.
  267. As an alternative tasks can be private to specific task registries
  268. by setting the ``shared`` argument to the ``@task`` decorator::
  269. @celery.task(shared=False)
  270. def add(x, y):
  271. return x + y
  272. Abstract tasks are now lazily bound.
  273. ------------------------------------
  274. The :class:`~celery.task.Task` class is no longer bound to an app
  275. by default, it will first be bound (and configured) when
  276. a concrete subclass is created.
  277. This means that you can safely import and make task base classes,
  278. without also initializing the default app environment::
  279. from celery.task import Task
  280. class DebugTask(Task):
  281. abstract = True
  282. def __call__(self, *args, **kwargs):
  283. print('CALLING %r' % (self, ))
  284. return self.run(*args, **kwargs)
  285. >>> DebugTask
  286. <unbound DebugTask>
  287. >>> @celery1.task(base=DebugTask)
  288. ... def add(x, y):
  289. ... return x + y
  290. >>> add.__class__
  291. <class add of <Celery default:0x101510d10>>
  292. Lazy task decorators
  293. --------------------
  294. The ``@task`` decorator is now lazy when used with custom apps.
  295. That is, if ``accept_magic_kwargs`` is enabled (herby called "compat mode"), the task
  296. decorator executes inline like before, however for custom apps the @task
  297. decorator now returns a special PromiseProxy object that is only evaluated
  298. on access.
  299. All promises will be evaluated when `app.finalize` is called, or implicitly
  300. when the task registry is first used.
  301. Smart `--app` option
  302. --------------------
  303. The :option:`--app` option now 'auto-detects'
  304. - If the provided path is a module it tries to get an
  305. attribute named 'celery'.
  306. - If the provided path is a package it tries
  307. to import a submodule named 'celery',
  308. and get the celery attribute from that module.
  309. E.g. if you have a project named 'proj' where the
  310. celery app is located in 'from proj.celery import celery',
  311. then the following will be equivalent::
  312. $ celery worker --app=proj
  313. $ celery worker --app=proj.celery:
  314. $ celery worker --app=proj.celery:celery
  315. In Other News
  316. -------------
  317. - New :setting:`CELERYD_WORKER_LOST_WAIT` to control the timeout in
  318. seconds before :exc:`billiard.WorkerLostError` is raised
  319. when a worker can not be signalled (Issue #595).
  320. Contributed by Brendon Crawford.
  321. - Redis event monitor queues are now automatically deleted (Issue #436).
  322. - App instance factory methods have been converted to be cached
  323. descriptors that creates a new subclass on access.
  324. This means that e.g. ``celery.Worker`` is an actual class
  325. and will work as expected when::
  326. class Worker(celery.Worker):
  327. ...
  328. - New signal: :signal:`task-success`.
  329. - Multiprocessing logs are now only emitted if the :envvar:`MP_LOG`
  330. environment variable is set.
  331. - The Celery instance can now be created with a broker URL
  332. .. code-block:: python
  333. celery = Celery(broker='redis://')
  334. - Result backends can now be set using an URL
  335. Currently only supported by redis. Example use::
  336. CELERY_RESULT_BACKEND = 'redis://localhost/1'
  337. - Heartbeat frequency now every 5s, and frequency sent with event
  338. The heartbeat frequency is now available in the worker event messages,
  339. so that clients can decide when to consider workers offline based on
  340. this value.
  341. - Module celery.actors has been removed, and will be part of cl instead.
  342. - Introduces new ``celery`` command, which is an entrypoint for all other
  343. commands.
  344. The main for this command can be run by calling ``celery.start()``.
  345. - Annotations now supports decorators if the key startswith '@'.
  346. E.g.:
  347. .. code-block:: python
  348. def debug_args(fun):
  349. @wraps(fun)
  350. def _inner(*args, **kwargs):
  351. print('ARGS: %r' % (args, ))
  352. return _inner
  353. CELERY_ANNOTATIONS = {
  354. 'tasks.add': {'@__call__': debug_args},
  355. }
  356. Also tasks are now always bound by class so that
  357. annotated methods end up being bound.
  358. - Bugreport now available as a command and broadcast command
  359. - Get it from a Python repl::
  360. >>> import celery
  361. >>> print(celery.bugreport())
  362. - Using the ``celery`` command-line program::
  363. $ celery report
  364. - Get it from remote workers::
  365. $ celery inspect report
  366. - Module ``celery.log`` moved to :mod:`celery.app.log`.
  367. - Module ``celery.task.control`` moved to :mod:`celery.app.control`.
  368. - New signal: :signal:`task-revoked`
  369. Sent in the main process when the task is revoked or terminated.
  370. - ``AsyncResult.task_id`` renamed to ``AsyncResult.id``
  371. - ``TasksetResult.taskset_id`` renamed to ``.id``
  372. - ``xmap(task, sequence)`` and ``xstarmap(task, sequence)``
  373. Returns a list of the results applying the task function to every item
  374. in the sequence.
  375. Example::
  376. >>> from celery import xstarmap
  377. >>> xstarmap(add, zip(range(10), range(10)).apply_async()
  378. [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
  379. - ``chunks(task, sequence, chunksize)``
  380. - ``group.skew(start=, stop=, step=)``
  381. Skew will skew the countdown for the individual tasks in a group,
  382. e.g. with a group::
  383. >>> g = group(add.s(i, i) for i in xrange(10))
  384. Skewing the tasks from 0 seconds to 10 seconds::
  385. >>> g.skew(stop=10)
  386. Will have the first task execute in 0 seconds, the second in 1 second,
  387. the third in 2 seconds and so on.
  388. - 99% test Coverage
  389. - :setting:`CELERY_QUEUES` can now be a list/tuple of :class:`~kombu.Queue`
  390. instances.
  391. Internally :attr:`@amqp.queues` is now a mapping of name/Queue instances,
  392. instead of converting on the fly.
  393. * Can now specify connection for :class:`@control.inspect`.
  394. .. code-block:: python
  395. from kombu import Connection
  396. i = celery.control.inspect(connection=Connection('redis://'))
  397. i.active_queues()
  398. * Module :mod:`celery.app.task` is now a module instead of a package.
  399. The setup.py install script will try to remove the old package,
  400. if that doesn't work for some reason you have to remove
  401. it manually, you can do so by executing the command::
  402. $ rm -r $(dirname $(python -c '
  403. import celery;print(celery.__file__)'))/app/task/
  404. * :setting:`CELERY_FORCE_EXECV` is now enabled by default.
  405. If the old behavior is wanted the setting can be set to False,
  406. or the new :option:`--no-execv` to :program:`celery worker`.
  407. * Deprecated module ``celery.conf`` has been removed.
  408. * The :setting:`CELERY_TIMEZONE` now always require the :mod:`pytz`
  409. library to be installed (exept if the timezone is set to `UTC`).
  410. * The Tokyo Tyrant backend has been removed and is no longer supported.
  411. * Now uses :func:`~kombu.common.maybe_declare` to cache queue declarations.
  412. * There is no longer a global default for the
  413. :setting:`CELERYBEAT_MAX_LOOP_INTERVAL` setting, it is instead
  414. set by individual schedulers.
  415. * Worker: now truncates very long message bodies in error reports.
  416. * :envvar:`CELERY_BENCH` environment variable, will now also list
  417. memory usage statistics at worker shutdown.
  418. * Worker: now only ever use a single timer for all timing needs,
  419. and instead set different priorities.
  420. Internals
  421. ---------
  422. * Compat modules are now generated dynamically upon use.
  423. These modules are ``celery.messaging``, ``celery.log``,
  424. ``celery.decorators`` and ``celery.registry``.
  425. * :mod:`celery.utils` refactored into multiple modules:
  426. :mod:`celery.utils.text`
  427. :mod:`celery.utils.imports`
  428. :mod:`celery.utils.functional`
  429. * Now using :mod:`kombu.utils.encoding` instead of
  430. `:mod:`celery.utils.encoding`.
  431. * Renamed module ``celery.routes`` -> :mod:`celery.app.routes`.
  432. * Renamed package ``celery.db`` -> :mod:`celery.backends.database`.
  433. * Renamed module ``celery.abstract`` -> :mod:`celery.worker.abstract`.
  434. * Command-line docs are now parsed from the module docstrings.
  435. * Test suite directory has been reorganized.
  436. * :program:`setup.py` now reads docs from the :file:`requirements/` directory.
  437. .. _v260-experimental:
  438. Experimental
  439. ============
  440. :mod:`celery.contrib.methods`: Task decorator for methods
  441. ----------------------------------------------------------
  442. This is an experimental module containing a task
  443. decorator, and a task decorator filter, that can be used
  444. to create tasks out of methods::
  445. from celery.contrib.methods import task_method
  446. class Counter(object):
  447. def __init__(self):
  448. self.value = 1
  449. @celery.task(name='Counter.increment', filter=task_method)
  450. def increment(self, n=1):
  451. self.value += 1
  452. return self.value
  453. See :mod:`celery.contrib.methods` for more information.
  454. .. _v260-unscheduled-removals:
  455. Unscheduled Removals
  456. ====================
  457. Usually we don't make backward incompatible removals,
  458. but these removals should have no major effect.
  459. - The following settings have been renamed:
  460. - ``CELERYD_ETA_SCHEDULER`` -> ``CELERYD_TIMER``
  461. - ``CELERYD_ETA_SCHEDULER_PRECISION`` -> ``CELERYD_TIMER_PRECISION``
  462. .. _v260-deprecations:
  463. Deprecations
  464. ============
  465. See the :ref:`deprecation-timeline`.
  466. The following undocumented API's has been moved:
  467. - ``control.inspect.add_consumer`` -> :meth:`@control.add_consumer`.
  468. - ``control.inspect.cancel_consumer`` -> :meth:`@control.cancel_consumer`.
  469. - ``control.inspect.enable_events`` -> :meth:`@control.enable_events`.
  470. - ``control.inspect.disable_events`` -> :meth:`@control.disable_events`.
  471. This way ``inspect()`` is only used for commands that do not
  472. modify anything, while idempotent control commands that make changes
  473. are on the control objects.
  474. Fixes
  475. =====
  476. - Retry sqlalchemy backend operations on DatabaseError/OperationalError
  477. (Issue #634)