Debian Codegraph @

docs/history/whatsnew-3.1.rst

raw
1 .. _whatsnew-3.1:
2
3 ===========================================
4 What's new in Celery 3.1 (Cipater)
5 ===========================================
6 :Author: Ask Solem (``ask at celeryproject.org``)
7
8 .. sidebar:: Change history
9
10 What's new documents describe the changes in major versions,
11 we also have a :ref:`changelog` that lists the changes in bugfix
12 releases (0.0.x), while older series are archived under the :ref:`history`
13 section.
14
15 Celery is a simple, flexible, and reliable distributed system to
16 process vast amounts of messages, while providing operations with
17 the tools required to maintain such a system.
18
19 It's a task queue with focus on real-time processing, while also
20 supporting task scheduling.
21
22 Celery has a large and diverse community of users and contributors,
23 you should come join us :ref:`on IRC <irc-channel>`
24 or :ref:`our mailing-list <mailing-list>`.
25
26 To read more about Celery you should go read the :ref:`introduction <intro>`.
27
28 While this version is backward compatible with previous versions
29 it's important that you read the following section.
30
31 This version is officially supported on CPython 2.6, 2.7, and 3.3,
32 and also supported on PyPy.
33
34 .. _`website`: http://celeryproject.org/
35
36 .. topic:: Table of Contents
37
38 Make sure you read the important notes before upgrading to this version.
39
40 .. contents::
41 :local:
42 :depth: 2
43
44 Preface
45 =======
46
47 Deadlocks have long plagued our workers, and while uncommon they're
48 not acceptable. They're also infamous for being extremely hard to diagnose
49 and reproduce, so to make this job easier I wrote a stress test suite that
50 bombards the worker with different tasks in an attempt to break it.
51
52 What happens if thousands of worker child processes are killed every
53 second? what if we also kill the broker connection every 10
54 seconds? These are examples of what the stress test suite will do to the
55 worker, and it reruns these tests using different configuration combinations
56 to find edge case bugs.
57
58 The end result was that I had to rewrite the prefork pool to avoid the use
59 of the POSIX semaphore. This was extremely challenging, but after
60 months of hard work the worker now finally passes the stress test suite.
61
62 There's probably more bugs to find, but the good news is
63 that we now have a tool to reproduce them, so should you be so unlucky to
64 experience a bug then we'll write a test for it and squash it!
65
66 Note that I've also moved many broker transports into experimental status:
67 the only transports recommended for production use today is RabbitMQ and
68 Redis.
69
70 I don't have the resources to maintain all of them, so bugs are left
71 unresolved. I wish that someone will step up and take responsibility for
72 these transports or donate resources to improve them, but as the situation
73 is now I don't think the quality is up to date with the rest of the code-base
74 so I cannot recommend them for production use.
75
76 The next version of Celery 4.0 will focus on performance and removing
77 rarely used parts of the library. Work has also started on a new message
78 protocol, supporting multiple languages and more. The initial draft can
79 be found :ref:`here <message-protocol-task-v2>`.
80
81 This has probably been the hardest release I've worked on, so no
82 introduction to this changelog would be complete without a massive
83 thank you to everyone who contributed and helped me test it!
84
85 Thank you for your support!
86
87 *— Ask Solem*
88
89 .. _v310-important:
90
91 Important Notes
92 ===============
93
94 Dropped support for Python 2.5
95 ------------------------------
96
97 Celery now requires Python 2.6 or later.
98
99 The new dual code base runs on both Python 2 and 3, without
100 requiring the ``2to3`` porting tool.
101
102 .. note::
103
104 This is also the last version to support Python 2.6! From Celery 4.0 and
105 on-wards Python 2.7 or later will be required.
106
107 .. _last-version-to-enable-pickle:
108
109 Last version to enable Pickle by default
110 ----------------------------------------
111
112 Starting from Celery 4.0 the default serializer will be json.
113
114 If you depend on pickle being accepted you should be prepared
115 for this change by explicitly allowing your worker
116 to consume pickled messages using the :setting:`CELERY_ACCEPT_CONTENT`
117 setting:
118
119 .. code-block:: python
120
121 CELERY_ACCEPT_CONTENT = ['pickle', 'json', 'msgpack', 'yaml']
122
123 Make sure you only select the serialization formats you'll actually be using,
124 and make sure you've properly secured your broker from unwanted access
125 (see the :ref:`Security Guide <guide-security>`).
126
127 The worker will emit a deprecation warning if you don't define this setting.
128
129 .. topic:: for Kombu users
130
131 Kombu 3.0 no longer accepts pickled messages by default, so if you
132 use Kombu directly then you have to configure your consumers:
133 see the :ref:`Kombu 3.0 Changelog <kombu:version-3.0.0>` for more
134 information.
135
136 Old command-line programs removed and deprecated
137 ------------------------------------------------
138
139 Everyone should move to the new :program:`celery` umbrella
140 command, so we're incrementally deprecating the old command names.
141
142 In this version we've removed all commands that aren't used
143 in init-scripts. The rest will be removed in 4.0.
144
145 +-------------------+--------------+-------------------------------------+
146 | Program | New Status | Replacement |
147 +===================+==============+=====================================+
148 | ``celeryd`` | *DEPRECATED* | :program:`celery worker` |
149 +-------------------+--------------+-------------------------------------+
150 | ``celerybeat`` | *DEPRECATED* | :program:`celery beat` |
151 +-------------------+--------------+-------------------------------------+
152 | ``celeryd-multi`` | *DEPRECATED* | :program:`celery multi` |
153 +-------------------+--------------+-------------------------------------+
154 | ``celeryctl`` | **REMOVED** | :program:`celery inspect|control` |
155 +-------------------+--------------+-------------------------------------+
156 | ``celeryev`` | **REMOVED** | :program:`celery events` |
157 +-------------------+--------------+-------------------------------------+
158 | ``camqadm`` | **REMOVED** | :program:`celery amqp` |
159 +-------------------+--------------+-------------------------------------+
160
161 If this isn't a new installation then you may want to remove the old
162 commands:
163
164 .. code-block:: console
165
166 $ pip uninstall celery
167 $ # repeat until it fails
168 # ...
169 $ pip uninstall celery
170 $ pip install celery
171
172 Please run :program:`celery --help` for help using the umbrella command.
173
174 .. _v310-news:
175
176 News
177 ====
178
179 Prefork Pool Improvements
180 -------------------------
181
182 These improvements are only active if you use an async capable
183 transport. This means only RabbitMQ (AMQP) and Redis are supported
184 at this point and other transports will still use the thread-based fallback
185 implementation.
186
187 - Pool is now using one IPC queue per child process.
188
189 Previously the pool shared one queue between all child processes,
190 using a POSIX semaphore as a mutex to achieve exclusive read and write
191 access.
192
193 The POSIX semaphore has now been removed and each child process
194 gets a dedicated queue. This means that the worker will require more
195 file descriptors (two descriptors per process), but it also means
196 that performance is improved and we can send work to individual child
197 processes.
198
199 POSIX semaphores aren't released when a process is killed, so killing
200 processes could lead to a deadlock if it happened while the semaphore was
201 acquired. There's no good solution to fix this, so the best option
202 was to remove the semaphore.
203
204 - Asynchronous write operations
205
206 The pool now uses async I/O to send work to the child processes.
207
208 - Lost process detection is now immediate.
209
210 If a child process is killed or exits mysteriously the pool previously
211 had to wait for 30 seconds before marking the task with a
212 :exc:`~celery.exceptions.WorkerLostError`. It had to do this because
213 the out-queue was shared between all processes, and the pool couldn't
214 be certain whether the process completed the task or not. So an arbitrary
215 timeout of 30 seconds was chosen, as it was believed that the out-queue
216 would've been drained by this point.
217
218 This timeout is no longer necessary, and so the task can be marked as
219 failed as soon as the pool gets the notification that the process exited.
220
221 - Rare race conditions fixed
222
223 Most of these bugs were never reported to us, but were discovered while
224 running the new stress test suite.
225
226 Caveats
227 ~~~~~~~
228
229 .. topic:: Long running tasks
230
231 The new pool will send tasks to a child process as long as the process
232 in-queue is writable, and since the socket is buffered this means
233 that the processes are, in effect, prefetching tasks.
234
235 This benefits performance but it also means that other tasks may be stuck
236 waiting for a long running task to complete::
237
238 -> send T1 to Process A
239 # A executes T1
240 -> send T2 to Process B
241 # B executes T2
242 <- T2 complete
243
244 -> send T3 to Process A
245 # A still executing T1, T3 stuck in local buffer and
246 # won't start until T1 returns
247
248 The buffer size varies based on the operating system: some may
249 have a buffer as small as 64KB but on recent Linux versions the buffer
250 size is 1MB (can only be changed system wide).
251
252 You can disable this prefetching behavior by enabling the
253 :option:`-Ofair <celery worker -O>` worker option:
254
255 .. code-block:: console
256
257 $ celery -A proj worker -l info -Ofair
258
259 With this option enabled the worker will only write to workers that are
260 available for work, disabling the prefetch behavior.
261
262 .. topic:: Max tasks per child
263
264 If a process exits and pool prefetch is enabled the worker may have
265 already written many tasks to the process in-queue, and these tasks
266 must then be moved back and rewritten to a new process.
267
268 This is very expensive if you have the
269 :option:`--max-tasks-per-child <celery worker --max-tasks-per-child>`
270 option set to a low value (e.g., less than 10), you should not be
271 using the :option:`-Ofast <celery worker -O>` scheduler option.
272
273 Django supported out of the box
274 -------------------------------
275
276 Celery 3.0 introduced a shiny new API, but unfortunately didn't
277 have a solution for Django users.
278
279 The situation changes with this version as Django is now supported
280 in core and new Django users coming to Celery are now expected
281 to use the new API directly.
282
283 The Django community has a convention where there's a separate
284 ``django-x`` package for every library, acting like a bridge between
285 Django and the library.
286
287 Having a separate project for Django users has been a pain for Celery,
288 with multiple issue trackers and multiple documentation
289 sources, and then lastly since 3.0 we even had different APIs.
290
291 With this version we challenge that convention and Django users will
292 use the same library, the same API and the same documentation as
293 everyone else.
294
295 There's no rush to port your existing code to use the new API,
296 but if you'd like to experiment with it you should know that:
297
298 - You need to use a Celery application instance.
299
300 The new Celery API introduced in 3.0 requires users to instantiate the
301 library by creating an application:
302
303 .. code-block:: python
304
305 from celery import Celery
306
307 app = Celery()
308
309 - You need to explicitly integrate Celery with Django
310
311 Celery won't automatically use the Django settings, so you can
312 either configure Celery separately or you can tell it to use the Django
313 settings with:
314
315 .. code-block:: python
316
317 app.config_from_object('django.conf:settings')
318
319 Neither will it automatically traverse your installed apps to find task
320 modules. If you want this behavior, you must explicitly pass a list of
321 Django instances to the Celery app:
322
323 .. code-block:: python
324
325 from django.conf import settings
326 app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
327
328 - You no longer use ``manage.py``
329
330 Instead you use the :program:`celery` command directly:
331
332 .. code-block:: console
333
334 $ celery -A proj worker -l info
335
336 For this to work your app module must store the :envvar:`DJANGO_SETTINGS_MODULE`
337 environment variable, see the example in the :ref:`Django
338 guide <django-first-steps>`.
339
340 To get started with the new API you should first read the :ref:`first-steps`
341 tutorial, and then you should read the Django-specific instructions in
342 :ref:`django-first-steps`.
343
344 The fixes and improvements applied by the :pypi:`django-celery` library
345 are now automatically applied by core Celery when it detects that
346 the :envvar:`DJANGO_SETTINGS_MODULE` environment variable is set.
347
348 The distribution ships with a new example project using Django
349 in :file:`examples/django`:
350
351 https://github.com/celery/celery/tree/3.1/examples/django
352
353 Some features still require the :pypi:`django-celery` library:
354
355 - Celery doesn't implement the Django database or cache result backends.
356 - Celery doesn't ship with the database-based periodic task
357 scheduler.
358
359 .. note::
360
361 If you're still using the old API when you upgrade to Celery 3.1
362 then you must make sure that your settings module contains
363 the ``djcelery.setup_loader()`` line, since this will
364 no longer happen as a side-effect of importing the :pypi:`django-celery`
365 module.
366
367 New users (or if you've ported to the new API) don't need the ``setup_loader``
368 line anymore, and must make sure to remove it.
369
370 Events are now ordered using logical time
371 -----------------------------------------
372
373 Keeping physical clocks in perfect sync is impossible, so using
374 time-stamps to order events in a distributed system isn't reliable.
375
376 Celery event messages have included a logical clock value for some time,
377 but starting with this version that field is also used to order them.
378
379 Also, events now record timezone information
380 by including a new ``utcoffset`` field in the event message.
381 This is a signed integer telling the difference from UTC time in hours,
382 so for example, an event sent from the Europe/London timezone in daylight savings
383 time will have an offset of 1.
384
385 :class:`@events.Receiver` will automatically convert the time-stamps
386 to the local timezone.
387
388 .. note::
389
390 The logical clock is synchronized with other nodes
391 in the same cluster (neighbors), so this means that the logical
392 epoch will start at the point when the first worker in the cluster
393 starts.
394
395 If all of the workers are shutdown the clock value will be lost
396 and reset to 0. To protect against this, you should specify the
397 :option:`celery worker --statedb` option such that the worker can
398 persist the clock value at shutdown.
399
400 You may notice that the logical clock is an integer value and
401 increases very rapidly. Don't worry about the value overflowing
402 though, as even in the most busy clusters it may take several
403 millennium before the clock exceeds a 64 bits value.
404
405 New worker node name format (``name@host``)
406 -------------------------------------------
407
408 Node names are now constructed by two elements: name and host-name
409 separated by '@'.
410
411 This change was made to more easily identify multiple instances running
412 on the same machine.
413
414 If a custom name isn't specified then the
415 worker will use the name 'celery' by default, resulting in a
416 fully qualified node name of 'celery@hostname':
417
418 .. code-block:: console
419
420 $ celery worker -n example.com
421 [email protected]
422
423 To also set the name you must include the @:
424
425 .. code-block:: console
426
427 $ celery worker -n [email protected]
428 [email protected]
429
430 The worker will identify itself using the fully qualified
431 node name in events and broadcast messages, so where before
432 a worker would identify itself as 'worker1.example.com', it'll now
433 use '[email protected]'.
434
435 Remember that the :option:`-n <celery worker -n>` argument also supports
436 simple variable substitutions, so if the current host-name
437 is *george.example.com* then the ``%h`` macro will expand into that:
438
439 .. code-block:: console
440
441 $ celery worker -n worker1@%h
442 [email protected]
443
444 The available substitutions are as follows:
445
446 +---------------+----------------------------------------+
447 | Variable | Substitution |
448 +===============+========================================+
449 | ``%h`` | Full host-name (including domain name) |
450 +---------------+----------------------------------------+
451 | ``%d`` | Domain name only |
452 +---------------+----------------------------------------+
453 | ``%n`` | Host-name only (without domain name) |
454 +---------------+----------------------------------------+
455 | ``%%`` | The character ``%`` |
456 +---------------+----------------------------------------+
457
458 Bound tasks
459 -----------
460
461 The task decorator can now create "bound tasks", which means that the
462 task will receive the ``self`` argument.
463
464 .. code-block:: python
465
466 @app.task(bind=True)
467 def send_twitter_status(self, oauth, tweet):
468 try:
469 twitter = Twitter(oauth)
470 twitter.update_status(tweet)
471 except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
472 raise self.retry(exc=exc)
473
474 Using *bound tasks* is now the recommended approach whenever
475 you need access to the task instance or request context.
476 Previously one would've to refer to the name of the task
477 instead (``send_twitter_status.retry``), but this could lead to problems
478 in some configurations.
479
480 Mingle: Worker synchronization
481 ------------------------------
482
483 The worker will now attempt to synchronize with other workers in
484 the same cluster.
485
486 Synchronized data currently includes revoked tasks and logical clock.
487
488 This only happens at start-up and causes a one second start-up delay
489 to collect broadcast responses from other workers.
490
491 You can disable this bootstep using the
492 :option:`celery worker --without-mingle` option.
493
494 Gossip: Worker <-> Worker communication
495 ---------------------------------------
496
497 Workers are now passively subscribing to worker related events like
498 heartbeats.
499
500 This means that a worker knows what other workers are doing and
501 can detect if they go offline. Currently this is only used for clock
502 synchronization, but there are many possibilities for future additions
503 and you can write extensions that take advantage of this already.
504
505 Some ideas include consensus protocols, reroute task to best worker (based on
506 resource usage or data locality) or restarting workers when they crash.
507
508 We believe that although this is a small addition, it opens
509 amazing possibilities.
510
511 You can disable this bootstep using the
512 :option:`celery worker --without-gossip` option.
513
514 Bootsteps: Extending the worker
515 -------------------------------
516
517 By writing bootsteps you can now easily extend the consumer part
518 of the worker to add additional features, like custom message consumers.
519
520 The worker has been using bootsteps for some time, but these were never
521 documented. In this version the consumer part of the worker
522 has also been rewritten to use bootsteps and the new :ref:`guide-extending`
523 guide documents examples extending the worker, including adding
524 custom message consumers.
525
526 See the :ref:`guide-extending` guide for more information.
527
528 .. note::
529
530 Bootsteps written for older versions won't be compatible
531 with this version, as the API has changed significantly.
532
533 The old API was experimental and internal but should you be so unlucky
534 to use it then please contact the mailing-list and we'll help you port
535 the bootstep to the new API.
536
537 New RPC result backend
538 ----------------------
539
540 This new experimental version of the ``amqp`` result backend is a good
541 alternative to use in classical RPC scenarios, where the process that initiates
542 the task is always the process to retrieve the result.
543
544 It uses Kombu to send and retrieve results, and each client
545 uses a unique queue for replies to be sent to. This avoids
546 the significant overhead of the original amqp result backend which creates
547 one queue per task.
548
549 By default results sent using this backend won't persist, so they won't
550 survive a broker restart. You can enable
551 the :setting:`CELERY_RESULT_PERSISTENT` setting to change that.
552
553 .. code-block:: python
554
555 CELERY_RESULT_BACKEND = 'rpc'
556 CELERY_RESULT_PERSISTENT = True
557
558 Note that chords are currently not supported by the RPC backend.
559
560 Time limits can now be set by the client
561 ----------------------------------------
562
563 Two new options have been added to the Calling API: ``time_limit`` and
564 ``soft_time_limit``:
565
566 .. code-block:: pycon
567
568 >>> res = add.apply_async((2, 2), time_limit=10, soft_time_limit=8)
569
570 >>> res = add.subtask((2, 2), time_limit=10, soft_time_limit=8).delay()
571
572 >>> res = add.s(2, 2).set(time_limit=10, soft_time_limit=8).delay()
573
574 Contributed by Mher Movsisyan.
575
576 Redis: Broadcast messages and virtual hosts
577 -------------------------------------------
578
579 Broadcast messages are currently seen by all virtual hosts when
580 using the Redis transport. You can now fix this by enabling a prefix to all channels
581 so that the messages are separated:
582
583 .. code-block:: python
584
585 BROKER_TRANSPORT_OPTIONS = {'fanout_prefix': True}
586
587 Note that you'll not be able to communicate with workers running older
588 versions or workers that doesn't have this setting enabled.
589
590 This setting will be the default in a future version.
591
592 Related to Issue #1490.
593
594 :pypi:`pytz` replaces :pypi:`python-dateutil` dependency
595 --------------------------------------------------------
596
597 Celery no longer depends on the :pypi:`python-dateutil` library,
598 but instead a new dependency on the :pypi:`pytz` library was added.
599
600 The :pypi:`pytz` library was already recommended for accurate timezone support.
601
602 This also means that dependencies are the same for both Python 2 and
603 Python 3, and that the :file:`requirements/default-py3k.txt` file has
604 been removed.
605
606 Support for :pypi:`setuptools` extra requirements
607 -------------------------------------------------
608
609 Pip now supports the :pypi:`setuptools` extra requirements format,
610 so we've removed the old bundles concept, and instead specify
611 setuptools extras.
612
613 You install extras by specifying them inside brackets:
614
615 .. code-block:: console
616
617 $ pip install celery[redis,mongodb]
618
619 The above will install the dependencies for Redis and MongoDB. You can list
620 as many extras as you want.
621
622
623 .. warning::
624
625 You can't use the ``celery-with-*`` packages anymore, as these won't be
626 updated to use Celery 3.1.
627
628 +-------------+-------------------------+---------------------------+
629 | Extension | Requirement entry | Type |
630 +=============+=========================+===========================+
631 | Redis | ``celery[redis]`` | transport, result backend |
632 +-------------+-------------------------+---------------------------+
633 | MongoDB | ``celery[mongodb]`` | transport, result backend |
634 +-------------+-------------------------+---------------------------+
635 | CouchDB | ``celery[couchdb]`` | transport |
636 +-------------+-------------------------+---------------------------+
637 | Beanstalk | ``celery[beanstalk]`` | transport |
638 +-------------+-------------------------+---------------------------+
639 | ZeroMQ | ``celery[zeromq]`` | transport |
640 +-------------+-------------------------+---------------------------+
641 | Zookeeper | ``celery[zookeeper]`` | transport |
642 +-------------+-------------------------+---------------------------+
643 | SQLAlchemy | ``celery[sqlalchemy]`` | transport, result backend |
644 +-------------+-------------------------+---------------------------+
645 | librabbitmq | ``celery[librabbitmq]`` | transport (C amqp client) |
646 +-------------+-------------------------+---------------------------+
647
648 The complete list with examples is found in the :ref:`bundles` section.
649
650 ``subtask.__call__()`` now executes the task directly
651 -----------------------------------------------------
652
653 A misunderstanding led to ``Signature.__call__`` being an alias of
654 ``.delay`` but this doesn't conform to the calling API of ``Task`` which
655 calls the underlying task method.
656
657 This means that:
658
659 .. code-block:: python
660
661 @app.task
662 def add(x, y):
663 return x + y
664
665 add.s(2, 2)()
666
667 now does the same as calling the task directly:
668
669 .. code-block:: pycon
670
671 >>> add(2, 2)
672
673 In Other News
674 -------------
675
676 - Now depends on :ref:`Kombu 3.0 <kombu:version-3.0.0>`.
677
678 - Now depends on :pypi:`billiard` version 3.3.
679
680 - Worker will now crash if running as the root user with pickle enabled.
681
682 - Canvas: ``group.apply_async`` and ``chain.apply_async`` no longer starts
683 separate task.
684
685 That the group and chord primitives supported the "calling API" like other
686 subtasks was a nice idea, but it was useless in practice and often
687 confused users. If you still want this behavior you can define a
688 task to do it for you.
689
690 - New method ``Signature.freeze()`` can be used to "finalize"
691 signatures/subtask.
692
693 Regular signature:
694
695 .. code-block:: pycon
696
697 >>> s = add.s(2, 2)
698 >>> result = s.freeze()
699 >>> result
700 <AsyncResult: ffacf44b-f8a1-44e9-80a3-703150151ef2>
701 >>> s.delay()
702 <AsyncResult: ffacf44b-f8a1-44e9-80a3-703150151ef2>
703
704 Group:
705
706 .. code-block:: pycon
707
708 >>> g = group(add.s(2, 2), add.s(4, 4))
709 >>> result = g.freeze()
710 <GroupResult: e1094b1d-08fc-4e14-838e-6d601b99da6d [
711 70c0fb3d-b60e-4b22-8df7-aa25b9abc86d,
712 58fcd260-2e32-4308-a2ea-f5be4a24f7f4]>
713 >>> g()
714 <GroupResult: e1094b1d-08fc-4e14-838e-6d601b99da6d [70c0fb3d-b60e-4b22-8df7-aa25b9abc86d, 58fcd260-2e32-4308-a2ea-f5be4a24f7f4]>
715
716 - Chord exception behavior defined (Issue #1172).
717
718 From this version the chord callback will change state to FAILURE
719 when a task part of a chord raises an exception.
720
721 See more at :ref:`chord-errors`.
722
723 - New ability to specify additional command line options
724 to the worker and beat programs.
725
726 The :attr:`@user_options` attribute can be used
727 to add additional command-line arguments, and expects
728 :mod:`optparse`-style options:
729
730 .. code-block:: python
731
732 from celery import Celery
733 from celery.bin import Option
734
735 app = Celery()
736 app.user_options['worker'].add(
737 Option('--my-argument'),
738 )
739
740 See the :ref:`guide-extending` guide for more information.
741
742 - All events now include a ``pid`` field, which is the process id of the
743 process that sent the event.
744
745 - Event heartbeats are now calculated based on the time when the event
746 was received by the monitor, and not the time reported by the worker.
747
748 This means that a worker with an out-of-sync clock will no longer
749 show as 'Offline' in monitors.
750
751 A warning is now emitted if the difference between the senders
752 time and the internal time is greater than 15 seconds, suggesting
753 that the clocks are out of sync.
754
755 - Monotonic clock support.
756
757 A monotonic clock is now used for timeouts and scheduling.
758
759 The monotonic clock function is built-in starting from Python 3.4,
760 but we also have fallback implementations for Linux and macOS.
761
762 - :program:`celery worker` now supports a new
763 :option:`--detach <celery worker --detach>` argument to start
764 the worker as a daemon in the background.
765
766 - :class:`@events.Receiver` now sets a ``local_received`` field for incoming
767 events, which is set to the time of when the event was received.
768
769 - :class:`@events.Dispatcher` now accepts a ``groups`` argument
770 which decides a white-list of event groups that'll be sent.
771
772 The type of an event is a string separated by '-', where the part
773 before the first '-' is the group. Currently there are only
774 two groups: ``worker`` and ``task``.
775
776 A dispatcher instantiated as follows:
777
778 .. code-block:: pycon
779
780 >>> app.events.Dispatcher(connection, groups=['worker'])
781
782 will only send worker related events and silently drop any attempts
783 to send events related to any other group.
784
785 - New :setting:`BROKER_FAILOVER_STRATEGY` setting.
786
787 This setting can be used to change the transport fail-over strategy,
788 can either be a callable returning an iterable or the name of a
789 Kombu built-in failover strategy. Default is "round-robin".
790
791 Contributed by Matt Wise.
792
793 - ``Result.revoke`` will no longer wait for replies.
794
795 You can add the ``reply=True`` argument if you really want to wait for
796 responses from the workers.
797
798 - Better support for link and link_error tasks for chords.
799
800 Contributed by Steeve Morin.
801
802 - Worker: Now emits warning if the :setting:`CELERYD_POOL` setting is set
803 to enable the eventlet/gevent pools.
804
805 The `-P` option should always be used to select the eventlet/gevent pool
806 to ensure that the patches are applied as early as possible.
807
808 If you start the worker in a wrapper (like Django's :file:`manage.py`)
809 then you must apply the patches manually, for example by creating an alternative
810 wrapper that monkey patches at the start of the program before importing
811 any other modules.
812
813 - There's a now an 'inspect clock' command which will collect the current
814 logical clock value from workers.
815
816 - `celery inspect stats` now contains the process id of the worker's main
817 process.
818
819 Contributed by Mher Movsisyan.
820
821 - New remote control command to dump a workers configuration.
822
823 Example:
824
825 .. code-block:: console
826
827 $ celery inspect conf
828
829 Configuration values will be converted to values supported by JSON
830 where possible.
831
832 Contributed by Mher Movsisyan.
833
834 - New settings :setting:`CELERY_EVENT_QUEUE_TTL` and
835 :setting:`CELERY_EVENT_QUEUE_EXPIRES`.
836
837 These control when a monitors event queue is deleted, and for how long
838 events published to that queue will be visible. Only supported on
839 RabbitMQ.
840
841 - New Couchbase result backend.
842
843 This result backend enables you to store and retrieve task results
844 using `Couchbase`_.
845
846 See :ref:`conf-couchbase-result-backend` for more information
847 about configuring this result backend.
848
849 Contributed by Alain Masiero.
850
851 .. _`Couchbase`: https://www.couchbase.com
852
853 - CentOS init-script now supports starting multiple worker instances.
854
855 See the script header for details.
856
857 Contributed by Jonathan Jordan.
858
859 - ``AsyncResult.iter_native`` now sets default interval parameter to 0.5
860
861 Fix contributed by Idan Kamara
862
863 - New setting :setting:`BROKER_LOGIN_METHOD`.
864
865 This setting can be used to specify an alternate login method
866 for the AMQP transports.
867
868 Contributed by Adrien Guinet
869
870 - The ``dump_conf`` remote control command will now give the string
871 representation for types that aren't JSON compatible.
872
873 - Function `celery.security.setup_security` is now :func:`@setup_security`.
874
875 - Task retry now propagates the message expiry value (Issue #980).
876
877 The value is forwarded at is, so the expiry time won't change.
878 To update the expiry time you'd've to pass a new expires
879 argument to ``retry()``.
880
881 - Worker now crashes if a channel error occurs.
882
883 Channel errors are transport specific and is the list of exceptions
884 returned by ``Connection.channel_errors``.
885 For RabbitMQ this means that Celery will crash if the equivalence
886 checks for one of the queues in :setting:`CELERY_QUEUES` mismatches, which
887 makes sense since this is a scenario where manual intervention is
888 required.
889
890 - Calling ``AsyncResult.get()`` on a chain now propagates errors for previous
891 tasks (Issue #1014).
892
893 - The parent attribute of ``AsyncResult`` is now reconstructed when using JSON
894 serialization (Issue #1014).
895
896 - Worker disconnection logs are now logged with severity warning instead of
897 error.
898
899 Contributed by Chris Adams.
900
901 - ``events.State`` no longer crashes when it receives unknown event types.
902
903 - SQLAlchemy Result Backend: New :setting:`CELERY_RESULT_DB_TABLENAMES`
904 setting can be used to change the name of the database tables used.
905
906 Contributed by Ryan Petrello.
907
908 - SQLAlchemy Result Backend: Now calls ``enginge.dispose`` after fork
909 (Issue #1564).
910
911 If you create your own SQLAlchemy engines then you must also
912 make sure that these are closed after fork in the worker:
913
914 .. code-block:: python
915
916 from multiprocessing.util import register_after_fork
917
918 engine = create_engine(*engine_args)
919 register_after_fork(engine, engine.dispose)
920
921 - A stress test suite for the Celery worker has been written.
922
923 This is located in the ``funtests/stress`` directory in the git
924 repository. There's a README file there to get you started.
925
926 - The logger named ``celery.concurrency`` has been renamed to ``celery.pool``.
927
928 - New command line utility ``celery graph``.
929
930 This utility creates graphs in GraphViz dot format.
931
932 You can create graphs from the currently installed bootsteps:
933
934 .. code-block:: console
935
936 # Create graph of currently installed bootsteps in both the worker
937 # and consumer name-spaces.
938 $ celery graph bootsteps | dot -T png -o steps.png
939
940 # Graph of the consumer name-space only.
941 $ celery graph bootsteps consumer | dot -T png -o consumer_only.png
942
943 # Graph of the worker name-space only.
944 $ celery graph bootsteps worker | dot -T png -o worker_only.png
945
946 Or graphs of workers in a cluster:
947
948 .. code-block:: console
949
950 # Create graph from the current cluster
951 $ celery graph workers | dot -T png -o workers.png
952
953 # Create graph from a specified list of workers
954 $ celery graph workers nodes:w1,w2,w3 | dot -T png workers.png
955
956 # also specify the number of threads in each worker
957 $ celery graph workers nodes:w1,w2,w3 threads:2,4,6
958
959 # …also specify the broker and backend URLs shown in the graph
960 $ celery graph workers broker:amqp:// backend:redis://
961
962 # …also specify the max number of workers/threads shown (wmax/tmax),
963 # enumerating anything that exceeds that number.
964 $ celery graph workers wmax:10 tmax:3
965
966 - Changed the way that app instances are pickled.
967
968 Apps can now define a ``__reduce_keys__`` method that's used instead
969 of the old ``AppPickler`` attribute. For example, if your app defines a custom
970 'foo' attribute that needs to be preserved when pickling you can define
971 a ``__reduce_keys__`` as such:
972
973 .. code-block:: python
974
975 import celery
976
977 class Celery(celery.Celery):
978
979 def __init__(self, *args, **kwargs):
980 super(Celery, self).__init__(*args, **kwargs)
981 self.foo = kwargs.get('foo')
982
983 def __reduce_keys__(self):
984 return super(Celery, self).__reduce_keys__().update(
985 foo=self.foo,
986 )
987
988 This is a much more convenient way to add support for pickling custom
989 attributes. The old ``AppPickler`` is still supported but its use is
990 discouraged and we would like to remove it in a future version.
991
992 - Ability to trace imports for debugging purposes.
993
994 The :envvar:`C_IMPDEBUG` can be set to trace imports as they
995 occur:
996
997 .. code-block:: console
998
999 $ C_IMDEBUG=1 celery worker -l info
1000
1001 .. code-block:: console
1002
1003 $ C_IMPDEBUG=1 celery shell
1004
1005 - Message headers now available as part of the task request.
1006
1007 Example adding and retrieving a header value:
1008
1009 .. code-block:: python
1010
1011 @app.task(bind=True)
1012 def t(self):
1013 return self.request.headers.get('sender')
1014
1015 >>> t.apply_async(headers={'sender': 'George Costanza'})
1016
1017 - New :signal:`before_task_publish` signal dispatched before a task message
1018 is sent and can be used to modify the final message fields (Issue #1281).
1019
1020 - New :signal:`after_task_publish` signal replaces the old :signal:`task_sent`
1021 signal.
1022
1023 The :signal:`task_sent` signal is now deprecated and shouldn't be used.
1024
1025 - New :signal:`worker_process_shutdown` signal is dispatched in the
1026 prefork pool child processes as they exit.
1027
1028 Contributed by Daniel M Taub.
1029
1030 - ``celery.platforms.PIDFile`` renamed to :class:`celery.platforms.Pidfile`.
1031
1032 - MongoDB Backend: Can now be configured using a URL:
1033
1034 - MongoDB Backend: No longer using deprecated ``pymongo.Connection``.
1035
1036 - MongoDB Backend: Now disables ``auto_start_request``.
1037
1038 - MongoDB Backend: Now enables ``use_greenlets`` when eventlet/gevent is used.
1039
1040 - ``subtask()`` / ``maybe_subtask()`` renamed to
1041 ``signature()``/``maybe_signature()``.
1042
1043 Aliases still available for backwards compatibility.
1044
1045 - The ``correlation_id`` message property is now automatically set to the
1046 id of the task.
1047
1048 - The task message ``eta`` and ``expires`` fields now includes timezone
1049 information.
1050
1051 - All result backends ``store_result``/``mark_as_*`` methods must now accept
1052 a ``request`` keyword argument.
1053
1054 - Events now emit warning if the broken ``yajl`` library is used.
1055
1056 - The :signal:`celeryd_init` signal now takes an extra keyword argument:
1057 ``option``.
1058
1059 This is the mapping of parsed command line arguments, and can be used to
1060 prepare new preload arguments (``app.user_options['preload']``).
1061
1062 - New callback: :meth:`@on_configure`.
1063
1064 This callback is called when an app is about to be configured (a
1065 configuration key is required).
1066
1067 - Worker: No longer forks on :sig:`HUP`.
1068
1069 This means that the worker will reuse the same pid for better
1070 support with external process supervisors.
1071
1072 Contributed by Jameel Al-Aziz.
1073
1074 - Worker: The log message ``Got task from broker …`` was changed to
1075 ``Received task …``.
1076
1077 - Worker: The log message ``Skipping revoked task …`` was changed
1078 to ``Discarding revoked task …``.
1079
1080 - Optimization: Improved performance of ``ResultSet.join_native()``.
1081
1082 Contributed by Stas Rudakou.
1083
1084 - The :signal:`task_revoked` signal now accepts new ``request`` argument
1085 (Issue #1555).
1086
1087 The revoked signal is dispatched after the task request is removed from
1088 the stack, so it must instead use the
1089 :class:`~celery.worker.request.Request` object to get information
1090 about the task.
1091
1092 - Worker: New :option:`-X <celery worker -X>` command line argument to
1093 exclude queues (Issue #1399).
1094
1095 The :option:`-X <celery worker -X>` argument is the inverse of the
1096 :option:`-Q <celery worker -Q>` argument and accepts a list of queues
1097 to exclude (not consume from):
1098
1099 .. code-block:: console
1100
1101 # Consume from all queues in CELERY_QUEUES, but not the 'foo' queue.
1102 $ celery worker -A proj -l info -X foo
1103
1104 - Adds :envvar:`C_FAKEFORK` environment variable for simple
1105 init-script/:program:`celery multi` debugging.
1106
1107 This means that you can now do:
1108
1109 .. code-block:: console
1110
1111 $ C_FAKEFORK=1 celery multi start 10
1112
1113 or:
1114
1115 .. code-block:: console
1116
1117 $ C_FAKEFORK=1 /etc/init.d/celeryd start
1118
1119 to avoid the daemonization step to see errors that aren't visible
1120 due to missing stdout/stderr.
1121
1122 A ``dryrun`` command has been added to the generic init-script that
1123 enables this option.
1124
1125 - New public API to push and pop from the current task stack:
1126
1127 :func:`celery.app.push_current_task` and
1128 :func:`celery.app.pop_current_task``.
1129
1130 - ``RetryTaskError`` has been renamed to :exc:`~celery.exceptions.Retry`.
1131
1132 The old name is still available for backwards compatibility.
1133
1134 - New semi-predicate exception :exc:`~celery.exceptions.Reject`.
1135
1136 This exception can be raised to ``reject``/``requeue`` the task message,
1137 see :ref:`task-semipred-reject` for examples.
1138
1139 - :ref:`Semipredicates <task-semipredicates>` documented: (Retry/Ignore/Reject).
1140
1141
1142 .. _v310-removals:
1143
1144 Scheduled Removals
1145 ==================
1146
1147 - The ``BROKER_INSIST`` setting and the ``insist`` argument
1148 to ``~@connection`` is no longer supported.
1149
1150 - The ``CELERY_AMQP_TASK_RESULT_CONNECTION_MAX`` setting is no longer
1151 supported.
1152
1153 Use :setting:`BROKER_POOL_LIMIT` instead.
1154
1155 - The ``CELERY_TASK_ERROR_WHITELIST`` setting is no longer supported.
1156
1157 You should set the :class:`~celery.utils.mail.ErrorMail` attribute
1158 of the task class instead. You can also do this using
1159 :setting:`CELERY_ANNOTATIONS`:
1160
1161 .. code-block:: python
1162
1163 from celery import Celery
1164 from celery.utils.mail import ErrorMail
1165
1166 class MyErrorMail(ErrorMail):
1167 whitelist = (KeyError, ImportError)
1168
1169 def should_send(self, context, exc):
1170 return isinstance(exc, self.whitelist)
1171
1172 app = Celery()
1173 app.conf.CELERY_ANNOTATIONS = {
1174 '*': {
1175 'ErrorMail': MyErrorMails,
1176 }
1177 }
1178
1179 - Functions that creates a broker connections no longer
1180 supports the ``connect_timeout`` argument.
1181
1182 This can now only be set using the :setting:`BROKER_CONNECTION_TIMEOUT`
1183 setting. This is because functions no longer create connections
1184 directly, but instead get them from the connection pool.
1185
1186 - The ``CELERY_AMQP_TASK_RESULT_EXPIRES`` setting is no longer supported.
1187
1188 Use :setting:`CELERY_TASK_RESULT_EXPIRES` instead.
1189
1190 .. _v310-deprecations:
1191
1192 Deprecation Time-line Changes
1193 =============================
1194
1195 See the :ref:`deprecation-timeline`.
1196
1197 .. _v310-fixes:
1198
1199 Fixes
1200 =====
1201
1202 - AMQP Backend: join didn't convert exceptions when using the json
1203 serializer.
1204
1205 - Non-abstract task classes are now shared between apps (Issue #1150).
1206
1207 Note that non-abstract task classes shouldn't be used in the
1208 new API. You should only create custom task classes when you
1209 use them as a base class in the ``@task`` decorator.
1210
1211 This fix ensure backwards compatibility with older Celery versions
1212 so that non-abstract task classes works even if a module is imported
1213 multiple times so that the app is also instantiated multiple times.
1214
1215 - Worker: Workaround for Unicode errors in logs (Issue #427).
1216
1217 - Task methods: ``.apply_async`` now works properly if args list is None
1218 (Issue #1459).
1219
1220 - Eventlet/gevent/solo/threads pools now properly handles :exc:`BaseException`
1221 errors raised by tasks.
1222
1223 - :control:`autoscale` and :control:`pool_grow`/:control:`pool_shrink` remote
1224 control commands will now also automatically increase and decrease the
1225 consumer prefetch count.
1226
1227 Fix contributed by Daniel M. Taub.
1228
1229 - ``celery control pool_`` commands didn't coerce string arguments to int.
1230
1231 - Redis/Cache chords: Callback result is now set to failure if the group
1232 disappeared from the database (Issue #1094).
1233
1234 - Worker: Now makes sure that the shutdown process isn't initiated more
1235 than once.
1236
1237 - Programs: :program:`celery multi` now properly handles both ``-f`` and
1238 :option:`--logfile <celery worker --logfile>` options (Issue #1541).
1239
1240 .. _v310-internal:
1241
1242 Internal changes
1243 ================
1244
1245 - Module ``celery.task.trace`` has been renamed to :mod:`celery.app.trace`.
1246
1247 - Module ``celery.concurrency.processes`` has been renamed to
1248 :mod:`celery.concurrency.prefork`.
1249
1250 - Classes that no longer fall back to using the default app:
1251
1252 - Result backends (:class:`celery.backends.base.BaseBackend`)
1253 - :class:`celery.worker.WorkController`
1254 - :class:`celery.worker.Consumer`
1255 - :class:`celery.worker.request.Request`
1256
1257 This means that you have to pass a specific app when instantiating
1258 these classes.
1259
1260 - ``EventDispatcher.copy_buffer`` renamed to
1261 :meth:`@events.Dispatcher.extend_buffer`.
1262
1263 - Removed unused and never documented global instance
1264 ``celery.events.state.state``.
1265
1266 - :class:`@events.Receiver` is now a :class:`kombu.mixins.ConsumerMixin`
1267 subclass.
1268
1269 - :class:`celery.apps.worker.Worker` has been refactored as a subclass of
1270 :class:`celery.worker.WorkController`.
1271
1272 This removes a lot of duplicate functionality.
1273
1274 - The ``Celery.with_default_connection`` method has been removed in favor
1275 of ``with app.connection_or_acquire`` (:meth:`@connection_or_acquire`)
1276
1277 - The ``celery.results.BaseDictBackend`` class has been removed and is replaced by
1278 :class:`celery.results.BaseBackend`.