whatsnew-4.0.rst 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299
  1. .. _whatsnew-4.0:
  2. ===========================================
  3. What's new in Celery 4.0 (0Today8)
  4. ===========================================
  5. :Author: Ask Solem (``ask at celeryproject.org``)
  6. .. sidebar:: Change history
  7. What's new documents describe the changes in major versions,
  8. we also have a :ref:`changelog` that lists the changes in bugfix
  9. releases (0.0.x), while older series are archived under the :ref:`history`
  10. section.
  11. Celery is a simple, flexible and reliable distributed system to
  12. process vast amounts of messages, while providing operations with
  13. the tools required to maintain such a system.
  14. It's a task queue with focus on real-time processing, while also
  15. supporting task scheduling.
  16. Celery has a large and diverse community of users and contributors,
  17. you should come join us :ref:`on IRC <irc-channel>`
  18. or :ref:`our mailing-list <mailing-list>`.
  19. To read more about Celery you should go read the :ref:`introduction <intro>`.
  20. While this version is backward compatible with previous versions
  21. it's important that you read the following section.
  22. This version is officially supported on CPython 2.7, 3.4 and 3.5.
  23. and also supported on PyPy.
  24. .. _`website`: http://celeryproject.org/
  25. .. topic:: Table of Contents
  26. Make sure you read the important notes before upgrading to this version.
  27. .. contents::
  28. :local:
  29. :depth: 2
  30. Preface
  31. =======
  32. Wall of Contributors
  33. --------------------
  34. Aaron McMillin, Adam Renberg, Adrien Guinet, Ahmet Demir, Aitor Gómez-Goiri,
  35. Albert Wang, Alex Koshelev, Alex Rattray, Alex Williams, Alexander Koshelev,
  36. Alexander Lebedev, Alexander Oblovatniy, Alexey Kotlyarov, Ali Bozorgkhan,
  37. Alice Zoë Bevan–McGregor, Allard Hoeve, Alman One, Andrea Rabbaglietti,
  38. Andrea Rosa, Andrei Fokau, Andrew Rodionoff, Andriy Yurchuk,
  39. Aneil Mallavarapu, Areski Belaid, Artyom Koval, Ask Solem, Balthazar Rouberol,
  40. Berker Peksag, Bert Vanderbauwhede, Brian Bouterse, Chris Duryee, Chris Erway,
  41. Chris Harris, Chris Martin, Corey Farwell, Craig Jellick, Cullen Rhodes,
  42. Dallas Marlow, Daniel Wallace, Danilo Bargen, Davanum Srinivas, Dave Smith,
  43. David Baumgold, David Harrigan, David Pravec, Dennis Brakhane, Derek Anderson,
  44. Dmitry Malinovsky, Dudás Ádám, Dustin J. Mitchell, Ed Morley, Fatih Sucu,
  45. Feanil Patel, Felix Schwarz, Fernando Rocha, Flavio Grossi, Frantisek Holop,
  46. Gao Jiangmiao, Gerald Manipon, Gilles Dartiguelongue, Gino Ledesma,
  47. Hank John, Hogni Gylfason, Ilya Georgievsky, Ionel Cristian Mărieș,
  48. James Pulec, Jared Lewis, Jason Veatch, Jasper Bryant-Greene, Jeremy Tillman,
  49. Jocelyn Delalande, Joe Jevnik, John Anderson, John Kirkham, John Whitlock,
  50. Joshua Harlow, Juan Rossi, Justin Patrin, Kai Groner, Kevin Harvey,
  51. Konstantinos Koukopoulos, Kouhei Maeda, Kracekumar Ramaraju,
  52. Krzysztof Bujniewicz, Latitia M. Haskins, Len Buckens, Lorenzo Mancini,
  53. Lucas Wiman, Luke Pomfrey, Marcio Ribeiro, Marin Atanasov Nikolov,
  54. Mark Parncutt, Maxime Vdb, Mher Movsisyan, Michael (``@michael-k``),
  55. Michael Duane Mooring, Michael Permana, Mickaël Penhard, Mike Attwood,
  56. Morton Fox, Môshe van der Sterre, Nat Williams, Nathan Van Gheem, Nik Nyby,
  57. Omer Katz, Omer Korner, Ori Hoch, Paul Pearce, Paulo Bu, Philip Garnero,
  58. Piotr Maślanka, Radek Czajka, Raghuram Srinivasan, Randy Barlow,
  59. Rodolfo Carvalho, Roger Hu, Rongze Zhu, Ross Deane, Ryan Luckie,
  60. Rémy Greinhofer, Samuel Jaillet, Sergey Azovskov, Sergey Tikhonov,
  61. Seungha Kim, Steve Peak, Sukrit Khera, Tadej Janež, Tewfik Sadaoui,
  62. Thomas French, Thomas Grainger, Tobias Schottdorf, Tocho Tochev,
  63. Valentyn Klindukh, Vic Kumar, Vladimir Bolshakov, Vladimir Gorbunov,
  64. Wayne Chang, Wil Langford, Will Thompson, William King, Yury Selivanov,
  65. Zoran Pavlovic, 許邱翔, ``@allenling``, ``@bee-keeper``, ``@ffeast``,
  66. ``@flyingfoxlee``, ``@gdw2``, ``@gitaarik``, ``@hankjin``, ``@m-vdb``,
  67. ``@mdk``, ``@nokrik``, ``@ocean1``, ``@orlo666``, ``@raducc``,
  68. ``@wanglei``, ``@worldexception``.
  69. .. _v400-important:
  70. Important Notes
  71. ===============
  72. Dropped support for Python 2.6
  73. ------------------------------
  74. Celery now requires Python 2.7 or later,
  75. and also drops support for Python 3.3 so supported versions are:
  76. - CPython 2.7
  77. - CPython 3.4
  78. - CPython 3.5
  79. - PyPy 4.0 (``pypy2``)
  80. - PyPy 2.4 (``pypy3``)
  81. - Jython 2.7.0
  82. Lowercase setting names
  83. -----------------------
  84. In the pursuit of beauty all settings have been renamed to be in all
  85. lowercase, and some setting names have been renamed for naming consistency.
  86. This change is fully backwards compatible so you can still use the uppercase
  87. setting names, but we would like you to upgrade as soon as possible and
  88. you can even do so automatically using the :program:`celery upgrade settings`
  89. command:
  90. .. code-block:: console
  91. $ celery upgrade settings proj/settings.py
  92. This command will modify your module in-place to use the new lower-case
  93. names (if you want uppercase with a celery prefix see block below),
  94. and save a backup in :file:`proj/settings.py.orig`.
  95. .. admonition:: For Django users and others who want to keep uppercase names
  96. If you're loading Celery configuration from the Django settings module
  97. then you will want to keep using the uppercase names.
  98. You will also want to use a ``CELERY_`` prefix so that no Celery settings
  99. collide with Django settings used by other apps.
  100. To do this, you will first need to convert your settings file
  101. to use the new consistent naming scheme, and add the prefix to all
  102. Celery related settings:
  103. .. code-block:: console
  104. $ celery upgrade settings --django proj/settings.py
  105. After upgrading the settings file, you need to set the prefix explicitly
  106. in your ``proj/celery.py`` module:
  107. .. code-block:: python
  108. app.config_from_object('django.conf:settings', namespace='CELERY')
  109. You can find the most up to date Django celery integration example
  110. here: :ref:`django-first-steps`.
  111. Note that this will also add a prefix to settings that didn't previously
  112. have one, like ``BROKER_URL``.
  113. Luckily you don't have to manually change the files, as
  114. the :program:`celery upgrade settings --django` program should do the
  115. right thing.
  116. The loader will try to detect if your configuration is using the new format,
  117. and act accordingly, but this also means that you are not allowed to mix and
  118. match new and old setting names, that is unless you provide a value for both
  119. alternatives.
  120. The major difference between previous versions, apart from the lower case
  121. names, are the renaming of some prefixes, like ``celerybeat_`` to ``beat_``,
  122. ``celeryd_`` to ``worker_``.
  123. The ``celery_`` prefix has also been removed, and task related settings
  124. from this name-space is now prefixed by ``task_``, worker related settings
  125. with ``worker_``.
  126. Apart from this most of the settings will be the same in lowercase, apart from
  127. a few special ones:
  128. ===================================== ==========================================================
  129. **Setting name** **Replace with**
  130. ===================================== ==========================================================
  131. ``CELERY_MAX_CACHED_RESULTS`` :setting:`result_cache_max`
  132. ``CELERY_MESSAGE_COMPRESSION`` :setting:`result_compression`/:setting:`task_compression`.
  133. ``CELERY_TASK_RESULT_EXPIRES`` :setting:`result_expires`
  134. ``CELERY_RESULT_DBURI`` :setting:`sqlalchemy_dburi`
  135. ``CELERY_RESULT_ENGINE_OPTIONS`` :setting:`sqlalchemy_engine_options`
  136. ``-*-_DB_SHORT_LIVED_SESSIONS`` :setting:`sqlalchemy_short_lived_sessions`
  137. ``CELERY_RESULT_DB_TABLE_NAMES`` :setting:`sqlalchemy_db_names`
  138. ``CELERY_ACKS_LATE`` :setting:`task_acks_late`
  139. ``CELERY_ALWAYS_EAGER`` :setting:`task_always_eager`
  140. ``CELERY_ANNOTATIONS`` :setting:`task_annotations`
  141. ``CELERY_MESSAGE_COMPRESSION`` :setting:`task_compression`
  142. ``CELERY_CREATE_MISSING_QUEUES`` :setting:`task_create_missing_queues`
  143. ``CELERY_DEFAULT_DELIVERY_MODE`` :setting:`task_default_delivery_mode`
  144. ``CELERY_DEFAULT_EXCHANGE`` :setting:`task_default_exchange`
  145. ``CELERY_DEFAULT_EXCHANGE_TYPE`` :setting:`task_default_exchange_type`
  146. ``CELERY_DEFAULT_QUEUE`` :setting:`task_default_queue`
  147. ``CELERY_DEFAULT_RATE_LIMIT`` :setting:`task_default_rate_limit`
  148. ``CELERY_DEFAULT_ROUTING_KEY`` :setting:`task_default_routing_key`
  149. ``-"-_EAGER_PROPAGATES_EXCEPTIONS`` :setting:`task_eager_propagates`
  150. ``CELERY_IGNORE_RESULT`` :setting:`task_ignore_result`
  151. ``CELERY_TASK_PUBLISH_RETRY`` :setting:`task_publish_retry`
  152. ``CELERY_TASK_PUBLISH_RETRY_POLICY`` :setting:`task_publish_retry_policy`
  153. ``CELERY_QUEUES`` :setting:`task_queues`
  154. ``CELERY_ROUTES`` :setting:`task_routes`
  155. ``CELERY_SEND_TASK_ERROR_EMAILS`` :setting:`task_send_error_emails`
  156. ``CELERY_SEND_TASK_SENT_EVENT`` :setting:`task_send_sent_event`
  157. ``CELERY_TASK_SERIALIZER`` :setting:`task_serializer`
  158. ``CELERYD_TASK_SOFT_TIME_LIMIT`` :setting:`task_soft_time_limit`
  159. ``CELERYD_TASK_TIME_LIMIT`` :setting:`task_time_limit`
  160. ``CELERY_TRACK_STARTED`` :setting:`task_track_started`
  161. ``CELERY_DISABLE_RATE_LIMITS`` :setting:`worker_disable_rate_limits`
  162. ``CELERY_ENABLE_REMOTE_CONTROL`` :setting:`worker_enable_remote_control`
  163. ``CELERYD_SEND_EVENTS`` :setting:`worker_send_task_events`
  164. ===================================== ==========================================================
  165. You can see a full table of the changes in :ref:`conf-old-settings-map`.
  166. JSON is now the default serializer
  167. ----------------------------------
  168. The time has finally come to end the reign of :mod:`pickle` as the default
  169. serialization mechanism, and json is the default serializer starting from this
  170. version.
  171. This change was :ref:`announced with the release of Celery 3.1
  172. <last-version-to-enable-pickle>`.
  173. If you're still depending on :mod:`pickle` being the default serializer,
  174. then you have to configure your app before upgrading to 4.0:
  175. .. code-block:: python
  176. task_serializer = 'pickle'
  177. result_serializer = 'pickle'
  178. accept_content = {'pickle'}
  179. The Task base class no longer automatically register tasks
  180. ----------------------------------------------------------
  181. The :class:`~@Task` class is no longer using a special meta-class
  182. that automatically registers the task in the task registry.
  183. Instead this is now handled by the :class:`@task` decorators.
  184. If you're still using class based tasks, then you need to register
  185. these manually:
  186. .. code-block:: python
  187. class CustomTask(Task):
  188. def run(self):
  189. print('running')
  190. app.tasks.register(CustomTask())
  191. The best practice is to use custom task classes only for overriding
  192. general behavior, and then using the task decorator to realize the task:
  193. .. code-block:: python
  194. @app.task(bind=True, base=CustomTask)
  195. def custom(self):
  196. print('running')
  197. This change also means the ``abstract`` attribute of the task
  198. no longer has any effect.
  199. Task argument checking
  200. ----------------------
  201. The arguments of the task is now verified when calling the task,
  202. even asynchronously:
  203. .. code-block:: pycon
  204. >>> @app.task
  205. ... def add(x, y):
  206. ... return x + y
  207. >>> add.delay(8, 8)
  208. <AsyncResult: f59d71ca-1549-43e0-be41-4e8821a83c0c>
  209. >>> add.delay(8)
  210. Traceback (most recent call last):
  211. File "<stdin>", line 1, in <module>
  212. File "celery/app/task.py", line 376, in delay
  213. return self.apply_async(args, kwargs)
  214. File "celery/app/task.py", line 485, in apply_async
  215. check_arguments(*(args or ()), **(kwargs or {}))
  216. TypeError: add() takes exactly 2 arguments (1 given)
  217. Redis Events not backward compatible
  218. ------------------------------------
  219. The Redis ``fanout_patterns`` and ``fanout_prefix`` transport
  220. options are now enabled by default, which means that workers
  221. running 4.0 cannot see workers running 3.1 on the default configuration,
  222. and vice versa.
  223. This is only related to monitor event messages, the workers should still
  224. execute tasks as normally.
  225. You can avoid this situation by configuring the 3.1 workers (and clients)
  226. to enable these settings, before upgrading to 4.0:
  227. .. code-block:: python
  228. BROKER_TRANSPORT_OPTIONS = {
  229. 'fanout_patterns': True,
  230. 'fanout_prefix': True,
  231. }
  232. Django: Auto-discover now supports Django app configurations
  233. ------------------------------------------------------------
  234. The :meth:`@autodiscover` function can now be called without arguments,
  235. and the Django handler will automatically find your installed apps:
  236. .. code-block:: python
  237. app.autodiscover()
  238. The Django integration :ref:`example in the documentation
  239. <django-first-steps>` has been updated to use the argument-less call.
  240. Worker direct queues no longer use auto-delete.
  241. ===============================================
  242. Workers/clients running 4.0 will no longer be able to send
  243. worker direct messages to worker running older versions, and vice versa.
  244. If you're relying on worker direct messages you should upgrade
  245. your 3.x workers and clients to use the new routing settings first,
  246. by replacing :func:`celery.utils.worker_direct` with this implementation:
  247. .. code-block:: python
  248. from kombu import Exchange, Queue
  249. worker_direct_exchange = Exchange('C.dq2')
  250. def worker_direct(hostname):
  251. return Queue(
  252. '{hostname}.dq2'.format(hostname),
  253. exchange=worker_direct_exchange,
  254. routing_key=hostname,
  255. )
  256. (This feature closed Issue #2492.)
  257. Old command-line programs removed
  258. ---------------------------------
  259. Installing Celery will no longer install the ``celeryd``,
  260. ``celerybeat`` and ``celeryd-multi`` programs.
  261. This was announced with the release of Celery 3.1, but you may still
  262. have scripts pointing to the old names so make sure you update these
  263. to use the new umbrella command:
  264. +-------------------+--------------+-------------------------------------+
  265. | Program | New Status | Replacement |
  266. +===================+==============+=====================================+
  267. | ``celeryd`` | **REMOVED** | :program:`celery worker` |
  268. +-------------------+--------------+-------------------------------------+
  269. | ``celerybeat`` | **REMOVED** | :program:`celery beat` |
  270. +-------------------+--------------+-------------------------------------+
  271. | ``celeryd-multi`` | **REMOVED** | :program:`celery multi` |
  272. +-------------------+--------------+-------------------------------------+
  273. .. _v400-news:
  274. News
  275. ====
  276. New Task Message Protocol
  277. =========================
  278. # e71652d384b1b5df2a4e6145df9f0efb456bc71c
  279. This version introduces a brand new task message protocol,
  280. the first major change to the protocol since the beginning of the project.
  281. The new protocol is backwards incompatible, so you need to set
  282. the :setting:`task_protocol` configuration option to ``2`` to take advantage:
  283. .. code-block:: python
  284. app = Celery()
  285. app.conf.task_protocol = 2
  286. Using the new protocol is recommended for everybody who don't
  287. need backwards compatibility.
  288. Once enabled task messages sent is unreadable to older versions of Celery.
  289. New protocol highlights
  290. -----------------------
  291. The new protocol fixes many problems with the old one, and enables
  292. some long-requested features:
  293. - Most of the data are now sent as message headers, instead of being
  294. serialized with the message body.
  295. In version 1 of the protocol the worker always had to deserialize
  296. the message to be able to read task meta-data like the task id,
  297. name, etc. This also meant that the worker was forced to double-decode
  298. the data, first deserializing the message on receipt, serializing
  299. the message again to send to child process, then finally the child process
  300. deserializes the message again.
  301. Keeping the meta-data fields in the message headers means the worker
  302. does not actually have to decode the payload before delivering
  303. the task to the child process, and also that it's now possible
  304. for the worker to reroute a task written in a language different
  305. from Python to a different worker.
  306. - A new ``lang`` message header can be used to specify the programming
  307. language the task is written in.
  308. - Worker stores results for internal errors like ``ContentDisallowed``,
  309. and other deserialization errors.
  310. - Worker stores results and sends monitoring events for unregistered
  311. task errors.
  312. - Worker calls callbacks/errbacks even when the result is sent by the
  313. parent process (e.g. :exc:`WorkerLostError` when a child process
  314. terminates, deserialization errors, unregistered tasks).
  315. - A new ``origin`` header contains information about the process sending
  316. the task (worker node-name, or PID and host-name information).
  317. - A new ``shadow`` header allows you to modify the task name used in logs.
  318. This is useful for dispatch like patterns, like a task that calls
  319. any function using pickle (don't do this at home):
  320. .. code-block:: python
  321. from celery import Task
  322. from celery.utils.imports import qualname
  323. class call_as_task(Task):
  324. def shadow_name(self, args, kwargs, options):
  325. return 'call_as_task:{0}'.format(qualname(args[0]))
  326. def run(self, fun, *args, **kwargs):
  327. return fun(*args, **kwargs)
  328. call_as_task = app.tasks.register(call_as_task())
  329. - New ``argsrepr`` and ``kwargsrepr`` fields contain textual representations
  330. of the task arguments (possibly truncated) for use in logs, monitors, etc.
  331. This means the worker does not have to deserialize the message payload
  332. to display the task arguments for informational purposes.
  333. - Chains now use a dedicated ``chain`` field enabling support for chains
  334. of thousands and more tasks.
  335. - New ``parent_id`` and ``root_id`` headers adds information about
  336. a tasks relationship with other tasks.
  337. - ``parent_id`` is the task id of the task that called this task
  338. - ``root_id`` is the first task in the work-flow.
  339. These fields can be used to improve monitors like flower to group
  340. related messages together (like chains, groups, chords, complete
  341. work-flows, etc).
  342. - ``app.TaskProducer`` replaced by :meth:`@amqp.create_task_message`` and
  343. :meth:`@amqp.send_task_message``.
  344. Dividing the responsibilities into creating and sending means that
  345. people who want to send messages using a Python AMQP client directly,
  346. does not have to implement the protocol.
  347. The :meth:`@amqp.create_task_message` method calls either
  348. :meth:`@amqp.as_task_v2`, or :meth:`@amqp.as_task_v1` depending
  349. on the configured task protocol, and returns a special
  350. :class:`~celery.app.amqp.task_message` tuple containing the
  351. headers, properties and body of the task message.
  352. .. seealso::
  353. The new task protocol is documented in full here:
  354. :ref:`message-protocol-task-v2`.
  355. Prefork: Tasks now log from the child process
  356. =============================================
  357. Logging of task success/failure now happens from the child process
  358. actually executing the task, which means that logging utilities
  359. like Sentry can get full information about tasks that fail, including
  360. variables in the traceback.
  361. Prefork: One log-file per child process
  362. =======================================
  363. Init-scrips and :program:`celery multi` now uses the `%I` log file format
  364. option (e.g. :file:`/var/log/celery/%n%I.log`).
  365. This change was necessary to ensure each child
  366. process has a separate log file after moving task logging
  367. to the child process, as multiple processes writing to the same
  368. log file can cause corruption.
  369. You are encouraged to upgrade your init-scripts and
  370. :program:`celery multi` arguments to use this new option.
  371. Configure broker URL for read/write separately.
  372. ===============================================
  373. New :setting:`broker_read_url` and :setting:`broker_write_url` settings
  374. have been added so that separate broker URLs can be provided
  375. for connections used for consuming/publishing.
  376. In addition to the configuration options, two new methods have been
  377. added the app API:
  378. - ``app.connection_for_read()``
  379. - ``app.connection_for_write()``
  380. These should now be used in place of ``app.connection()`` to specify
  381. the intent of the required connection.
  382. .. note::
  383. Two connection pools are available: ``app.pool`` (read), and
  384. ``app.producer_pool`` (write). The latter does not actually give connections
  385. but full :class:`kombu.Producer` instances.
  386. .. code-block:: python
  387. def publish_some_message(app, producer=None):
  388. with app.producer_or_acquire(producer) as producer:
  389. ...
  390. def consume_messages(app, connection=None):
  391. with app.connection_or_acquire(connection) as connection:
  392. ...
  393. Canvas Refactor
  394. ===============
  395. The canvas/work-flow implementation have been heavily refactored
  396. to fix some long outstanding issues.
  397. # BLALBLABLA
  398. d79dcd8e82c5e41f39abd07ffed81ca58052bcd2
  399. 1e9dd26592eb2b93f1cb16deb771cfc65ab79612
  400. e442df61b2ff1fe855881c1e2ff9acc970090f54
  401. 0673da5c09ac22bdd49ba811c470b73a036ee776
  402. - Now unrolls groups within groups into a single group (Issue #1509).
  403. - chunks/map/starmap tasks now routes based on the target task
  404. - chords and chains can now be immutable.
  405. - Fixed bug where serialized signatures were not converted back into
  406. signatures (Issue #2078)
  407. Fix contributed by Ross Deane.
  408. - Fixed problem where chains and groups did not work when using JSON
  409. serialization (Issue #2076).
  410. Fix contributed by Ross Deane.
  411. - Creating a chord no longer results in multiple values for keyword
  412. argument 'task_id' (Issue #2225).
  413. Fix contributed by Aneil Mallavarapu
  414. - Fixed issue where the wrong result is returned when a chain
  415. contains a chord as the penultimate task.
  416. Fix contributed by Aneil Mallavarapu
  417. - Special case of ``group(A.s() | group(B.s() | C.s()))`` now works.
  418. - Chain: Fixed bug with incorrect id set when a subtask is also a chain.
  419. - ``group | group`` is now flattened into a single group (Issue #2573).
  420. - Fixed issue where ``group | task`` was not upgrading correctly
  421. to chord (Issue #2922).
  422. Amazon SQS transport now officially supported.
  423. ==============================================
  424. The SQS broker transport has been rewritten to use async I/O and as such
  425. joins RabbitMQ and Redis as officially supported transports.
  426. The new implementation also takes advantage of long polling,
  427. and closes several issues related to using SQS as a broker.
  428. This work was sponsored by Nextdoor.
  429. Schedule tasks based on sunrise, sunset, dawn and dusk.
  430. =======================================================
  431. See :ref:`beat-solar` for more information.
  432. Contributed by Mark Parncutt.
  433. New API for configuring periodic tasks
  434. ======================================
  435. This new API enables you to use signatures when defining periodic tasks,
  436. removing the chance of mistyping task names.
  437. An example of the new API is :ref:`here <beat-entries>`.
  438. # bc18d0859c1570f5eb59f5a969d1d32c63af764b
  439. # 132d8d94d38f4050db876f56a841d5a5e487b25b
  440. RabbitMQ Priority queue support
  441. ===============================
  442. See :ref:`routing-options-rabbitmq-priorities` for more information.
  443. Contributed by Gerald Manipon.
  444. Prefork: Limit child process resident memory size.
  445. ==================================================
  446. # 5cae0e754128750a893524dcba4ae030c414de33
  447. You can now limit the maximum amount of memory allocated per prefork
  448. pool child process by setting the worker
  449. :option:`--maxmemperchild <celery worker --maxmemperchild>` option,
  450. or the :setting:`worker_max_memory_per_child` setting.
  451. The limit is for RSS/resident memory size and is specified in kilobytes.
  452. A child process having exceeded the limit will be terminated and replaced
  453. with a new process after the currently executing task returns.
  454. See :ref:`worker-maxmemperchild` for more information.
  455. Contributed by Dave Smith.
  456. Redis: Result backend optimization
  457. ==================================
  458. RPC is now using pub/sub for streaming task results.
  459. ----------------------------------------------------
  460. Calling ``result.get()`` when using the Redis result backend
  461. used to be extremely expensive as it was using polling to wait
  462. for the result to become available. A default polling
  463. interval of 0.5 seconds did not help performance, but was
  464. necessary to avoid a spin loop.
  465. The new implementation is using Redis Pub/Sub mechanisms to
  466. publish and retrieve results immediately, greatly improving
  467. task round-trip times.
  468. Contributed by Yaroslav Zhavoronkov and Ask Solem.
  469. New optimized chord join implementation.
  470. ----------------------------------------
  471. This was an experimental feature introduced in Celery 3.1,
  472. that could only be enabled by adding ``?new_join=1`` to the
  473. result backend URL configuration.
  474. We feel that the implementation has been tested thoroughly enough
  475. to be considered stable and enabled by default.
  476. The new implementation greatly reduces the overhead of chords,
  477. and especially with larger chords the performance benefit can be massive.
  478. New Riak result backend Introduced.
  479. ===================================
  480. See :ref:`conf-riak-result-backend` for more information.
  481. Contributed by Gilles Dartiguelongue, Alman One and NoKriK.
  482. New CouchDB result backend introduced.
  483. ======================================
  484. See :ref:`conf-couchdb-result-backend` for more information.
  485. Contributed by Nathan Van Gheem
  486. Brand new Cassandra result backend.
  487. ===================================
  488. A brand new Cassandra backend utilizing the new :pypi:`cassandra-driver`
  489. library is replacing the old result backend which was using the older
  490. :pypi:`pycassa` library.
  491. See :ref:`conf-cassandra-result-backend` for more information.
  492. # XXX What changed?
  493. New Elasticsearch result backend introduced.
  494. ============================================
  495. See :ref:`conf-elasticsearch-result-backend` for more information.
  496. Contributed by Ahmet Demir.
  497. New File-system result backend introduced.
  498. ==========================================
  499. See :ref:`conf-filesystem-result-backend` for more information.
  500. Contributed by Môshe van der Sterre.
  501. Event Batching
  502. ==============
  503. Events are now buffered in the worker and sent as a list which reduces
  504. the overhead required to send monitoring events.
  505. For authors of custom event monitors there will be no action
  506. required as long as you're using the Python celery
  507. helpers (:class:`~@events.Receiver`) to implement your monitor.
  508. However, if you're manually receiving event messages you must now account
  509. for batched event messages which differ from normal event messages
  510. in the following way:
  511. - The routing key for a batch of event messages will be set to
  512. ``<event-group>.multi`` where the only batched event group
  513. is currently ``task`` (giving a routing key of ``task.multi``).
  514. - The message body will be a serialized list-of-dictionaries instead
  515. of a dictionary. Each item in the list can be regarded
  516. as a normal event message body.
  517. 03399b4d7c26fb593e61acf34f111b66b340ba4e
  518. Task.replace
  519. ============
  520. Task.replace changed, removes Task.replace_in_chord.
  521. The two methods had almost the same functionality, but the old
  522. ``Task.replace`` would force the new task to inherit the
  523. callbacks/errbacks of the existing task.
  524. If you replace a node in a tree, then you would not expect the new node to
  525. inherit the children of the old node, so this seems like unexpected
  526. behavior.
  527. So ``self.replace(sig)`` now works for any task, in addition ``sig`` can now
  528. be a group.
  529. Groups are automatically converted to a chord, where the callback
  530. will "accumulate" the results of the group tasks.
  531. A new built-in task (`celery.accumulate` was added for this purpose)
  532. Closes #817
  533. Optimized Beat implementation
  534. =============================
  535. The :program:`celery beat` implementation has been optimized
  536. for millions of periodic tasks by using a heap to schedule entries.
  537. Contributed by Ask Solem and Alexander Koshelev.
  538. Task Auto-retry Decorator
  539. =========================
  540. Writing custom retry handling for exception events is so common
  541. that we now have built-in support for it.
  542. For this a new ``autoretry_for`` argument is now supported by
  543. the task decorators, where you can specify a tuple of exceptions
  544. to automatically retry for.
  545. See :ref:`task-autoretry` for more information.
  546. Contributed by Dmitry Malinovsky.
  547. # 75246714dd11e6c463b9dc67f4311690643bff24
  548. Remote Task Tracebacks
  549. ======================
  550. The new :setting:`task_remote_tracebacks` will make task tracebacks more
  551. useful by injecting the stack of the remote worker.
  552. This feature requires the additional :pypi:`tblib` library.
  553. Contributed by Ionel Cristian Mărieș.
  554. Async Result API
  555. ================
  556. eventlet/gevent drainers, promises, BLA BLA
  557. Closed issue #2529.
  558. In Other News
  559. -------------
  560. - **Requirements**:
  561. - Now depends on :ref:`Kombu 4.0 <kombu:version-4.0>`.
  562. - Now depends on :pypi:`billiard` version 3.5.
  563. - No longer depends on :pypi:`anyjson` :(
  564. - **Tasks**: The "anon-exchange" is now used for simple name-name direct routing.
  565. This increases performance as it completely bypasses the routing table,
  566. in addition it also improves reliability for the Redis broker transport.
  567. - **Tasks**: :setting:`task_routes` can now contain glob patterns and
  568. regexes.
  569. See new examples in :setting:`task_routes` and :ref:`routing-automatic`.
  570. - **Eventlet/Gevent**: Fixed race condition leading to "simultaneous read"
  571. errors (Issue #2812).
  572. - **Programs**: ``%n`` format for :program:`celery multi` is now synonym with
  573. ``%N`` to be consistent with :program:`celery worker`.
  574. - **Programs**: celery inspect/control now supports a new
  575. :option:`--json <celery inspect --json>` option to give output in json format.
  576. - **Programs**: :program:`celery inspect registered` now ignores built-in
  577. tasks.
  578. - **Programs**: New :program:`celery logtool`: Utility for filtering and parsing
  579. celery worker log-files
  580. - **Redis Transport**: The Redis transport now supports the
  581. :setting:`broker_use_ssl` option.
  582. - **Worker**: Worker now only starts the remote control command consumer if the
  583. broker transport used actually supports them.
  584. - **Worker**: Gossip now sets ``x-message-ttl`` for event queue to heartbeat_interval s.
  585. (Issue #2005).
  586. - **Worker**: Now preserves exit code (Issue #2024).
  587. - **Worker**: Log--level for unrecoverable errors changed from ``error`` to
  588. ``critical``.
  589. - **Worker**: Improved rate limiting accuracy.
  590. - **Worker**: Account for missing timezone information in task expires field.
  591. Fix contributed by Albert Wang.
  592. - **Worker**: The worker no longer has a ``Queues`` bootsteps, as it is now
  593. superfluous.
  594. - **Tasks**: New :setting:`task_reject_on_worker_lost` setting, and
  595. :attr:`~@Task.reject_on_worker_lost` task attribute decides what happens
  596. when the child worker process executing a late ack task is terminated.
  597. Contributed by Michael Permana.
  598. - **Worker**: Improvements and fixes for LimitedSet
  599. Getting rid of leaking memory + adding ``minlen`` size of the set:
  600. the minimal residual size of the set after operating for some time.
  601. ``minlen`` items are kept, even if they should have been expired.
  602. Problems with older and even more old code:
  603. #. Heap would tend to grow in some scenarios
  604. (like adding an item multiple times).
  605. #. Adding many items fast would not clean them soon enough (if ever).
  606. #. When talking to other workers, revoked._data was sent, but
  607. it was processed on the other side as iterable.
  608. That means giving those keys new (current)
  609. time-stamp. By doing this workers could recycle
  610. items forever. Combined with 1) and 2), this means that in
  611. large set of workers, you are getting out of memory soon.
  612. All those problems should be fixed now.
  613. This should fix issues #3095, #3086.
  614. Contributed by David Pravec.
  615. - **App**: New signals for app configuration/finalization:
  616. - :data:`app.on_configure <@on_configure>`
  617. - :data:`app.on_after_configure <@on_after_configure>`
  618. - :data:`app.on_after_finalize <@on_after_finalize>`
  619. - **Task**: New task signals for rejected task messages:
  620. - :data:`celery.signals.task_rejected`.
  621. - :data:`celery.signals.task_unknown`.
  622. - **Events**: Event messages now uses the RabbitMQ ``x-message-ttl`` option
  623. to ensure older event messages are discarded.
  624. The default is 5 seconds, but can be changed using the
  625. :setting:`event_queue_ttl` setting.
  626. - **Events**: Event monitors now sets the :setting:`event_queue_expires`
  627. setting by default.
  628. The queues will now expire after 60 seconds after the monitor stops
  629. consuming from it.
  630. - **Canvas**: ``chunks``/``map``/``starmap`` are now routed based on the target task.
  631. - **Canvas**: ``Signature.link`` now works when argument is scalar (not a list)
  632. (Issue #2019).
  633. - **App**: The application can now change how task names are generated using
  634. the :meth:`~@gen_task_name` method.
  635. Contributed by Dmitry Malinovsky.
  636. - **App**: App has new ``app.current_worker_task`` property that
  637. returns the task that is currently being worked on (or :const:`None`).
  638. (Issue #2100).
  639. - **Tasks**: ``Task.subtask`` renamed to ``Task.signature`` with alias.
  640. - **Tasks**: ``Task.subtask_from_request`` renamed to
  641. ``Task.signature_from_request`` with alias.
  642. - **Tasks**: The ``delivery_mode`` attribute for :class:`kombu.Queue` is now
  643. respected (Issue #1953).
  644. - **Tasks**: Routes in :setting:`task-routes` can now specify a
  645. :class:`~kombu.Queue` instance directly.
  646. Example:
  647. .. code-block:: python
  648. task_routes = {'proj.tasks.add': {'queue': Queue('add')}}
  649. - **Tasks**: ``AsyncResult`` now raises :exc:`ValueError` if task_id is None.
  650. (Issue #1996).
  651. - **Tasks**: ``result.get()`` now supports an ``on_message`` argument to set a
  652. callback to be called for every message received.
  653. - **Tasks**: New abstract classes added:
  654. - :class:`~celery.utils.abstract.CallableTask`
  655. Looks like a task.
  656. - :class:`~celery.utils.abstract.CallableSignature`
  657. Looks like a task signature.
  658. - **Programs**: :program:`celery multi` now passes through `%i` and `%I` log
  659. file formats.
  660. - **Programs**: ``%p`` can now be used to expand to the full worker node-name
  661. in log-file/pid-file arguments.
  662. - **Programs**: A new command line option
  663. :option:`--executable <celery worker --executable>` is now
  664. available for daemonizing programs (:program:`celery worker` and
  665. :program:`celery beat`).
  666. Contributed by Bert Vanderbauwhede.
  667. - **Programs**: :program:`celery worker` supports new
  668. :option:`--prefetch-multiplier <celery worker --prefetch-multiplier>` option.
  669. Contributed by Mickaël Penhard.
  670. - **Deployment**: Generic init-scripts now support
  671. :envvar:`CELERY_SU`` and :envvar:`CELERYD_SU_ARGS` environment variables
  672. to set the path and arguments for :command:`su` (:manpage:`su(1)`).
  673. - **Prefork**: Prefork pool now uses ``poll`` instead of ``select`` where
  674. available (Issue #2373).
  675. - **Eventlet**: Now returns pool size in :program:`celery inspect stats`
  676. command.
  677. Contributed by Alexander Oblovatniy.
  678. - **Tasks**: New :setting:`email_charset` setting allows for changing
  679. the character set used for outgoing error emails.
  680. Contributed by Vladimir Gorbunov.
  681. - **Worker**: Now respects :setting:`broker_connection_retry` setting.
  682. Fix contributed by Nat Williams.
  683. - **Worker**: Auto-scale did not always update keep-alive when scaling down.
  684. Fix contributed by Philip Garnero.
  685. - **General**: Dates are now always timezone aware even if
  686. :setting:`enable_utc` is disabled (Issue #943).
  687. Fix contributed by Omer Katz.
  688. - **Result Backends**: The redis result backend now has a default socket
  689. timeout of 5 seconds.
  690. The default can be changed using the new :setting:`redis_socket_timeout`
  691. setting.
  692. Contributed by Raghuram Srinivasan.
  693. - **Result Backends**: RPC Backend result queues are now auto delete by
  694. default (Issue #2001).
  695. - **Result Backends**: MongoDB now supports setting the
  696. :setting:`result_serialzier` setting to ``bson`` to use the MongoDB
  697. libraries own serializer.
  698. Contributed by Davide Quarta.
  699. - **Result Backends**: SQLAlchemy result backend now ignores all result
  700. engine options when using NullPool (Issue #1930).
  701. - **Result Backends**: MongoDB URI handling has been improved to use
  702. database name, user and password from the URI if provided.
  703. Contributed by Samuel Jaillet.
  704. - **Result Backends**: Fix problem with RPC/AMQP backends where exception
  705. was not deserialized properly with the json serializer (Issue #2518).
  706. Fix contributed by Allard Hoeve.
  707. - **Result Backends**: Database backend now sets max char size to 155 to deal
  708. with brain damaged MySQL unicode implementation (Issue #1748).
  709. - **General**: All Celery exceptions/warnings now inherit from common
  710. :class:`~celery.exceptions.CeleryException`/:class:`~celery.exceptions.CeleryWarning`.
  711. (Issue #2643).
  712. - **Tasks**: Task retry now also throws in eager mode.
  713. Fix contributed by Feanil Patel.
  714. - **Tasks**: Task error email character set now set to ``utf-8`` by default
  715. (Issue #2737).
  716. - Apps can now define how tasks are named (:meth:`@gen_task_name`).
  717. Contributed by Dmitry Malinovsky
  718. - Module ``celery.worker.job`` renamed to :mod:`celery.worker.request`.
  719. - Beat: ``Scheduler.Publisher``/``.publisher`` renamed to
  720. ``.Producer``/``.producer``.
  721. Incompatible changes
  722. ====================
  723. - Prefork: Calling ``result.get()`` or joining any result from within a task
  724. now raises :exc:`RuntimeError`.
  725. In previous versions this would emit a warning.
  726. - :mod:`celery.worker.consumer` is now a package, not a module.
  727. - Result: The task_name argument/attribute of :class:`@AsyncResult` was
  728. removed.
  729. This was historically a field used for :mod:`pickle` compatibility,
  730. but is no longer needed.
  731. - Backends: Arguments named ``status`` renamed to ``state``.
  732. - Backends: ``backend.get_status()`` renamed to ``backend.get_state()``.
  733. Unscheduled Removals
  734. ====================
  735. - The experimental :mod:`celery.contrib.methods` feature has been removed,
  736. as there were far many bugs in the implementation to be useful.
  737. - The CentOS init-scripts have been removed.
  738. These did not really add any features over the generic init-scripts,
  739. so you are encouraged to use them instead, or something like
  740. :pypi:`supervisor`.
  741. .. _v400-removals:
  742. Scheduled Removals
  743. ==================
  744. Modules
  745. -------
  746. - Module ``celery.worker.job`` has been renamed to :mod:`celery.worker.request`.
  747. This was an internal module so should not have any effect.
  748. It is now part of the public API so should not change again.
  749. - Module ``celery.task.trace`` has been renamed to ``celery.app.trace``
  750. as the ``celery.task`` package is being phased out. The module
  751. will be removed in version 5.0 so please change any import from::
  752. from celery.task.trace import X
  753. to::
  754. from celery.app.trace import X
  755. - Old compatibility aliases in the :mod:`celery.loaders` module
  756. has been removed.
  757. - Removed ``celery.loaders.current_loader()``, use: ``current_app.loader``
  758. - Removed ``celery.loaders.load_settings()``, use: ``current_app.conf``
  759. Result
  760. ------
  761. - ``AsyncResult.serializable()`` and ``celery.result.from_serializable``
  762. has been removed:
  763. Use instead:
  764. .. code-block:: pycon
  765. >>> tup = result.as_tuple()
  766. >>> from celery.result import result_from_tuple
  767. >>> result = result_from_tuple(tup)
  768. - Removed ``BaseAsyncResult``, use ``AsyncResult`` for instance checks
  769. instead.
  770. - Removed ``TaskSetResult``, use ``GroupResult`` instead.
  771. - ``TaskSetResult.total`` -> ``len(GroupResult)``
  772. - ``TaskSetResult.taskset_id`` -> ``GroupResult.id``
  773. - Removed ``ResultSet.subtasks``, use ``ResultSet.results`` instead.
  774. TaskSet
  775. -------
  776. TaskSet has been renamed to group and TaskSet will be removed in version 4.0.
  777. Old::
  778. >>> from celery.task import TaskSet
  779. >>> TaskSet(add.subtask((i, i)) for i in xrange(10)).apply_async()
  780. New::
  781. >>> from celery import group
  782. >>> group(add.s(i, i) for i in xrange(10))()
  783. Events
  784. ------
  785. - Removals for class :class:`celery.events.state.Worker`:
  786. - ``Worker._defaults`` attribute.
  787. Use ``{k: getattr(worker, k) for k in worker._fields}``.
  788. - ``Worker.update_heartbeat``
  789. Use ``Worker.event(None, timestamp, received)``
  790. - ``Worker.on_online``
  791. Use ``Worker.event('online', timestamp, received, fields)``
  792. - ``Worker.on_offline``
  793. Use ``Worker.event('offline', timestamp, received, fields)``
  794. - ``Worker.on_heartbeat``
  795. Use ``Worker.event('heartbeat', timestamp, received, fields)``
  796. - Removals for class :class:`celery.events.state.Task`:
  797. - ``Task._defaults`` attribute.
  798. Use ``{k: getattr(task, k) for k in task._fields}``.
  799. - ``Task.on_sent``
  800. Use ``Worker.event('sent', timestamp, received, fields)``
  801. - ``Task.on_received``
  802. Use ``Task.event('received', timestamp, received, fields)``
  803. - ``Task.on_started``
  804. Use ``Task.event('started', timestamp, received, fields)``
  805. - ``Task.on_failed``
  806. Use ``Task.event('failed', timestamp, received, fields)``
  807. - ``Task.on_retried``
  808. Use ``Task.event('retried', timestamp, received, fields)``
  809. - ``Task.on_succeeded``
  810. Use ``Task.event('succeeded', timestamp, received, fields)``
  811. - ``Task.on_revoked``
  812. Use ``Task.event('revoked', timestamp, received, fields)``
  813. - ``Task.on_unknown_event``
  814. Use ``Task.event(short_type, timestamp, received, fields)``
  815. - ``Task.update``
  816. Use ``Task.event(short_type, timestamp, received, fields)``
  817. - ``Task.merge``
  818. Contact us if you need this.
  819. Magic keyword arguments
  820. -----------------------
  821. Support for the very old magic keyword arguments accepted by tasks is
  822. finally removed in this version.
  823. If you are still using these you have to rewrite any task still
  824. using the old ``celery.decorators`` module and depending
  825. on keyword arguments being passed to the task,
  826. for example::
  827. from celery.decorators import task
  828. @task()
  829. def add(x, y, task_id=None):
  830. print('My task id is %r' % (task_id,))
  831. should be rewritten into::
  832. from celery import task
  833. @task(bind=True)
  834. def add(self, x, y):
  835. print('My task id is {0.request.id}'.format(self))
  836. Settings
  837. --------
  838. The following settings have been removed, and is no longer supported:
  839. Logging Settings
  840. ~~~~~~~~~~~~~~~~
  841. ===================================== =====================================
  842. **Setting name** **Replace with**
  843. ===================================== =====================================
  844. ``CELERYD_LOG_LEVEL`` :option:`celery worker --loglevel`
  845. ``CELERYD_LOG_FILE`` :option:`celery worker --logfile`
  846. ``CELERYBEAT_LOG_LEVEL`` :option:`celery beat --loglevel`
  847. ``CELERYBEAT_LOG_FILE`` :option:`celery beat --loglevel`
  848. ``CELERYMON_LOG_LEVEL`` celerymon is deprecated, use flower.
  849. ``CELERYMON_LOG_FILE`` celerymon is deprecated, use flower.
  850. ``CELERYMON_LOG_FORMAT`` celerymon is deprecated, use flower.
  851. ===================================== =====================================
  852. Task Settings
  853. ~~~~~~~~~~~~~~
  854. ===================================== =====================================
  855. **Setting name** **Replace with**
  856. ===================================== =====================================
  857. ``CELERY_CHORD_PROPAGATES`` N/A
  858. ===================================== =====================================
  859. .. _v400-deprecations:
  860. Deprecation Time-line Changes
  861. =============================
  862. See the :ref:`deprecation-timeline`.
  863. .. _v400-fixes:
  864. Fixes
  865. =====