whatsnew-4.0.rst 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349
  1. .. _whatsnew-4.0:
  2. ===========================================
  3. What's new in Celery 4.0 (latentcall)
  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: 3
  30. Preface
  31. =======
  32. Welcome to Celery 4!
  33. This is a massive release with over two years of changes.
  34. Not only does it come with many new features, but it also fixes
  35. a massive list of bugs, so in many ways you could call it
  36. our "Snow Leopard" release.
  37. The next major version of Celery will support Python 3.5 only, were
  38. we are planning to take advantage of the new asyncio library.
  39. This release would not have been possible without the support
  40. of my employer, `Robinhood`_ (we're hiring!).
  41. - Ask Solem
  42. Dedicated to Sebastian "Zeb" Bjørnerud (RIP),
  43. with special thanks to `Ty Wilkins`_, for designing our new logo,
  44. all the contributors who help make this happen, and my colleagues
  45. at `Robinhood`_.
  46. .. _`Ty Wilkins`: http://tywilkins.com
  47. .. _`Robinhood`: http://robinhood.com
  48. Wall of Contributors
  49. --------------------
  50. Aaron McMillin, Adam Chainz, Adam Renberg, Adriano Martins de Jesus,
  51. Adrien Guinet, Ahmet Demir, Aitor Gómez-Goiri, Alan Justino,
  52. Albert Wang, Alex Koshelev, Alex Rattray, Alex Williams, Alexander Koshelev,
  53. Alexander Lebedev, Alexander Oblovatniy, Alexey Kotlyarov, Ali Bozorgkhan,
  54. Alice Zoë Bevan–McGregor, Allard Hoeve, Alman One, Amir Rustamzadeh,
  55. Andrea Rabbaglietti, Andrea Rosa, Andrei Fokau, Andrew Rodionoff,
  56. Andrew Stewart, Andriy Yurchuk, Aneil Mallavarapu, Areski Belaid,
  57. Armenak Baburyan, Arthur Vuillard, Artyom Koval, Asif Saifuddin Auvi,
  58. Ask Solem, Balthazar Rouberol, Batiste Bieler, Berker Peksag,
  59. Bert Vanderbauwhede, Brendan Smithyman, Brian Bouterse, Bryce Groff,
  60. Cameron Will, ChangBo Guo, Chris Clark, Chris Duryee, Chris Erway,
  61. Chris Harris, Chris Martin, Chillar Anand, Colin McIntosh, Conrad Kramer,
  62. Corey Farwell, Craig Jellick, Cullen Rhodes, Dallas Marlow, Daniel Devine,
  63. Daniel Wallace, Danilo Bargen, Davanum Srinivas, Dave Smith, David Baumgold,
  64. David Harrigan, David Pravec, Dennis Brakhane, Derek Anderson,
  65. Dmitry Dygalo, Dmitry Malinovsky, Dongweiming, Dudás Ádám,
  66. Dustin J. Mitchell, Ed Morley, Edward Betts, Éloi Rivard, Emmanuel Cazenave,
  67. Fahad Siddiqui, Fatih Sucu, Feanil Patel, Federico Ficarelli, Felix Schwarz,
  68. Felix Yan, Fernando Rocha, Flavio Grossi, Frantisek Holop, Gao Jiangmiao,
  69. George Whewell, Gerald Manipon, Gilles Dartiguelongue, Gino Ledesma, Greg Wilbur,
  70. Guillaume Seguin, Hank John, Hogni Gylfason, Ilya Georgievsky,
  71. Ionel Cristian Mărieș, Ivan Larin, James Pulec, Jared Lewis, Jason Veatch,
  72. Jasper Bryant-Greene, Jeff Widman, Jeremy Tillman, Jeremy Zafran,
  73. Jocelyn Delalande, Joe Jevnik, Joe Sanford, John Anderson, John Barham,
  74. John Kirkham, John Whitlock, Jonathan Vanasco, Joshua Harlow, João Ricardo,
  75. Juan Carlos Ferrer, Juan Rossi, Justin Patrin, Kai Groner, Kevin Harvey,
  76. Kevin Richardson, Komu Wairagu, Konstantinos Koukopoulos, Kouhei Maeda,
  77. Kracekumar Ramaraju, Krzysztof Bujniewicz, Latitia M. Haskins, Len Buckens,
  78. Lev Berman, lidongming, Lorenzo Mancini, Lucas Wiman, Luke Pomfrey,
  79. Luyun Xie, Maciej Obuchowski, Manuel Kaufmann, Marat Sharafutdinov,
  80. Marc Sibson, Marcio Ribeiro, Marin Atanasov Nikolov, Mathieu Fenniak,
  81. Mark Parncutt, Mauro Rocco, Maxime Beauchemin, Maxime Vdb, Mher Movsisyan,
  82. Michael Aquilina, Michael Duane Mooring, Michael Permana, Mickaël Penhard,
  83. Mike Attwood, Mitchel Humpherys, Mohamed Abouelsaoud, Morris Tweed, Morton Fox,
  84. Môshe van der Sterre, Nat Williams, Nathan Van Gheem, Nicolas Unravel,
  85. Nik Nyby, Omer Katz, Omer Korner, Ori Hoch, Paul Pearce, Paulo Bu,
  86. Pavlo Kapyshin, Philip Garnero, Pierre Fersing, Piotr Kilczuk,
  87. Piotr Maślanka, Quentin Pradet, Radek Czajka, Raghuram Srinivasan,
  88. Randy Barlow, Raphael Michel, Rémy Léone, Robert Coup, Robert Kolba,
  89. Rockallite Wulf, Rodolfo Carvalho, Roger Hu, Romuald Brunet, Rongze Zhu,
  90. Ross Deane, Ryan Luckie, Rémy Greinhofer, Samuel Giffard, Samuel Jaillet,
  91. Sergey Azovskov, Sergey Tikhonov, Seungha Kim, Simon Peeters,
  92. Spencer E. Olson, Srinivas Garlapati, Stephen Milner, Steve Peak, Steven Sklar,
  93. Stuart Axon, Sukrit Khera, Tadej Janež, Taha Jahangir, Takeshi Kanemoto,
  94. Tayfun Sen, Tewfik Sadaoui, Thomas French, Thomas Grainger, Tomas Machalek,
  95. Tobias Schottdorf, Tocho Tochev, Valentyn Klindukh, Vic Kumar,
  96. Vladimir Bolshakov, Vladimir Gorbunov, Wayne Chang, Wieland Hoffmann,
  97. Wido den Hollander, Wil Langford, Will Thompson, William King, Yury Selivanov,
  98. Vytis Banaitis, Zoran Pavlovic, Xin Li, 許邱翔, :github_user:`allenling`,
  99. :github_user:`alzeih`, :github_user:`bastb`, :github_user:`bee-keeper`,
  100. :github_user:`ffeast`, :github_user:`firefly4268`,
  101. :github_user:`flyingfoxlee`, :github_user:`gdw2`, :github_user:`gitaarik`,
  102. :github_user:`hankjin`, :github_user:`lvh`, :github_user:`m-vdb`,
  103. :github_user:`kindule`, :github_user:`mdk`:, :github_user:`michael-k`,
  104. :github_user:`mozillazg`, :github_user:`nokrik`, :github_user:`ocean1`,
  105. :github_user:`orlo666`, :github_user:`raducc`, :github_user:`wanglei`,
  106. :github_user:`worldexception`, :github_user:`xBeAsTx`.
  107. .. note::
  108. This wall was automatically generated from git history,
  109. so sadly it doesn't not include the people who help with more important
  110. things like answering mailing-list questions.
  111. Upgrading from Celery 3.1
  112. =========================
  113. Step 1: Upgrade to Celery 3.1.25
  114. --------------------------------
  115. If you haven't already, the first step is to upgrade to Celery 3.1.25.
  116. This version adds forward compatibility to the new message protocol,
  117. so that you can incrementally upgrade from 3.1 to 4.0.
  118. Deploy the workers first by upgrading to 3.1.25, this means these
  119. workers can process messages sent by clients using both 3.1 and 4.0.
  120. After the workers are upgraded you can upgrade the clients (e.g. web servers).
  121. Step 2: Update your configuration with the new setting names
  122. ------------------------------------------------------------
  123. This version radically changes the configuration setting names,
  124. to be more consistent.
  125. The changes are fully backwards compatible, so you have the option to wait
  126. until the old setting names are deprecated, but to ease the transition
  127. we have included a command-line utility that rewrites your settings
  128. automatically.
  129. See :ref:`v400-upgrade-settings` for more information.
  130. Step 3: Read the important notes in this document
  131. -------------------------------------------------
  132. Make sure you are not affected by any of the important upgrade notes
  133. mentioned in the following section.
  134. An especially important note is that Celery now checks the arguments
  135. you send to a task by matching it to the signature (:ref:`v400-typing`).
  136. Step 4: Upgrade to Celery 4.0
  137. -----------------------------
  138. At this point you can upgrade your workers and clients with the new version.
  139. .. _v400-important:
  140. Important Notes
  141. ===============
  142. Dropped support for Python 2.6
  143. ------------------------------
  144. Celery now requires Python 2.7 or later,
  145. and also drops support for Python 3.3 so supported versions are:
  146. - CPython 2.7
  147. - CPython 3.4
  148. - CPython 3.5
  149. - PyPy 5.4 (``pypy2``)
  150. - PyPy 5.5-alpha (``pypy3``)
  151. Last major version to support Python 2
  152. --------------------------------------
  153. Starting from Celery 5.0 only Python 3.5+ will be supported.
  154. To make sure you're not affected by this change you should pin
  155. the Celery version in your requirements file, either to a specific
  156. version: ``celery==4.0.0``, or a range: ``celery>=4.0,<5.0``.
  157. Dropping support for Python 2 will enable us to remove massive
  158. amounts of compatibility code, and going with Python 3.5 allows
  159. us to take advantage of typing, async/await, asyncio, and similar
  160. concepts there's no alternative for in older versions.
  161. Celery 4.x will continue to work on Python 2.7, 3.4, 3.5; just as Celery 3.x
  162. still works on Python 2.6.
  163. Django support
  164. --------------
  165. Celery 4.x requires Django 1.8 or later, but we really recommend
  166. using at least Django 1.9 for the new ``transaction.on_commit`` feature.
  167. A common problem when calling tasks from Django is when the task is related
  168. to a model change, and you wish to cancel the task if the transaction is
  169. rolled back, or ensure the task is only executed after the changes have been
  170. written to the database.
  171. ``transaction.atomic`` enables you to solve this problem by adding
  172. the task as a callback to be called only when the transaction is committed.
  173. Example usage:
  174. .. code-block:: python
  175. from functools import partial
  176. from django.db import transaction
  177. from .models import Article, Log
  178. from .tasks import send_article_created_notification
  179. def create_article(request):
  180. with transaction.atomic():
  181. article = Article.objects.create(**request.POST)
  182. # send this task only if the rest of the transaction succeeds.
  183. transaction.on_commit(partial(
  184. send_article_created_notification.delay, article_id=article.pk))
  185. Log.objects.create(type=Log.ARTICLE_CREATED, object_pk=article.pk)
  186. Removed features
  187. ----------------
  188. - Microsoft Windows is no longer supported.
  189. The test suite is passing, and Celery seems to be working with Windows,
  190. but we make no guarantees as we are unable to diagnose issues on this
  191. platform. If you are a company requiring support on this platform,
  192. please get in touch.
  193. - Jython is no longer supported.
  194. Features removed for simplicity
  195. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  196. - Webhook task machinery (``celery.task.http``) has been removed.
  197. Nowadays it's easy to use the :pypi:`requests` module to write
  198. webhook tasks manually. We would love to use requests but we
  199. are simply unable to as there's a very vocal 'anti-dependency'
  200. mob in the Python community
  201. If you need backwards compatibility
  202. you can simply copy + paste the 3.1 version of the module and make sure
  203. it's imported by the worker:
  204. https://github.com/celery/celery/blob/3.1/celery/task/http.py
  205. - Tasks no longer sends error emails.
  206. This also removes support for ``app.mail_admins``, and any functionality
  207. related to sending emails.
  208. - ``celery.contrib.batches`` has been removed.
  209. This was an experimental feature, so not covered by our deprecation
  210. timeline guarantee.
  211. You can copy and pase the existing batches code for use within your projects:
  212. https://github.com/celery/celery/blob/3.1/celery/contrib/batches.py
  213. Features removed for lack of funding
  214. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  215. We announced with the 3.1 release that some transports were
  216. moved to experimental status, and that there'd be no official
  217. support for the transports.
  218. As this subtle hint for the need of funding failed
  219. we've removed them completely, breaking backwards compatibility.
  220. - Using the Django ORM as a broker is no longer supported.
  221. You can still use the Django ORM as a result backend:
  222. see :ref:`django-celery-results` section for more information.
  223. - Using SQLAlchemy as a broker is no longer supported.
  224. You can still use SQLAlchemy as a result backend.
  225. - Using CouchDB as a broker is no longer supported.
  226. You can still use CouchDB as a result backend.
  227. - Using IronMQ as a broker is no longer supported.
  228. - Using Beanstalk as a broker is no longer supported.
  229. In addition some features have been removed completely so that
  230. attempting to use them will raise an exception:
  231. - The ``--autoreload`` feature has been removed.
  232. This was an experimental feature, and not covered by our deprecation
  233. timeline guarantee. The flag is removed completely so the worker
  234. will crash at startup when present. Luckily this
  235. flag isn't used in production systems.
  236. - The experimental ``threads`` pool is no longer supported and has been removed.
  237. - The ``force_execv`` feature is no longer supported.
  238. The ``celery worker`` command now ignores the ``--no-execv``,
  239. ``--force-execv``, and the ``CELERYD_FORCE_EXECV`` setting.
  240. This flag will be removed completely in 5.0 and the worker
  241. will raise an error.
  242. - The old legacy "amqp" result backend has been deprecated, and will
  243. be removed in Celery 5.0.
  244. Please use the ``rpc`` result backend for RPC-style calls, and a
  245. persistent result backend for multi-consumer results.
  246. We think most of these can be fixed without considerable effort, so if you're
  247. interested in getting any of these features back, please get in touch.
  248. **Now to the good news**...
  249. New Task Message Protocol
  250. -------------------------
  251. .. :sha:`e71652d384b1b5df2a4e6145df9f0efb456bc71c`
  252. This version introduces a brand new task message protocol,
  253. the first major change to the protocol since the beginning of the project.
  254. The new protocol is enabled by default in this version and since the new
  255. version isn't backwards compatible you have to be careful when upgrading.
  256. The 3.1.25 version was released to add compatibility with the new protocol
  257. so the easiest way to upgrade is to upgrade to that version first, then
  258. upgrade to 4.0 in a second deployment.
  259. If you wish to keep using the old protocol you may also configure
  260. the protocol version number used:
  261. .. code-block:: python
  262. app = Celery()
  263. app.conf.task_protocol = 1
  264. Read more about the features available in the new protocol in the news
  265. section found later in this document.
  266. .. _v400-upgrade-settings:
  267. Lowercase setting names
  268. -----------------------
  269. In the pursuit of beauty all settings are now renamed to be in all
  270. lowercase and some setting names have been renamed for consistency.
  271. This change is fully backwards compatible so you can still use the uppercase
  272. setting names, but we would like you to upgrade as soon as possible and
  273. you can do this automatically using the :program:`celery upgrade settings`
  274. command:
  275. .. code-block:: console
  276. $ celery upgrade settings proj/settings.py
  277. This command will modify your module in-place to use the new lower-case
  278. names (if you want uppercase with a "``CELERY``" prefix see block below),
  279. and save a backup in :file:`proj/settings.py.orig`.
  280. .. admonition:: For Django users and others who want to keep uppercase names
  281. If you're loading Celery configuration from the Django settings module
  282. then you'll want to keep using the uppercase names.
  283. You also want to use a ``CELERY_`` prefix so that no Celery settings
  284. collide with Django settings used by other apps.
  285. To do this, you'll first need to convert your settings file
  286. to use the new consistent naming scheme, and add the prefix to all
  287. Celery related settings:
  288. .. code-block:: console
  289. $ celery upgrade settings proj/settings.py --django
  290. After upgrading the settings file, you need to set the prefix explicitly
  291. in your ``proj/celery.py`` module:
  292. .. code-block:: python
  293. app.config_from_object('django.conf:settings', namespace='CELERY')
  294. You can find the most up to date Django Celery integration example
  295. here: :ref:`django-first-steps`.
  296. .. note::
  297. This will also add a prefix to settings that didn't previously
  298. have one, for example ``BROKER_URL`` should be written
  299. ``CELERY_BROKER_URL`` with a namespace of ``CELERY``
  300. ``CELERY_BROKER_URL``.
  301. Luckily you don't have to manually change the files, as
  302. the :program:`celery upgrade settings --django` program should do the
  303. right thing.
  304. The loader will try to detect if your configuration is using the new format,
  305. and act accordingly, but this also means you're not allowed to mix and
  306. match new and old setting names, that's unless you provide a value for both
  307. alternatives.
  308. The major difference between previous versions, apart from the lower case
  309. names, are the renaming of some prefixes, like ``celerybeat_`` to ``beat_``,
  310. ``celeryd_`` to ``worker_``.
  311. The ``celery_`` prefix has also been removed, and task related settings
  312. from this name-space is now prefixed by ``task_``, worker related settings
  313. with ``worker_``.
  314. Apart from this most of the settings will be the same in lowercase, apart from
  315. a few special ones:
  316. ===================================== ==========================================================
  317. **Setting name** **Replace with**
  318. ===================================== ==========================================================
  319. ``CELERY_MAX_CACHED_RESULTS`` :setting:`result_cache_max`
  320. ``CELERY_MESSAGE_COMPRESSION`` :setting:`result_compression`/:setting:`task_compression`.
  321. ``CELERY_TASK_RESULT_EXPIRES`` :setting:`result_expires`
  322. ``CELERY_RESULT_DBURI`` :setting:`result_backend`
  323. ``CELERY_RESULT_ENGINE_OPTIONS`` :setting:`database_engine_options`
  324. ``-*-_DB_SHORT_LIVED_SESSIONS`` :setting:`database_short_lived_sessions`
  325. ``CELERY_RESULT_DB_TABLE_NAMES`` :setting:`database_db_names`
  326. ``CELERY_ACKS_LATE`` :setting:`task_acks_late`
  327. ``CELERY_ALWAYS_EAGER`` :setting:`task_always_eager`
  328. ``CELERY_ANNOTATIONS`` :setting:`task_annotations`
  329. ``CELERY_MESSAGE_COMPRESSION`` :setting:`task_compression`
  330. ``CELERY_CREATE_MISSING_QUEUES`` :setting:`task_create_missing_queues`
  331. ``CELERY_DEFAULT_DELIVERY_MODE`` :setting:`task_default_delivery_mode`
  332. ``CELERY_DEFAULT_EXCHANGE`` :setting:`task_default_exchange`
  333. ``CELERY_DEFAULT_EXCHANGE_TYPE`` :setting:`task_default_exchange_type`
  334. ``CELERY_DEFAULT_QUEUE`` :setting:`task_default_queue`
  335. ``CELERY_DEFAULT_RATE_LIMIT`` :setting:`task_default_rate_limit`
  336. ``CELERY_DEFAULT_ROUTING_KEY`` :setting:`task_default_routing_key`
  337. ``-"-_EAGER_PROPAGATES_EXCEPTIONS`` :setting:`task_eager_propagates`
  338. ``CELERY_IGNORE_RESULT`` :setting:`task_ignore_result`
  339. ``CELERY_TASK_PUBLISH_RETRY`` :setting:`task_publish_retry`
  340. ``CELERY_TASK_PUBLISH_RETRY_POLICY`` :setting:`task_publish_retry_policy`
  341. ``CELERY_QUEUES`` :setting:`task_queues`
  342. ``CELERY_ROUTES`` :setting:`task_routes`
  343. ``CELERY_SEND_TASK_SENT_EVENT`` :setting:`task_send_sent_event`
  344. ``CELERY_TASK_SERIALIZER`` :setting:`task_serializer`
  345. ``CELERYD_TASK_SOFT_TIME_LIMIT`` :setting:`task_soft_time_limit`
  346. ``CELERYD_TASK_TIME_LIMIT`` :setting:`task_time_limit`
  347. ``CELERY_TRACK_STARTED`` :setting:`task_track_started`
  348. ``CELERY_DISABLE_RATE_LIMITS`` :setting:`worker_disable_rate_limits`
  349. ``CELERY_ENABLE_REMOTE_CONTROL`` :setting:`worker_enable_remote_control`
  350. ``CELERYD_SEND_EVENTS`` :setting:`worker_send_task_events`
  351. ===================================== ==========================================================
  352. You can see a full table of the changes in :ref:`conf-old-settings-map`.
  353. Json is now the default serializer
  354. ----------------------------------
  355. The time has finally come to end the reign of :mod:`pickle` as the default
  356. serialization mechanism, and json is the default serializer starting from this
  357. version.
  358. This change was :ref:`announced with the release of Celery 3.1
  359. <last-version-to-enable-pickle>`.
  360. If you're still depending on :mod:`pickle` being the default serializer,
  361. then you have to configure your app before upgrading to 4.0:
  362. .. code-block:: python
  363. task_serializer = 'pickle'
  364. result_serializer = 'pickle'
  365. accept_content = {'pickle'}
  366. The Json serializer now also supports some additional types:
  367. - :class:`~datetime.datetime`, :class:`~datetime.time`, :class:`~datetime.date`
  368. Converted to json text, in ISO-8601 format.
  369. - :class:`~decimal.Decimal`
  370. Converted to json text.
  371. - :class:`django.utils.functional.Promise`
  372. Django only: Lazy strings used for translation etc., are evaluated
  373. and conversion to a json type is attempted.
  374. - :class:`uuid.UUID`
  375. Converted to json text.
  376. You can also define a ``__json__`` method on your custom classes to support
  377. JSON serialization (must return a json compatible type):
  378. .. code-block:: python
  379. class Person:
  380. first_name = None
  381. last_name = None
  382. address = None
  383. def __json__(self):
  384. return {
  385. 'first_name': self.first_name,
  386. 'last_name': self.last_name,
  387. 'address': self.address,
  388. }
  389. The Task base class no longer automatically register tasks
  390. ----------------------------------------------------------
  391. The :class:`~@Task` class is no longer using a special meta-class
  392. that automatically registers the task in the task registry.
  393. Instead this is now handled by the :class:`@task` decorators.
  394. If you're still using class based tasks, then you need to register
  395. these manually:
  396. .. code-block:: python
  397. class CustomTask(Task):
  398. def run(self):
  399. print('running')
  400. app.register_task(CustomTask())
  401. The best practice is to use custom task classes only for overriding
  402. general behavior, and then using the task decorator to realize the task:
  403. .. code-block:: python
  404. @app.task(bind=True, base=CustomTask)
  405. def custom(self):
  406. print('running')
  407. This change also means that the ``abstract`` attribute of the task
  408. no longer has any effect.
  409. .. _v400-typing:
  410. Task argument checking
  411. ----------------------
  412. The arguments of the task are now verified when calling the task,
  413. even asynchronously:
  414. .. code-block:: pycon
  415. >>> @app.task
  416. ... def add(x, y):
  417. ... return x + y
  418. >>> add.delay(8, 8)
  419. <AsyncResult: f59d71ca-1549-43e0-be41-4e8821a83c0c>
  420. >>> add.delay(8)
  421. Traceback (most recent call last):
  422. File "<stdin>", line 1, in <module>
  423. File "celery/app/task.py", line 376, in delay
  424. return self.apply_async(args, kwargs)
  425. File "celery/app/task.py", line 485, in apply_async
  426. check_arguments(*(args or ()), **(kwargs or {}))
  427. TypeError: add() takes exactly 2 arguments (1 given)
  428. You can disable the argument checking for any task by setting its
  429. :attr:`~@Task.typing` attribute to :const:`False`:
  430. .. code-block:: pycon
  431. >>> @app.task(typing=False)
  432. ... def add(x, y):
  433. ... return x + y
  434. Or if you would like to disable this completely for all tasks
  435. you can pass ``strict_typing=False`` when creating the app:
  436. .. code-block:: python
  437. app = Celery(..., strict_typing=False)
  438. Redis Events not backward compatible
  439. ------------------------------------
  440. The Redis ``fanout_patterns`` and ``fanout_prefix`` transport
  441. options are now enabled by default.
  442. Workers/monitors without these flags enabled won't be able to
  443. see workers with this flag disabled. They can still execute tasks,
  444. but they cannot receive each others monitoring messages.
  445. You can upgrade in a backward compatible manner by first configuring
  446. your 3.1 workers and monitors to enable the settings, before the final
  447. upgrade to 4.0:
  448. .. code-block:: python
  449. BROKER_TRANSPORT_OPTIONS = {
  450. 'fanout_patterns': True,
  451. 'fanout_prefix': True,
  452. }
  453. Redis Priorities Reversed
  454. -------------------------
  455. Priority 0 is now lowest, 9 is highest.
  456. This change was made to make priority support consistent with how
  457. it works in AMQP.
  458. Contributed by **Alex Koshelev**.
  459. Django: Auto-discover now supports Django app configurations
  460. ------------------------------------------------------------
  461. The ``autodiscover_tasks()`` function can now be called without arguments,
  462. and the Django handler will automatically find your installed apps:
  463. .. code-block:: python
  464. app.autodiscover_tasks()
  465. The Django integration :ref:`example in the documentation
  466. <django-first-steps>` has been updated to use the argument-less call.
  467. This also ensures compatibility with the new, ehm, ``AppConfig`` stuff
  468. introduced in recent Django versions.
  469. Worker direct queues no longer use auto-delete
  470. ----------------------------------------------
  471. Workers/clients running 4.0 will no longer be able to send
  472. worker direct messages to workers running older versions, and vice versa.
  473. If you're relying on worker direct messages you should upgrade
  474. your 3.x workers and clients to use the new routing settings first,
  475. by replacing :func:`celery.utils.worker_direct` with this implementation:
  476. .. code-block:: python
  477. from kombu import Exchange, Queue
  478. worker_direct_exchange = Exchange('C.dq2')
  479. def worker_direct(hostname):
  480. return Queue(
  481. '{hostname}.dq2'.format(hostname),
  482. exchange=worker_direct_exchange,
  483. routing_key=hostname,
  484. )
  485. This feature closed Issue #2492.
  486. Old command-line programs removed
  487. ---------------------------------
  488. Installing Celery will no longer install the ``celeryd``,
  489. ``celerybeat`` and ``celeryd-multi`` programs.
  490. This was announced with the release of Celery 3.1, but you may still
  491. have scripts pointing to the old names, so make sure you update these
  492. to use the new umbrella command:
  493. +-------------------+--------------+-------------------------------------+
  494. | Program | New Status | Replacement |
  495. +===================+==============+=====================================+
  496. | ``celeryd`` | **REMOVED** | :program:`celery worker` |
  497. +-------------------+--------------+-------------------------------------+
  498. | ``celerybeat`` | **REMOVED** | :program:`celery beat` |
  499. +-------------------+--------------+-------------------------------------+
  500. | ``celeryd-multi`` | **REMOVED** | :program:`celery multi` |
  501. +-------------------+--------------+-------------------------------------+
  502. .. _v400-news:
  503. News
  504. ====
  505. New protocol highlights
  506. -----------------------
  507. The new protocol fixes many problems with the old one, and enables
  508. some long-requested features:
  509. - Most of the data are now sent as message headers, instead of being
  510. serialized with the message body.
  511. In version 1 of the protocol the worker always had to deserialize
  512. the message to be able to read task meta-data like the task id,
  513. name, etc. This also meant that the worker was forced to double-decode
  514. the data, first deserializing the message on receipt, serializing
  515. the message again to send to child process, then finally the child process
  516. deserializes the message again.
  517. Keeping the meta-data fields in the message headers means the worker
  518. doesn't actually have to decode the payload before delivering
  519. the task to the child process, and also that it's now possible
  520. for the worker to reroute a task written in a language different
  521. from Python to a different worker.
  522. - A new ``lang`` message header can be used to specify the programming
  523. language the task is written in.
  524. - Worker stores results for internal errors like ``ContentDisallowed``,
  525. and other deserialization errors.
  526. - Worker stores results and sends monitoring events for unregistered
  527. task errors.
  528. - Worker calls callbacks/errbacks even when the result is sent by the
  529. parent process (e.g., :exc:`WorkerLostError` when a child process
  530. terminates, deserialization errors, unregistered tasks).
  531. - A new ``origin`` header contains information about the process sending
  532. the task (worker node-name, or PID and host-name information).
  533. - A new ``shadow`` header allows you to modify the task name used in logs.
  534. This is useful for dispatch like patterns, like a task that calls
  535. any function using pickle (don't do this at home):
  536. .. code-block:: python
  537. from celery import Task
  538. from celery.utils.imports import qualname
  539. class call_as_task(Task):
  540. def shadow_name(self, args, kwargs, options):
  541. return 'call_as_task:{0}'.format(qualname(args[0]))
  542. def run(self, fun, *args, **kwargs):
  543. return fun(*args, **kwargs)
  544. call_as_task = app.register_task(call_as_task())
  545. - New ``argsrepr`` and ``kwargsrepr`` fields contain textual representations
  546. of the task arguments (possibly truncated) for use in logs, monitors, etc.
  547. This means the worker doesn't have to deserialize the message payload
  548. to display the task arguments for informational purposes.
  549. - Chains now use a dedicated ``chain`` field enabling support for chains
  550. of thousands and more tasks.
  551. - New ``parent_id`` and ``root_id`` headers adds information about
  552. a tasks relationship with other tasks.
  553. - ``parent_id`` is the task id of the task that called this task
  554. - ``root_id`` is the first task in the work-flow.
  555. These fields can be used to improve monitors like flower to group
  556. related messages together (like chains, groups, chords, complete
  557. work-flows, etc).
  558. - ``app.TaskProducer`` replaced by :meth:`@amqp.create_task_message` and
  559. :meth:`@amqp.send_task_message`.
  560. Dividing the responsibilities into creating and sending means that
  561. people who want to send messages using a Python AMQP client directly,
  562. doesn't have to implement the protocol.
  563. The :meth:`@amqp.create_task_message` method calls either
  564. :meth:`@amqp.as_task_v2`, or :meth:`@amqp.as_task_v1` depending
  565. on the configured task protocol, and returns a special
  566. :class:`~celery.app.amqp.task_message` tuple containing the
  567. headers, properties and body of the task message.
  568. .. seealso::
  569. The new task protocol is documented in full here:
  570. :ref:`message-protocol-task-v2`.
  571. Prefork Pool Improvements
  572. -------------------------
  573. Tasks now log from the child process
  574. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  575. Logging of task success/failure now happens from the child process
  576. executing the task. As a result logging utilities,
  577. like Sentry can get full information about tasks, including
  578. variables in the traceback stack.
  579. ``-Ofair`` is now the default scheduling strategy
  580. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  581. To re-enable the default behavior in 3.1 use the ``-Ofast`` command-line
  582. option.
  583. There's been lots of confusion about what the ``-Ofair`` command-line option
  584. does, and using the term "prefetch" in explanations have probably not helped
  585. given how confusing this terminology is in AMQP.
  586. When a Celery worker using the prefork pool receives a task, it needs to
  587. delegate that task to a child process for execution.
  588. The prefork pool has a configurable number of child processes
  589. (``--concurrency``) that can be used to execute tasks, and each child process
  590. uses pipes/sockets to communicate with the parent process:
  591. - inqueue (pipe/socket): parent sends task to the child process
  592. - outqueue (pipe/socket): child sends result/return value to the parent.
  593. In Celery 3.1 the default scheduling mechanism was simply to send
  594. the task to the first ``inqueue`` that was writable, with some heuristics
  595. to make sure we round-robin between them to ensure each child process
  596. would receive the same amount of tasks.
  597. This means that in the default scheduling strategy, a worker may send
  598. tasks to the same child process that is already executing a task. If that
  599. task is long running, it may block the waiting task for a long time. Even
  600. worse, hundreds of short-running tasks may be stuck behind a long running task
  601. even when there are child processes free to do work.
  602. The ``-Ofair`` scheduling strategy was added to avoid this situation,
  603. and when enabled it adds the rule that no task should be sent to the a child
  604. process that is already executing a task.
  605. The fair scheduling strategy may perform slightly worse if you have only
  606. short running tasks.
  607. Limit child process resident memory size
  608. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  609. .. :sha:`5cae0e754128750a893524dcba4ae030c414de33`
  610. You can now limit the maximum amount of memory allocated per prefork
  611. pool child process by setting the worker
  612. :option:`--max-memory-per-child <celery worker --max-memory-per-child>` option,
  613. or the :setting:`worker_max_memory_per_child` setting.
  614. The limit is for RSS/resident memory size and is specified in kilobytes.
  615. A child process having exceeded the limit will be terminated and replaced
  616. with a new process after the currently executing task returns.
  617. See :ref:`worker-max-memory-per-child` for more information.
  618. Contributed by **Dave Smith**.
  619. One log-file per child process
  620. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  621. Init-scrips and :program:`celery multi` now uses the `%I` log file format
  622. option (e.g., :file:`/var/log/celery/%n%I.log`).
  623. This change was necessary to ensure each child
  624. process has a separate log file after moving task logging
  625. to the child process, as multiple processes writing to the same
  626. log file can cause corruption.
  627. You're encouraged to upgrade your init-scripts and
  628. :program:`celery multi` arguments to use this new option.
  629. Transports
  630. ----------
  631. RabbitMQ priority queue support
  632. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  633. See :ref:`routing-options-rabbitmq-priorities` for more information.
  634. Contributed by **Gerald Manipon**.
  635. Configure broker URL for read/write separately
  636. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  637. New :setting:`broker_read_url` and :setting:`broker_write_url` settings
  638. have been added so that separate broker URLs can be provided
  639. for connections used for consuming/publishing.
  640. In addition to the configuration options, two new methods have been
  641. added the app API:
  642. - ``app.connection_for_read()``
  643. - ``app.connection_for_write()``
  644. These should now be used in place of ``app.connection()`` to specify
  645. the intent of the required connection.
  646. .. note::
  647. Two connection pools are available: ``app.pool`` (read), and
  648. ``app.producer_pool`` (write). The latter doesn't actually give connections
  649. but full :class:`kombu.Producer` instances.
  650. .. code-block:: python
  651. def publish_some_message(app, producer=None):
  652. with app.producer_or_acquire(producer) as producer:
  653. ...
  654. def consume_messages(app, connection=None):
  655. with app.connection_or_acquire(connection) as connection:
  656. ...
  657. RabbitMQ queue extensions support
  658. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  659. Queue declarations can now set a message TTL and queue expiry time directly,
  660. by using the ``message_ttl`` and ``expires`` arguments
  661. New arguments have been added to :class:`~kombu.Queue` that lets
  662. you directly and conveniently configure RabbitMQ queue extensions
  663. in queue declarations:
  664. - ``Queue(expires=20.0)``
  665. Set queue expiry time in float seconds.
  666. See :attr:`kombu.Queue.expires`.
  667. - ``Queue(message_ttl=30.0)``
  668. Set queue message time-to-live float seconds.
  669. See :attr:`kombu.Queue.message_ttl`.
  670. - ``Queue(max_length=1000)``
  671. Set queue max length (number of messages) as int.
  672. See :attr:`kombu.Queue.max_length`.
  673. - ``Queue(max_length_bytes=1000)``
  674. Set queue max length (message size total in bytes) as int.
  675. See :attr:`kombu.Queue.max_length_bytes`.
  676. - ``Queue(max_priority=10)``
  677. Declare queue to be a priority queue that routes messages
  678. based on the ``priority`` field of the message.
  679. See :attr:`kombu.Queue.max_priority`.
  680. Amazon SQS transport now officially supported
  681. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  682. The SQS broker transport has been rewritten to use async I/O and as such
  683. joins RabbitMQ, Redis and QPid as officially supported transports.
  684. The new implementation also takes advantage of long polling,
  685. and closes several issues related to using SQS as a broker.
  686. This work was sponsored by Nextdoor.
  687. Apache QPid transport now officially supported
  688. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  689. Contributed by **Brian Bouterse**.
  690. Redis: Support for Sentinel
  691. ---------------------------
  692. You can point the connection to a list of sentinel URLs like:
  693. .. code-block:: text
  694. sentinel://0.0.0.0:26379;sentinel://0.0.0.0:26380/...
  695. where each sentinel is separated by a `;`. Multiple sentinels are handled
  696. by :class:`kombu.Connection` constructor, and placed in the alternative
  697. list of servers to connect to in case of connection failure.
  698. Contributed by **Sergey Azovskov**, and **Lorenzo Mancini**.
  699. Tasks
  700. -----
  701. Task Auto-retry Decorator
  702. ~~~~~~~~~~~~~~~~~~~~~~~~~
  703. Writing custom retry handling for exception events is so common
  704. that we now have built-in support for it.
  705. For this a new ``autoretry_for`` argument is now supported by
  706. the task decorators, where you can specify a tuple of exceptions
  707. to automatically retry for:
  708. .. code-block:: python
  709. from twitter.exceptions import FailWhaleError
  710. @app.task(autoretry_for=(FailWhaleError,))
  711. def refresh_timeline(user):
  712. return twitter.refresh_timeline(user)
  713. See :ref:`task-autoretry` for more information.
  714. Contributed by **Dmitry Malinovsky**.
  715. .. :sha:`75246714dd11e6c463b9dc67f4311690643bff24`
  716. ``Task.replace`` Improvements
  717. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  718. - ``self.replace(signature)`` can now replace any task, chord or group,
  719. and the signature to replace with can be a chord, group or any other
  720. type of signature.
  721. - No longer inherits the callbacks and errbacks of the existing task.
  722. If you replace a node in a tree, then you wouldn't expect the new node to
  723. inherit the children of the old node.
  724. - ``Task.replace_in_chord`` has been removed, use ``.replace`` instead.
  725. - If the replacement is a group, that group will be automatically converted
  726. to a chord, where the callback "accumulates" the results of the group tasks.
  727. A new built-in task (`celery.accumulate` was added for this purpose)
  728. Contributed by **Steeve Morin**, and **Ask Solem**.
  729. Remote Task Tracebacks
  730. ~~~~~~~~~~~~~~~~~~~~~~
  731. The new :setting:`task_remote_tracebacks` will make task tracebacks more
  732. useful by injecting the stack of the remote worker.
  733. This feature requires the additional :pypi:`tblib` library.
  734. Contributed by **Ionel Cristian Mărieș**.
  735. Handling task connection errors
  736. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  737. Connection related errors occuring while sending a task is now re-raised
  738. as a :exc:`kombu.exceptions.OperationalError` error:
  739. .. code-block:: pycon
  740. >>> try:
  741. ... add.delay(2, 2)
  742. ... except add.OperationalError as exc:
  743. ... print('Could not send task %r: %r' % (add, exc))
  744. See :ref:`calling-connection-errors` for more information.
  745. Gevent/Eventlet: Dedicated thread for consuming results
  746. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  747. When using :pypi:`gevent`, or :pypi:`eventlet` there is now a single
  748. thread responsible for consuming events.
  749. This means that if you have many calls retrieving results, there will be
  750. a dedicated thread for consuming them:
  751. .. code-block:: python
  752. result = add.delay(2, 2)
  753. # this call will delegate to the result consumer thread:
  754. # once the consumer thread has received the result this greenlet can
  755. # continue.
  756. value = result.get(timeout=3)
  757. This makes performing RPC calls when using gevent/eventlet perform much
  758. better.
  759. ``AsyncResult.then(on_success, on_error)``
  760. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  761. The AsyncResult API has been extended to support the :class:`~vine.promise` protocol.
  762. This currently only works with the RPC (amqp) and Redis result backends, but
  763. lets you attach callbacks to when tasks finish:
  764. .. code-block:: python
  765. import gevent.monkey
  766. monkey.patch_all()
  767. import time
  768. from celery import Celery
  769. app = Celery(broker='amqp://', backend='rpc')
  770. @app.task
  771. def add(x, y):
  772. return x + y
  773. def on_result_ready(result):
  774. print('Received result for id %r: %r' % (result.id, result.result,))
  775. add.delay(2, 2).then(on_result_ready)
  776. time.sleep(3) # run gevent event loop for a while.
  777. Demonstrated using :pypi:`gevent` here, but really this is an API that's more
  778. useful in callback-based event loops like :pypi:`twisted`, or :pypi:`tornado`.
  779. New Task Router API
  780. ~~~~~~~~~~~~~~~~~~~
  781. The :setting:`task_routes` setting can now hold functions, and map routes
  782. now support glob patterns and regexes.
  783. Instead of using router classes you can now simply define a function:
  784. .. code-block:: python
  785. def route_for_task(name, args, kwargs, options, task=None, **kwargs):
  786. from proj import tasks
  787. if name == tasks.add.name:
  788. return {'queue': 'hipri'}
  789. If you don't need the arguments you can use start arguments, just make
  790. sure you always also accept star arguments so that we have the ability
  791. to add more features in the future:
  792. .. code-block:: python
  793. def route_for_task(name, *args, **kwargs):
  794. from proj import tasks
  795. if name == tasks.add.name:
  796. return {'queue': 'hipri', 'priority': 9}
  797. Both the ``options`` argument and the new ``task`` keyword argument
  798. are new to the function-style routers, and will make it easier to write
  799. routers based on execution options, or properties of the task.
  800. The optional ``task`` keyword argument won't be set if a task is called
  801. by name using :meth:`@send_task`.
  802. For more examples, including using glob/regexes in routers please see
  803. :setting:`task_routes` and :ref:`routing-automatic`.
  804. Canvas Refactor
  805. ~~~~~~~~~~~~~~~
  806. The canvas/work-flow implementation have been heavily refactored
  807. to fix some long outstanding issues.
  808. .. :sha:`d79dcd8e82c5e41f39abd07ffed81ca58052bcd2`
  809. .. :sha:`1e9dd26592eb2b93f1cb16deb771cfc65ab79612`
  810. .. :sha:`e442df61b2ff1fe855881c1e2ff9acc970090f54`
  811. .. :sha:`0673da5c09ac22bdd49ba811c470b73a036ee776`
  812. - Error callbacks can now take real exception and traceback instances
  813. (Issue #2538).
  814. .. code-block:: pycon
  815. >>> add.s(2, 2).on_error(log_error.s()).delay()
  816. Where ``log_error`` could be defined as:
  817. .. code-block:: python
  818. @app.task
  819. def log_error(request, exc, traceback):
  820. with open(os.path.join('/var/errors', request.id), 'a') as fh:
  821. print('--\n\n{0} {1} {2}'.format(
  822. task_id, exc, traceback), file=fh)
  823. See :ref:`guide-canvas` for more examples.
  824. - ``chain(a, b, c)`` now works the same as ``a | b | c``.
  825. This means chain may no longer return an instance of ``chain``,
  826. instead it may optimize the workflow so that e.g. two groups
  827. chained together becomes one group.
  828. - Now unrolls groups within groups into a single group (Issue #1509).
  829. - chunks/map/starmap tasks now routes based on the target task
  830. - chords and chains can now be immutable.
  831. - Fixed bug where serialized signatures weren't converted back into
  832. signatures (Issue #2078)
  833. Fix contributed by **Ross Deane**.
  834. - Fixed problem where chains and groups didn't work when using JSON
  835. serialization (Issue #2076).
  836. Fix contributed by **Ross Deane**.
  837. - Creating a chord no longer results in multiple values for keyword
  838. argument 'task_id' (Issue #2225).
  839. Fix contributed by **Aneil Mallavarapu**.
  840. - Fixed issue where the wrong result is returned when a chain
  841. contains a chord as the penultimate task.
  842. Fix contributed by **Aneil Mallavarapu**.
  843. - Special case of ``group(A.s() | group(B.s() | C.s()))`` now works.
  844. - Chain: Fixed bug with incorrect id set when a subtask is also a chain.
  845. - ``group | group`` is now flattened into a single group (Issue #2573).
  846. - Fixed issue where ``group | task`` wasn't upgrading correctly
  847. to chord (Issue #2922).
  848. - Chords now properly sets ``result.parent`` links.
  849. - ``chunks``/``map``/``starmap`` are now routed based on the target task.
  850. - ``Signature.link`` now works when argument is scalar (not a list)
  851. (Issue #2019).
  852. - ``group()`` now properly forwards keyword arguments (Issue #3426).
  853. Fix contributed by **Samuel Giffard**.
  854. - A ``chord`` where the header group only consists of a single task
  855. is now turned into a simple chain.
  856. - Passing a ``link`` argument to ``group.apply_async()`` now raises an error
  857. (Issue #3508).
  858. - ``chord | sig`` now attaches to the chord callback (Issue #3356).
  859. Periodic Tasks
  860. --------------
  861. New API for configuring periodic tasks
  862. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  863. This new API enables you to use signatures when defining periodic tasks,
  864. removing the chance of mistyping task names.
  865. An example of the new API is :ref:`here <beat-entries>`.
  866. .. :sha:`bc18d0859c1570f5eb59f5a969d1d32c63af764b`
  867. .. :sha:`132d8d94d38f4050db876f56a841d5a5e487b25b`
  868. Optimized Beat implementation
  869. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  870. The :program:`celery beat` implementation has been optimized
  871. for millions of periodic tasks by using a heap to schedule entries.
  872. Contributed by **Ask Solem** and **Alexander Koshelev**.
  873. Schedule tasks based on sunrise, sunset, dawn and dusk
  874. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  875. See :ref:`beat-solar` for more information.
  876. Contributed by **Mark Parncutt**.
  877. Result Backends
  878. ---------------
  879. RPC Result Backend matured
  880. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  881. Lots of bugs in the previously experimental RPC result backend have been fixed
  882. and can now be considered to production use.
  883. Contributed by **Ask Solem**, **Morris Tweed**.
  884. Redis: Result backend optimizations
  885. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  886. ``result.get()`` is now using pub/sub for streaming task results
  887. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  888. Calling ``result.get()`` when using the Redis result backend
  889. used to be extremely expensive as it was using polling to wait
  890. for the result to become available. A default polling
  891. interval of 0.5 seconds didn't help performance, but was
  892. necessary to avoid a spin loop.
  893. The new implementation is using Redis Pub/Sub mechanisms to
  894. publish and retrieve results immediately, greatly improving
  895. task round-trip times.
  896. Contributed by **Yaroslav Zhavoronkov** and **Ask Solem**.
  897. New optimized chord join implementation
  898. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  899. This was an experimental feature introduced in Celery 3.1,
  900. that could only be enabled by adding ``?new_join=1`` to the
  901. result backend URL configuration.
  902. We feel that the implementation has been tested thoroughly enough
  903. to be considered stable and enabled by default.
  904. The new implementation greatly reduces the overhead of chords,
  905. and especially with larger chords the performance benefit can be massive.
  906. New Riak result backend introduced
  907. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  908. See :ref:`conf-riak-result-backend` for more information.
  909. Contributed by **Gilles Dartiguelongue**, **Alman One** and **NoKriK**.
  910. New CouchDB result backend introduced
  911. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  912. See :ref:`conf-couchdb-result-backend` for more information.
  913. Contributed by **Nathan Van Gheem**.
  914. New Consul result backend introduced
  915. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  916. Add support for Consul as a backend using the Key/Value store of Consul.
  917. Consul has an HTTP API where through you can store keys with their values.
  918. The backend extends KeyValueStoreBackend and implements most of the methods.
  919. Mainly to set, get and remove objects.
  920. This allows Celery to store Task results in the K/V store of Consul.
  921. Consul also allows to set a TTL on keys using the Sessions from Consul. This way
  922. the backend supports auto expiry of Task results.
  923. For more information on Consul visit http://consul.io/
  924. The backend uses :pypi:`python-consul` for talking to the HTTP API.
  925. This package is fully Python 3 compliant just as this backend is:
  926. .. code-block:: console
  927. $ pip install python-consul
  928. That installs the required package to talk to Consul's HTTP API from Python.
  929. You can also specify consul as an extension in your dependency on Celery:
  930. .. code-block:: console
  931. $ pip install celery[consul]
  932. See :ref:`bundles` for more information.
  933. Contributed by **Wido den Hollander**.
  934. Brand new Cassandra result backend
  935. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  936. A brand new Cassandra backend utilizing the new :pypi:`cassandra-driver`
  937. library is replacing the old result backend using the older
  938. :pypi:`pycassa` library.
  939. See :ref:`conf-cassandra-result-backend` for more information.
  940. To depend on Celery with Cassandra as the result backend use:
  941. .. code-block:: console
  942. $ pip install celery[cassandra]
  943. You can also combine multiple extension requirements,
  944. please see :ref:`bundles` for more information.
  945. .. # XXX What changed?
  946. New Elasticsearch result backend introduced
  947. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  948. See :ref:`conf-elasticsearch-result-backend` for more information.
  949. To depend on Celery with Elasticsearch as the result bakend use:
  950. .. code-block:: console
  951. $ pip install celery[elasticsearch]
  952. You can also combine multiple extension requirements,
  953. please see :ref:`bundles` for more information.
  954. Contributed by **Ahmet Demir**.
  955. New File-system result backend introduced
  956. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  957. See :ref:`conf-filesystem-result-backend` for more information.
  958. Contributed by **Môshe van der Sterre**.
  959. Event Batching
  960. --------------
  961. Events are now buffered in the worker and sent as a list, reducing
  962. the overhead required to send monitoring events.
  963. For authors of custom event monitors there will be no action
  964. required as long as you're using the Python Celery
  965. helpers (:class:`~@events.Receiver`) to implement your monitor.
  966. However, if you're parsing raw event messages you must now account
  967. for batched event messages, as they differ from normal event messages
  968. in the following way:
  969. - The routing key for a batch of event messages will be set to
  970. ``<event-group>.multi`` where the only batched event group
  971. is currently ``task`` (giving a routing key of ``task.multi``).
  972. - The message body will be a serialized list-of-dictionaries instead
  973. of a dictionary. Each item in the list can be regarded
  974. as a normal event message body.
  975. .. :sha:`03399b4d7c26fb593e61acf34f111b66b340ba4e`
  976. In Other News...
  977. ----------------
  978. Requirements
  979. ~~~~~~~~~~~~
  980. - Now depends on :ref:`Kombu 4.0 <kombu:version-4.0>`.
  981. - Now depends on :pypi:`billiard` version 3.5.
  982. - No longer depends on :pypi:`anyjson`. Good-bye old friend :(
  983. Tasks
  984. ~~~~~
  985. - The "anon-exchange" is now used for simple name-name direct routing.
  986. This increases performance as it completely bypasses the routing table,
  987. in addition it also improves reliability for the Redis broker transport.
  988. - An empty ResultSet now evaluates to True.
  989. Fix contributed by **Colin McIntosh**.
  990. - The default routing key and exchange name is now taken from the
  991. :setting:`task_default_queue` setting.
  992. This means that to change the name of the default queue, you now
  993. only have to set a single setting.
  994. - New :setting:`task_reject_on_worker_lost` setting, and
  995. :attr:`~@Task.reject_on_worker_lost` task attribute decides what happens
  996. when the child worker process executing a late ack task is terminated.
  997. Contributed by **Michael Permana**.
  998. - ``Task.subtask`` renamed to ``Task.signature`` with alias.
  999. - ``Task.subtask_from_request`` renamed to
  1000. ``Task.signature_from_request`` with alias.
  1001. - The ``delivery_mode`` attribute for :class:`kombu.Queue` is now
  1002. respected (Issue #1953).
  1003. - Routes in :setting:`task-routes` can now specify a
  1004. :class:`~kombu.Queue` instance directly.
  1005. Example:
  1006. .. code-block:: python
  1007. task_routes = {'proj.tasks.add': {'queue': Queue('add')}}
  1008. - ``AsyncResult`` now raises :exc:`ValueError` if task_id is None.
  1009. (Issue #1996).
  1010. - Retried tasks didn't forward expires setting (Issue #3297).
  1011. - ``result.get()`` now supports an ``on_message`` argument to set a
  1012. callback to be called for every message received.
  1013. - New abstract classes added:
  1014. - :class:`~celery.utils.abstract.CallableTask`
  1015. Looks like a task.
  1016. - :class:`~celery.utils.abstract.CallableSignature`
  1017. Looks like a task signature.
  1018. - ``Task.replace`` now properly forwards callbacks (Issue #2722).
  1019. Fix contributed by **Nicolas Unravel**.
  1020. - ``Task.replace``: Append to chain/chord (Closes #3232)
  1021. Fixed issue #3232, adding the signature to the chain (if there's any).
  1022. Fixed the chord suppress if the given signature contains one.
  1023. Fix contributed by :github_user:`honux`.
  1024. - Task retry now also throws in eager mode.
  1025. Fix contributed by **Feanil Patel**.
  1026. Beat
  1027. ~~~~
  1028. - Fixed crontab infinite loop with invalid date.
  1029. When occurrence can never be reached (example, April, 31th), trying
  1030. to reach the next occurrence would trigger an infinite loop.
  1031. Try fixing that by raising a :exc:`RuntimeError` after 2,000 iterations
  1032. (Also added a test for crontab leap years in the process)
  1033. Fix contributed by **Romuald Brunet**.
  1034. - Now ensures the program exits with a non-zero exit code when an
  1035. exception terminates the service.
  1036. Fix contributed by **Simon Peeters**.
  1037. App
  1038. ~~~
  1039. - Dates are now always timezone aware even if
  1040. :setting:`enable_utc` is disabled (Issue #943).
  1041. Fix contributed by **Omer Katz**.
  1042. - **Config**: App preconfiguration is now also pickled with the configuration.
  1043. Fix contributed by **Jeremy Zafran**.
  1044. - The application can now change how task names are generated using
  1045. the :meth:`~@gen_task_name` method.
  1046. Contributed by **Dmitry Malinovsky**.
  1047. - App has new ``app.current_worker_task`` property that
  1048. returns the task that's currently being worked on (or :const:`None`).
  1049. (Issue #2100).
  1050. Logging
  1051. ~~~~~~~
  1052. - :func:`~celery.utils.log.get_task_logger` now raises an exception
  1053. if trying to use the name "celery" or "celery.task" (Issue #3475).
  1054. Execution Pools
  1055. ~~~~~~~~~~~~~~~
  1056. - **Eventlet/Gevent**: now enables AMQP heartbeat (Issue #3338).
  1057. - **Eventlet/Gevent**: Fixed race condition leading to "simultaneous read"
  1058. errors (Issue #2755).
  1059. - **Prefork**: Prefork pool now uses ``poll`` instead of ``select`` where
  1060. available (Issue #2373).
  1061. - **Prefork**: Fixed bug where the pool would refuse to shut down the
  1062. worker (Issue #2606).
  1063. - **Eventlet**: Now returns pool size in :program:`celery inspect stats`
  1064. command.
  1065. Contributed by **Alexander Oblovatniy**.
  1066. Testing
  1067. -------
  1068. - Celery is now a :pypi:`pytest` plugin, including fixtures
  1069. useful for unit and integration testing.
  1070. See the :ref:`testing user guide <testing>` for more information.
  1071. Transports
  1072. ~~~~~~~~~~
  1073. - ``amqps://`` can now be specified to require SSL.
  1074. - **Redis Transport**: The Redis transport now supports the
  1075. :setting:`broker_use_ssl` option.
  1076. Contributed by **Robert Kolba**.
  1077. - JSON serializer now calls ``obj.__json__`` for unsupported types.
  1078. This means you can now define a ``__json__`` method for custom
  1079. types that can be reduced down to a built-in json type.
  1080. Example:
  1081. .. code-block:: python
  1082. class Person:
  1083. first_name = None
  1084. last_name = None
  1085. address = None
  1086. def __json__(self):
  1087. return {
  1088. 'first_name': self.first_name,
  1089. 'last_name': self.last_name,
  1090. 'address': self.address,
  1091. }
  1092. - JSON serializer now handles datetime's, Django promise, UUID and Decimal.
  1093. - New ``Queue.consumer_arguments`` can be used for the ability to
  1094. set consumer priority via ``x-priority``.
  1095. See https://www.rabbitmq.com/consumer-priority.html
  1096. Example:
  1097. .. code-block:: python
  1098. consumer = Consumer(channel, consumer_arguments={'x-priority': 3})
  1099. - Queue/Exchange: ``no_declare`` option added (also enabled for
  1100. internal amq. exchanges).
  1101. Programs
  1102. ~~~~~~~~
  1103. - Celery is now using :mod:`argparse`, instead of :mod:`optparse`.
  1104. - All programs now disable colors if the controlling terminal is not a TTY.
  1105. - :program:`celery worker`: The ``-q`` argument now disables the startup
  1106. banner.
  1107. - :program:`celery worker`: The "worker ready" message is now logged
  1108. using severity info, instead of warn.
  1109. - :program:`celery multi`: ``%n`` format for is now synonym with
  1110. ``%N`` to be consistent with :program:`celery worker`.
  1111. - :program:`celery inspect`/:program:`celery control`: now supports a new
  1112. :option:`--json <celery inspect --json>` option to give output in json format.
  1113. - :program:`celery inspect registered`: now ignores built-in tasks.
  1114. - :program:`celery purge` now takes ``-Q`` and ``-X`` options
  1115. used to specify what queues to include and exclude from the purge.
  1116. - New :program:`celery logtool`: Utility for filtering and parsing
  1117. celery worker log-files
  1118. - :program:`celery multi`: now passes through `%i` and `%I` log
  1119. file formats.
  1120. - General: ``%p`` can now be used to expand to the full worker node-name
  1121. in log-file/pid-file arguments.
  1122. - A new command line option
  1123. :option:`--executable <celery worker --executable>` is now
  1124. available for daemonizing programs (:program:`celery worker` and
  1125. :program:`celery beat`).
  1126. Contributed by **Bert Vanderbauwhede**.
  1127. - :program:`celery worker`: supports new
  1128. :option:`--prefetch-multiplier <celery worker --prefetch-multiplier>` option.
  1129. Contributed by **Mickaël Penhard**.
  1130. - The ``--loader`` argument is now always effective even if an app argument is
  1131. set (Issue #3405).
  1132. - inspect/control now takes commands from registry
  1133. This means user remote-control commands can also be used from the
  1134. command-line.
  1135. Note that you need to specify the arguments/and type of arguments
  1136. for the arguments to be correctly passed on the command-line.
  1137. There are now two decorators, which use depends on the type of
  1138. command: `@inspect_command` + `@control_command`:
  1139. .. code-block:: python
  1140. from celery.worker.control import control_command
  1141. @control_command(
  1142. args=[('n', int)]
  1143. signature='[N=1]',
  1144. )
  1145. def something(state, n=1, **kwargs):
  1146. ...
  1147. Here ``args`` is a list of args supported by the command.
  1148. The list must contain tuples of ``(argument_name, type)``.
  1149. ``signature`` is just the command-line help used in e.g.
  1150. ``celery -A proj control --help``.
  1151. Commands also support `variadic` arguments, which means that any
  1152. arguments left over will be added to a single variable. Here demonstrated
  1153. by the ``terminate`` command which takes a signal argument and a variable
  1154. number of task_ids:
  1155. .. code-block:: python
  1156. from celery.worker.control import control_command
  1157. @control_command(
  1158. args=[('signal', str)],
  1159. signature='<signal> [id1, [id2, [..., [idN]]]]',
  1160. variadic='ids',
  1161. )
  1162. def terminate(state, signal, ids, **kwargs):
  1163. ...
  1164. This command can now be called using:
  1165. .. code-block:: console
  1166. $ celery -A proj control terminate SIGKILL id1 id2 id3`
  1167. See :ref:`worker-custom-control-commands` for more information.
  1168. Worker
  1169. ~~~~~~
  1170. - Improvements and fixes for :class:`~celery.utils.collections.LimitedSet`.
  1171. Getting rid of leaking memory + adding ``minlen`` size of the set:
  1172. the minimal residual size of the set after operating for some time.
  1173. ``minlen`` items are kept, even if they should've been expired.
  1174. Problems with older and even more old code:
  1175. #. Heap would tend to grow in some scenarios
  1176. (like adding an item multiple times).
  1177. #. Adding many items fast wouldn't clean them soon enough (if ever).
  1178. #. When talking to other workers, revoked._data was sent, but
  1179. it was processed on the other side as iterable.
  1180. That means giving those keys new (current)
  1181. time-stamp. By doing this workers could recycle
  1182. items forever. Combined with 1) and 2), this means that in
  1183. large set of workers, you're getting out of memory soon.
  1184. All those problems should be fixed now.
  1185. This should fix issues #3095, #3086.
  1186. Contributed by **David Pravec**.
  1187. - New settings to control remote control command queues.
  1188. - :setting:`control_queue_expires`
  1189. Set queue expiry time for both remote control command queues,
  1190. and remote control reply queues.
  1191. - :setting:`control_queue_ttl`
  1192. Set message time-to-live for both remote control command queues,
  1193. and remote control reply queues.
  1194. Contributed by **Alan Justino**.
  1195. - The :signal:`worker_shutdown` signal is now always called during shutdown.
  1196. Previously it would not be called if the worker instance was collected
  1197. by gc first.
  1198. - Worker now only starts the remote control command consumer if the
  1199. broker transport used actually supports them.
  1200. - Gossip now sets ``x-message-ttl`` for event queue to heartbeat_interval s.
  1201. (Issue #2005).
  1202. - Now preserves exit code (Issue #2024).
  1203. - Now rejects messages with an invalid ETA value (instead of ack, which means
  1204. they will be sent to the dead-letter exchange if one is configured).
  1205. - Fixed crash when the ``-purge`` argument was used.
  1206. - Log--level for unrecoverable errors changed from ``error`` to
  1207. ``critical``.
  1208. - Improved rate limiting accuracy.
  1209. - Account for missing timezone information in task expires field.
  1210. Fix contributed by **Albert Wang**.
  1211. - The worker no longer has a ``Queues`` bootsteps, as it is now
  1212. superfluous.
  1213. - Now emits the "Received task" line even for revoked tasks.
  1214. (Issue #3155).
  1215. - Now respects :setting:`broker_connection_retry` setting.
  1216. Fix contributed by **Nat Williams**.
  1217. - New :setting:`control_queue_ttl` and :setting:`control_queue_expires`
  1218. settings now enables you to configure remote control command
  1219. message TTLs, and queue expiry time.
  1220. Contributed by **Alan Justino**.
  1221. - New :data:`celery.worker.state.requests` enables O(1) loookup
  1222. of active/reserved tasks by id.
  1223. - Auto-scale didn't always update keep-alive when scaling down.
  1224. Fix contributed by **Philip Garnero**.
  1225. - Fixed typo ``options_list`` -> ``option_list``.
  1226. Fix contributed by **Greg Wilbur**.
  1227. - Some worker command-line arguments and ``Worker()`` class arguments have
  1228. been renamed for consistency.
  1229. All of these have aliases for backward compatibility.
  1230. - ``--send-events`` -> ``--task-events``
  1231. - ``--schedule`` -> ``--schedule-filename``
  1232. - ``--maxtasksperchild`` -> ``--max-tasks-per-child``
  1233. - ``Beat(scheduler_cls=)`` -> ``Beat(scheduler=)``
  1234. - ``Worker(send_events=True)`` -> ``Worker(task_events=True)``
  1235. - ``Worker(task_time_limit=)`` -> ``Worker(time_limit=``)
  1236. - ``Worker(task_soft_time_limit=)`` -> ``Worker(soft_time_limit=)``
  1237. - ``Worker(state_db=)`` -> ``Worker(statedb=)``
  1238. - ``Worker(working_directory=)`` -> ``Worker(workdir=)``
  1239. Debugging Utilities
  1240. ~~~~~~~~~~~~~~~~~~~
  1241. - :mod:`celery.contrib.rdb`: Changed remote debugger banner so that you can copy and paste
  1242. the address easily (no longer has a period in the address).
  1243. Contributed by **Jonathan Vanasco**.
  1244. - Fixed compatibility with recent :pypi:`psutil` versions (Issue #3262).
  1245. Signals
  1246. ~~~~~~~
  1247. - **App**: New signals for app configuration/finalization:
  1248. - :data:`app.on_configure <@on_configure>`
  1249. - :data:`app.on_after_configure <@on_after_configure>`
  1250. - :data:`app.on_after_finalize <@on_after_finalize>`
  1251. - **Task**: New task signals for rejected task messages:
  1252. - :data:`celery.signals.task_rejected`.
  1253. - :data:`celery.signals.task_unknown`.
  1254. - **Worker**: New signal for when a heartbeat event is sent.
  1255. - :data:`celery.signals.heartbeat_sent`
  1256. Contributed by **Kevin Richardson**.
  1257. Events
  1258. ~~~~~~
  1259. - Event messages now uses the RabbitMQ ``x-message-ttl`` option
  1260. to ensure older event messages are discarded.
  1261. The default is 5 seconds, but can be changed using the
  1262. :setting:`event_queue_ttl` setting.
  1263. - ``Task.send_event`` now automatically retries sending the event
  1264. on connection failure, according to the task publish retry settings.
  1265. - Event monitors now sets the :setting:`event_queue_expires`
  1266. setting by default.
  1267. The queues will now expire after 60 seconds after the monitor stops
  1268. consuming from it.
  1269. - Fixed a bug where a None value wasn't handled properly.
  1270. Fix contributed by **Dongweiming**.
  1271. - New :setting:`event_queue_prefix` setting can now be used
  1272. to change the default ``celeryev`` queue prefix for event receiver queues.
  1273. Contributed by **Takeshi Kanemoto**.
  1274. - ``State.tasks_by_type`` and ``State.tasks_by_worker`` can now be
  1275. used as a mapping for fast access to this information.
  1276. Deployment
  1277. ~~~~~~~~~~
  1278. - Generic init-scripts now support
  1279. :envvar:`CELERY_SU` and :envvar:`CELERYD_SU_ARGS` environment variables
  1280. to set the path and arguments for :command:`su` (:manpage:`su(1)`).
  1281. - Generic init-scripts now better support FreeBSD and other BSD
  1282. systems by searching :file:`/usr/local/etc/` for the configuration file.
  1283. Contributed by **Taha Jahangir**.
  1284. - Generic init-script: Fixed strange bug for ``celerybeat`` where
  1285. restart didn't always work (Issue #3018).
  1286. - The systemd init script now uses a shell when executing
  1287. services.
  1288. Contributed by **Tomas Machalek**.
  1289. Result Backends
  1290. ~~~~~~~~~~~~~~~
  1291. - Redis: Now has a default socket timeout of 120 seconds.
  1292. The default can be changed using the new :setting:`redis_socket_timeout`
  1293. setting.
  1294. Contributed by **Raghuram Srinivasan**.
  1295. - RPC Backend result queues are now auto delete by default (Issue #2001).
  1296. - RPC Backend: Fixed problem where exception
  1297. wasn't deserialized properly with the json serializer (Issue #2518).
  1298. Fix contributed by **Allard Hoeve**.
  1299. - CouchDB: The backend used to double-json encode results.
  1300. Fix contributed by **Andrew Stewart**.
  1301. - CouchDB: Fixed typo causing the backend to not be found
  1302. (Issue #3287).
  1303. Fix contributed by **Andrew Stewart**.
  1304. - MongoDB: Now supports setting the :setting:`result_serialzier` setting
  1305. to ``bson`` to use the MongoDB libraries own serializer.
  1306. Contributed by **Davide Quarta**.
  1307. - MongoDB: URI handling has been improved to use
  1308. database name, user and password from the URI if provided.
  1309. Contributed by **Samuel Jaillet**.
  1310. - SQLAlchemy result backend: Now ignores all result
  1311. engine options when using NullPool (Issue #1930).
  1312. - SQLAlchemy result backend: Now sets max char size to 155 to deal
  1313. with brain damaged MySQL Unicode implementation (Issue #1748).
  1314. - **General**: All Celery exceptions/warnings now inherit from common
  1315. :class:`~celery.exceptions.CeleryError`/:class:`~celery.exceptions.CeleryWarning`.
  1316. (Issue #2643).
  1317. Documentation Improvements
  1318. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1319. Contributed by:
  1320. - Adam Chainz
  1321. - Amir Rustamzadeh
  1322. - Arthur Vuillard
  1323. - Batiste Bieler
  1324. - Berker Peksag
  1325. - Bryce Groff
  1326. - Daniel Devine
  1327. - Edward Betts
  1328. - Jason Veatch
  1329. - Jeff Widman
  1330. - Maciej Obuchowski
  1331. - Manuel Kaufmann
  1332. - Maxime Beauchemin
  1333. - Mitchel Humpherys
  1334. - Pavlo Kapyshin
  1335. - Pierre Fersing
  1336. - Rik
  1337. - Steven Sklar
  1338. - Tayfun Sen
  1339. - Wieland Hoffmann
  1340. Reorganization, Deprecations, and Removals
  1341. ==========================================
  1342. Incompatible changes
  1343. --------------------
  1344. - Prefork: Calling ``result.get()`` or joining any result from within a task
  1345. now raises :exc:`RuntimeError`.
  1346. In previous versions this would emit a warning.
  1347. - :mod:`celery.worker.consumer` is now a package, not a module.
  1348. - Module ``celery.worker.job`` renamed to :mod:`celery.worker.request`.
  1349. - Beat: ``Scheduler.Publisher``/``.publisher`` renamed to
  1350. ``.Producer``/``.producer``.
  1351. - Result: The task_name argument/attribute of :class:`@AsyncResult` was
  1352. removed.
  1353. This was historically a field used for :mod:`pickle` compatibility,
  1354. but is no longer needed.
  1355. - Backends: Arguments named ``status`` renamed to ``state``.
  1356. - Backends: ``backend.get_status()`` renamed to ``backend.get_state()``.
  1357. - Backends: ``backend.maybe_reraise()`` renamed to ``.maybe_throw()``
  1358. The promise API uses .throw(), so this change was made to make it more
  1359. consistent.
  1360. There's an alias available, so you can still use maybe_reraise until
  1361. Celery 5.0.
  1362. .. _v400-unscheduled-removals:
  1363. Unscheduled Removals
  1364. --------------------
  1365. - The experimental :mod:`celery.contrib.methods` feature has been removed,
  1366. as there were far many bugs in the implementation to be useful.
  1367. - The CentOS init-scripts have been removed.
  1368. These didn't really add any features over the generic init-scripts,
  1369. so you're encouraged to use them instead, or something like
  1370. :pypi:`supervisor`.
  1371. .. _v400-deprecations-reorg:
  1372. Reorganization Deprecations
  1373. ---------------------------
  1374. These symbols have been renamed, and while there's an alias available in this
  1375. version for backward compatibility, they will be removed in Celery 5.0, so
  1376. make sure you rename these ASAP to make sure it won't break for that release.
  1377. Chances are that you'll only use the first in this list, but you never
  1378. know:
  1379. - ``celery.utils.worker_direct`` ->
  1380. :meth:`celery.utils.nodenames.worker_direct`.
  1381. - ``celery.utils.nodename`` -> :meth:`celery.utils.nodenames.nodename`.
  1382. - ``celery.utils.anon_nodename`` ->
  1383. :meth:`celery.utils.nodenames.anon_nodename`.
  1384. - ``celery.utils.nodesplit`` -> :meth:`celery.utils.nodenames.nodesplit`.
  1385. - ``celery.utils.default_nodename`` ->
  1386. :meth:`celery.utils.nodenames.default_nodename`.
  1387. - ``celery.utils.node_format`` -> :meth:`celery.utils.nodenames.node_format`.
  1388. - ``celery.utils.host_format`` -> :meth:`celery.utils.nodenames.host_format`.
  1389. .. _v400-removals:
  1390. Scheduled Removals
  1391. ------------------
  1392. Modules
  1393. ~~~~~~~
  1394. - Module ``celery.worker.job`` has been renamed to :mod:`celery.worker.request`.
  1395. This was an internal module so shouldn't have any effect.
  1396. It's now part of the public API so must not change again.
  1397. - Module ``celery.task.trace`` has been renamed to ``celery.app.trace``
  1398. as the ``celery.task`` package is being phased out. The module
  1399. will be removed in version 5.0 so please change any import from::
  1400. from celery.task.trace import X
  1401. to::
  1402. from celery.app.trace import X
  1403. - Old compatibility aliases in the :mod:`celery.loaders` module
  1404. has been removed.
  1405. - Removed ``celery.loaders.current_loader()``, use: ``current_app.loader``
  1406. - Removed ``celery.loaders.load_settings()``, use: ``current_app.conf``
  1407. Result
  1408. ~~~~~~
  1409. - ``AsyncResult.serializable()`` and ``celery.result.from_serializable``
  1410. has been removed:
  1411. Use instead:
  1412. .. code-block:: pycon
  1413. >>> tup = result.as_tuple()
  1414. >>> from celery.result import result_from_tuple
  1415. >>> result = result_from_tuple(tup)
  1416. - Removed ``BaseAsyncResult``, use ``AsyncResult`` for instance checks
  1417. instead.
  1418. - Removed ``TaskSetResult``, use ``GroupResult`` instead.
  1419. - ``TaskSetResult.total`` -> ``len(GroupResult)``
  1420. - ``TaskSetResult.taskset_id`` -> ``GroupResult.id``
  1421. - Removed ``ResultSet.subtasks``, use ``ResultSet.results`` instead.
  1422. TaskSet
  1423. ~~~~~~~
  1424. TaskSet has been removed, as it was replaced by the ``group`` construct in
  1425. Celery 3.0.
  1426. If you have code like this:
  1427. .. code-block:: pycon
  1428. >>> from celery.task import TaskSet
  1429. >>> TaskSet(add.subtask((i, i)) for i in xrange(10)).apply_async()
  1430. You need to replace that with:
  1431. .. code-block:: pycon
  1432. >>> from celery import group
  1433. >>> group(add.s(i, i) for i in xrange(10))()
  1434. Events
  1435. ~~~~~~
  1436. - Removals for class :class:`celery.events.state.Worker`:
  1437. - ``Worker._defaults`` attribute.
  1438. Use ``{k: getattr(worker, k) for k in worker._fields}``.
  1439. - ``Worker.update_heartbeat``
  1440. Use ``Worker.event(None, timestamp, received)``
  1441. - ``Worker.on_online``
  1442. Use ``Worker.event('online', timestamp, received, fields)``
  1443. - ``Worker.on_offline``
  1444. Use ``Worker.event('offline', timestamp, received, fields)``
  1445. - ``Worker.on_heartbeat``
  1446. Use ``Worker.event('heartbeat', timestamp, received, fields)``
  1447. - Removals for class :class:`celery.events.state.Task`:
  1448. - ``Task._defaults`` attribute.
  1449. Use ``{k: getattr(task, k) for k in task._fields}``.
  1450. - ``Task.on_sent``
  1451. Use ``Worker.event('sent', timestamp, received, fields)``
  1452. - ``Task.on_received``
  1453. Use ``Task.event('received', timestamp, received, fields)``
  1454. - ``Task.on_started``
  1455. Use ``Task.event('started', timestamp, received, fields)``
  1456. - ``Task.on_failed``
  1457. Use ``Task.event('failed', timestamp, received, fields)``
  1458. - ``Task.on_retried``
  1459. Use ``Task.event('retried', timestamp, received, fields)``
  1460. - ``Task.on_succeeded``
  1461. Use ``Task.event('succeeded', timestamp, received, fields)``
  1462. - ``Task.on_revoked``
  1463. Use ``Task.event('revoked', timestamp, received, fields)``
  1464. - ``Task.on_unknown_event``
  1465. Use ``Task.event(short_type, timestamp, received, fields)``
  1466. - ``Task.update``
  1467. Use ``Task.event(short_type, timestamp, received, fields)``
  1468. - ``Task.merge``
  1469. Contact us if you need this.
  1470. Magic keyword arguments
  1471. ~~~~~~~~~~~~~~~~~~~~~~~
  1472. Support for the very old magic keyword arguments accepted by tasks is
  1473. finally removed in this version.
  1474. If you're still using these you have to rewrite any task still
  1475. using the old ``celery.decorators`` module and depending
  1476. on keyword arguments being passed to the task,
  1477. for example::
  1478. from celery.decorators import task
  1479. @task()
  1480. def add(x, y, task_id=None):
  1481. print('My task id is %r' % (task_id,))
  1482. should be rewritten into::
  1483. from celery import task
  1484. @task(bind=True)
  1485. def add(self, x, y):
  1486. print('My task id is {0.request.id}'.format(self))
  1487. Removed Settings
  1488. ----------------
  1489. The following settings have been removed, and is no longer supported:
  1490. Logging Settings
  1491. ~~~~~~~~~~~~~~~~
  1492. ===================================== =====================================
  1493. **Setting name** **Replace with**
  1494. ===================================== =====================================
  1495. ``CELERYD_LOG_LEVEL`` :option:`celery worker --loglevel`
  1496. ``CELERYD_LOG_FILE`` :option:`celery worker --logfile`
  1497. ``CELERYBEAT_LOG_LEVEL`` :option:`celery beat --loglevel`
  1498. ``CELERYBEAT_LOG_FILE`` :option:`celery beat --loglevel`
  1499. ``CELERYMON_LOG_LEVEL`` celerymon is deprecated, use flower
  1500. ``CELERYMON_LOG_FILE`` celerymon is deprecated, use flower
  1501. ``CELERYMON_LOG_FORMAT`` celerymon is deprecated, use flower
  1502. ===================================== =====================================
  1503. Task Settings
  1504. ~~~~~~~~~~~~~~
  1505. ===================================== =====================================
  1506. **Setting name** **Replace with**
  1507. ===================================== =====================================
  1508. ``CELERY_CHORD_PROPAGATES`` N/A
  1509. ===================================== =====================================
  1510. Changes to internal API
  1511. -----------------------
  1512. - Module ``celery.datastructures`` renamed to :mod:`celery.utils.collections`.
  1513. - Module ``celery.utils.timeutils`` renamed to :mod:`celery.utils.time`.
  1514. - ``celery.utils.datastructures.DependencyGraph`` moved to
  1515. :mod:`celery.utils.graph`.
  1516. - ``celery.utils.jsonify`` is now :func:`celery.utils.serialization.jsonify`.
  1517. - ``celery.utils.strtobool`` is now
  1518. :func:`celery.utils.serialization.strtobool`.
  1519. - ``celery.utils.is_iterable`` has been removed.
  1520. Instead use:
  1521. .. code-block:: python
  1522. isinstance(x, collections.Iterable)
  1523. - ``celery.utils.lpmerge`` is now :func:`celery.utils.collections.lpmerge`.
  1524. - ``celery.utils.cry`` is now :func:`celery.utils.debug.cry`.
  1525. - ``celery.utils.isatty`` is now :func:`celery.platforms.isatty`.
  1526. - ``celery.utils.gen_task_name`` is now
  1527. :func:`celery.utils.imports.gen_task_name`.
  1528. - ``celery.utils.deprecated`` is now :func:`celery.utils.deprecated.Callable`
  1529. - ``celery.utils.deprecated_property`` is now
  1530. :func:`celery.utils.deprecated.Property`.
  1531. - ``celery.utils.warn_deprecated`` is now :func:`celery.utils.deprecated.warn`
  1532. .. _v400-deprecations:
  1533. Deprecation Time-line Changes
  1534. =============================
  1535. See the :ref:`deprecation-timeline`.