Debian Codegraph @

docs/userguide/signals.rst

raw
1 .. _signals:
2
3 =======
4 Signals
5 =======
6
7 .. contents::
8 :local:
9
10 Signals allow decoupled applications to receive notifications when
11 certain actions occur elsewhere in the application.
12
13 Celery ships with many signals that your application can hook into
14 to augment behavior of certain actions.
15
16 .. _signal-basics:
17
18 Basics
19 ======
20
21 Several kinds of events trigger signals, you can connect to these signals
22 to perform actions as they trigger.
23
24 Example connecting to the :signal:`after_task_publish` signal:
25
26 .. code-block:: python
27
28 from celery.signals import after_task_publish
29
30 @after_task_publish.connect
31 def task_sent_handler(sender=None, headers=None, body=None, **kwargs):
32 # information about task are located in headers for task messages
33 # using the task protocol version 2.
34 info = headers if 'task' in headers else body
35 print('after_task_publish for task id {info[id]}'.format(
36 info=info,
37 ))
38
39
40 Some signals also have a sender you can filter by. For example the
41 :signal:`after_task_publish` signal uses the task name as a sender, so by
42 providing the ``sender`` argument to
43 :class:`~celery.utils.dispatch.signal.Signal.connect` you can
44 connect your handler to be called every time a task with name `"proj.tasks.add"`
45 is published:
46
47 .. code-block:: python
48
49 @after_task_publish.connect(sender='proj.tasks.add')
50 def task_sent_handler(sender=None, headers=None, body=None, **kwargs):
51 # information about task are located in headers for task messages
52 # using the task protocol version 2.
53 info = headers if 'task' in headers else body
54 print('after_task_publish for task id {info[id]}'.format(
55 info=info,
56 ))
57
58 Signals use the same implementation as :mod:`django.core.dispatch`. As a
59 result other keyword parameters (e.g., signal) are passed to all signal
60 handlers by default.
61
62 The best practice for signal handlers is to accept arbitrary keyword
63 arguments (i.e., ``**kwargs``). That way new Celery versions can add additional
64 arguments without breaking user code.
65
66 .. _signal-ref:
67
68 Signals
69 =======
70
71 Task Signals
72 ------------
73
74 .. signal:: before_task_publish
75
76 ``before_task_publish``
77 ~~~~~~~~~~~~~~~~~~~~~~~
78 .. versionadded:: 3.1
79
80 Dispatched before a task is published.
81 Note that this is executed in the process sending the task.
82
83 Sender is the name of the task being sent.
84
85 Provides arguments:
86
87 * ``body``
88
89 Task message body.
90
91 This is a mapping containing the task message fields,
92 see :ref:`message-protocol-task-v2`
93 and :ref:`message-protocol-task-v1`
94 for a reference of possible fields that can be defined.
95
96 * ``exchange``
97
98 Name of the exchange to send to or a :class:`~kombu.Exchange` object.
99
100 * ``routing_key``
101
102 Routing key to use when sending the message.
103
104 * ``headers``
105
106 Application headers mapping (can be modified).
107
108 * ``properties``
109
110 Message properties (can be modified)
111
112 * ``declare``
113
114 List of entities (:class:`~kombu.Exchange`,
115 :class:`~kombu.Queue`, or :class:`~kombu.binding` to declare before
116 publishing the message. Can be modified.
117
118 * ``retry_policy``
119
120 Mapping of retry options. Can be any argument to
121 :meth:`kombu.Connection.ensure` and can be modified.
122
123 .. signal:: after_task_publish
124
125 ``after_task_publish``
126 ~~~~~~~~~~~~~~~~~~~~~~
127
128 Dispatched when a task has been sent to the broker.
129 Note that this is executed in the process that sent the task.
130
131 Sender is the name of the task being sent.
132
133 Provides arguments:
134
135 * ``headers``
136
137 The task message headers, see :ref:`message-protocol-task-v2`
138 and :ref:`message-protocol-task-v1`
139 for a reference of possible fields that can be defined.
140
141 * ``body``
142
143 The task message body, see :ref:`message-protocol-task-v2`
144 and :ref:`message-protocol-task-v1`
145 for a reference of possible fields that can be defined.
146
147 * ``exchange``
148
149 Name of the exchange or :class:`~kombu.Exchange` object used.
150
151 * ``routing_key``
152
153 Routing key used.
154
155 .. signal:: task_prerun
156
157 ``task_prerun``
158 ~~~~~~~~~~~~~~~
159
160 Dispatched before a task is executed.
161
162 Sender is the task object being executed.
163
164 Provides arguments:
165
166 * ``task_id``
167
168 Id of the task to be executed.
169
170 * ``task``
171
172 The task being executed.
173
174 * ``args``
175
176 The tasks positional arguments.
177
178 * ``kwargs``
179
180 The tasks keyword arguments.
181
182 .. signal:: task_postrun
183
184 ``task_postrun``
185 ~~~~~~~~~~~~~~~~
186
187 Dispatched after a task has been executed.
188
189 Sender is the task object executed.
190
191 Provides arguments:
192
193 * ``task_id``
194
195 Id of the task to be executed.
196
197 * ``task``
198
199 The task being executed.
200
201 * ``args``
202
203 The tasks positional arguments.
204
205 * ``kwargs``
206
207 The tasks keyword arguments.
208
209 * ``retval``
210
211 The return value of the task.
212
213 * ``state``
214
215 Name of the resulting state.
216
217 .. signal:: task_retry
218
219 ``task_retry``
220 ~~~~~~~~~~~~~~
221
222 Dispatched when a task will be retried.
223
224 Sender is the task object.
225
226 Provides arguments:
227
228 * ``request``
229
230 The current task request.
231
232 * ``reason``
233
234 Reason for retry (usually an exception instance, but can always be
235 coerced to :class:`str`).
236
237 * ``einfo``
238
239 Detailed exception information, including traceback
240 (a :class:`billiard.einfo.ExceptionInfo` object).
241
242 .. note::
243
244 Only the ``request`` argument is guaranteed to be provided in all cases.
245 The ``reason`` and ``einfo`` arguments may be ``None`` or not provided
246 in certain scenarios, such as when a task is cancelled and retried.
247 Signal handlers should not assume these arguments are always present.
248
249 .. signal:: task_success
250
251 ``task_success``
252 ~~~~~~~~~~~~~~~~
253
254 Dispatched when a task succeeds.
255
256 Sender is the task object executed.
257
258 Provides arguments
259
260 * ``result``
261 Return value of the task.
262
263 .. signal:: task_failure
264
265 ``task_failure``
266 ~~~~~~~~~~~~~~~~
267
268 Dispatched when a task fails.
269
270 Sender is the task object executed.
271
272 Provides arguments:
273
274 * ``task_id``
275
276 Id of the task.
277
278 * ``exception``
279
280 Exception instance raised.
281
282 * ``args``
283
284 Positional arguments the task was called with.
285
286 * ``kwargs``
287
288 Keyword arguments the task was called with.
289
290 * ``traceback``
291
292 Stack trace object.
293
294 * ``einfo``
295
296 The :class:`billiard.einfo.ExceptionInfo` instance.
297
298 ``task_internal_error``
299 ~~~~~~~~~~~~~~~~~~~~~~~
300
301 Dispatched when an internal Celery error occurs while executing the task.
302
303 Sender is the task object executed.
304
305 .. signal:: task_internal_error
306
307 Provides arguments:
308
309 * ``task_id``
310
311 Id of the task.
312
313 * ``args``
314
315 Positional arguments the task was called with.
316
317 * ``kwargs``
318
319 Keyword arguments the task was called with.
320
321 * ``request``
322
323 The original request dictionary.
324 This is provided as the ``task.request`` may not be ready by the time
325 the exception is raised.
326
327 * ``exception``
328
329 Exception instance raised.
330
331 * ``traceback``
332
333 Stack trace object.
334
335 * ``einfo``
336
337 The :class:`billiard.einfo.ExceptionInfo` instance.
338
339 ``task_received``
340 ~~~~~~~~~~~~~~~~~
341
342 Dispatched when a task is received from the broker and is ready for execution.
343
344 Sender is the consumer object.
345
346 .. signal:: task_received
347
348 Provides arguments:
349
350 * ``request``
351
352 This is a :class:`~celery.worker.request.Request` instance, and not
353 ``task.request``. When using the prefork pool this signal
354 is dispatched in the parent process, so ``task.request`` isn't available
355 and shouldn't be used. Use this object instead, as they share many
356 of the same fields.
357
358 .. signal:: task_revoked
359
360 ``task_revoked``
361 ~~~~~~~~~~~~~~~~
362
363 Dispatched when a task is revoked/terminated by the worker.
364
365 Sender is the task object revoked/terminated.
366
367 Provides arguments:
368
369 * ``request``
370
371 This is a :class:`~celery.app.task.Context` instance, and not
372 ``task.request``. When using the prefork pool this signal
373 is dispatched in the parent process, so ``task.request`` isn't available
374 and shouldn't be used. Use this object instead, as they share many
375 of the same fields.
376
377 * ``terminated``
378
379 Set to :const:`True` if the task was terminated.
380
381 * ``signum``
382
383 Signal number used to terminate the task. If this is :const:`None` and
384 terminated is :const:`True` then :sig:`TERM` should be assumed.
385
386 * ``expired``
387
388 Set to :const:`True` if the task expired.
389
390 .. signal:: task_unknown
391
392 ``task_unknown``
393 ~~~~~~~~~~~~~~~~
394
395 Dispatched when a worker receives a message for a task that's not registered.
396
397 Sender is the worker :class:`~celery.worker.consumer.Consumer`.
398
399 Provides arguments:
400
401 * ``name``
402
403 Name of task not found in registry.
404
405 * ``id``
406
407 The task id found in the message.
408
409 * ``message``
410
411 Raw message object.
412
413 * ``exc``
414
415 The error that occurred.
416
417 .. signal:: task_rejected
418
419 ``task_rejected``
420 ~~~~~~~~~~~~~~~~~
421
422 Dispatched when a worker receives an unknown type of message to one of its
423 task queues.
424
425 Sender is the worker :class:`~celery.worker.consumer.Consumer`.
426
427 Provides arguments:
428
429 * ``message``
430
431 Raw message object.
432
433 * ``exc``
434
435 The error that occurred (if any).
436
437 App Signals
438 -----------
439
440 .. signal:: import_modules
441
442 ``import_modules``
443 ~~~~~~~~~~~~~~~~~~
444
445 This signal is sent when a program (worker, beat, shell) etc, asks
446 for modules in the :setting:`include` and :setting:`imports`
447 settings to be imported.
448
449 Sender is the app instance.
450
451 Worker Signals
452 --------------
453
454 .. signal:: celeryd_after_setup
455
456 ``celeryd_after_setup``
457 ~~~~~~~~~~~~~~~~~~~~~~~
458
459 This signal is sent after the worker instance is set up, but before it
460 calls run. This means that any queues from the :option:`celery worker -Q`
461 option is enabled, logging has been set up and so on.
462
463 It can be used to add custom queues that should always be consumed
464 from, disregarding the :option:`celery worker -Q` option. Here's an example
465 that sets up a direct queue for each worker, these queues can then be
466 used to route a task to any specific worker:
467
468 .. code-block:: python
469
470 from celery.signals import celeryd_after_setup
471
472 @celeryd_after_setup.connect
473 def setup_direct_queue(sender, instance, **kwargs):
474 queue_name = '{0}.dq'.format(sender) # sender is the nodename of the worker
475 instance.app.amqp.queues.select_add(queue_name)
476
477 Provides arguments:
478
479 * ``sender``
480
481 Node name of the worker.
482
483 * ``instance``
484
485 This is the :class:`celery.apps.worker.Worker` instance to be initialized.
486 Note that only the :attr:`app` and :attr:`hostname` (nodename) attributes have been
487 set so far, and the rest of ``__init__`` hasn't been executed.
488
489 * ``conf``
490
491 The configuration of the current app.
492
493 .. signal:: celeryd_init
494
495 ``celeryd_init``
496 ~~~~~~~~~~~~~~~~
497
498 This is the first signal sent when :program:`celery worker` starts up.
499 The ``sender`` is the host name of the worker, so this signal can be used
500 to setup worker specific configuration:
501
502 .. code-block:: python
503
504 from celery.signals import celeryd_init
505
506 @celeryd_init.connect(sender='[email protected]')
507 def configure_worker12(conf=None, **kwargs):
508 conf.task_default_rate_limit = '10/m'
509
510 or to set up configuration for multiple workers you can omit specifying a
511 sender when you connect:
512
513 .. code-block:: python
514
515 from celery.signals import celeryd_init
516
517 @celeryd_init.connect
518 def configure_workers(sender=None, conf=None, **kwargs):
519 if sender in ('[email protected]', '[email protected]'):
520 conf.task_default_rate_limit = '10/m'
521 if sender == '[email protected]':
522 conf.worker_prefetch_multiplier = 0
523
524 Provides arguments:
525
526 * ``sender``
527
528 Nodename of the worker.
529
530 * ``instance``
531
532 This is the :class:`celery.apps.worker.Worker` instance to be initialized.
533 Note that only the :attr:`app` and :attr:`hostname` (nodename) attributes have been
534 set so far, and the rest of ``__init__`` hasn't been executed.
535
536 * ``conf``
537
538 The configuration of the current app.
539
540 * ``options``
541
542 Options passed to the worker from command-line arguments (including
543 defaults).
544
545 .. signal:: worker_init
546
547 ``worker_init``
548 ~~~~~~~~~~~~~~~
549
550 Dispatched before the worker is started.
551
552 .. signal:: worker_before_create_process
553
554 ``worker_before_create_process``
555 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
556
557 Dispatched in the parent process, just before new child process is created in the prefork pool.
558 It can be used to clean up instances that don't behave well when forking.
559
560 .. code-block:: python
561
562 @signals.worker_before_create_process.connect
563 def clean_channels(**kwargs):
564 grpc_singleton.clean_channel()
565
566 .. signal:: worker_ready
567
568 ``worker_ready``
569 ~~~~~~~~~~~~~~~~
570
571 Dispatched when the worker is ready to accept work.
572
573 .. signal:: heartbeat_sent
574
575 ``heartbeat_sent``
576 ~~~~~~~~~~~~~~~~~~
577
578 Dispatched when Celery sends a worker heartbeat.
579
580 Sender is the :class:`celery.worker.heartbeat.Heart` instance.
581
582 .. signal:: worker_shutting_down
583
584 ``worker_shutting_down``
585 ~~~~~~~~~~~~~~~~~~~~~~~~
586
587 Dispatched when the worker begins the shutdown process.
588
589 Provides arguments:
590
591 * ``sig``
592
593 The POSIX signal that was received.
594
595 * ``how``
596
597 The shutdown method, warm or cold.
598
599 * ``exitcode``
600
601 The exitcode that will be used when the main process exits.
602
603 .. signal:: worker_process_init
604
605 ``worker_process_init``
606 ~~~~~~~~~~~~~~~~~~~~~~~
607
608 Dispatched in all pool child processes when they start.
609
610 Note that handlers attached to this signal mustn't be blocking
611 for more than 4 seconds, or the process will be killed assuming
612 it failed to start.
613
614 .. signal:: worker_process_shutdown
615
616 ``worker_process_shutdown``
617 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
618
619 Dispatched in all pool child processes just before they exit.
620
621 Note: There's no guarantee that this signal will be dispatched,
622 similarly to :keyword:`finally` blocks it's impossible to guarantee that
623 handlers will be called at shutdown, and if called it may be
624 interrupted during.
625
626 Provides arguments:
627
628 * ``pid``
629
630 The pid of the child process that's about to shutdown.
631
632 * ``exitcode``
633
634 The exitcode that'll be used when the child process exits.
635
636 .. signal:: worker_shutdown
637
638 ``worker_shutdown``
639 ~~~~~~~~~~~~~~~~~~~
640
641 Dispatched when the worker is about to shut down.
642
643 Beat Signals
644 ------------
645
646 .. signal:: beat_init
647
648 ``beat_init``
649 ~~~~~~~~~~~~~
650
651 Dispatched when :program:`celery beat` starts (either standalone or embedded).
652
653 Sender is the :class:`celery.beat.Service` instance.
654
655 .. signal:: beat_embedded_init
656
657 ``beat_embedded_init``
658 ~~~~~~~~~~~~~~~~~~~~~~
659
660 Dispatched in addition to the :signal:`beat_init` signal when :program:`celery
661 beat` is started as an embedded process.
662
663 Sender is the :class:`celery.beat.Service` instance.
664
665 Eventlet Signals
666 ----------------
667
668 .. signal:: eventlet_pool_started
669
670 ``eventlet_pool_started``
671 ~~~~~~~~~~~~~~~~~~~~~~~~~
672
673 Sent when the eventlet pool has been started.
674
675 Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
676
677 .. signal:: eventlet_pool_preshutdown
678
679 ``eventlet_pool_preshutdown``
680 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
681
682 Sent when the worker shutdown, just before the eventlet pool
683 is requested to wait for remaining workers.
684
685 Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
686
687 .. signal:: eventlet_pool_postshutdown
688
689 ``eventlet_pool_postshutdown``
690 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
691
692 Sent when the pool has been joined and the worker is ready to shutdown.
693
694 Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
695
696 .. signal:: eventlet_pool_apply
697
698 ``eventlet_pool_apply``
699 ~~~~~~~~~~~~~~~~~~~~~~~
700
701 Sent whenever a task is applied to the pool.
702
703 Sender is the :class:`celery.concurrency.eventlet.TaskPool` instance.
704
705 Provides arguments:
706
707 * ``target``
708
709 The target function.
710
711 * ``args``
712
713 Positional arguments.
714
715 * ``kwargs``
716
717 Keyword arguments.
718
719 Logging Signals
720 ---------------
721
722 .. signal:: setup_logging
723
724 ``setup_logging``
725 ~~~~~~~~~~~~~~~~~
726
727 Celery won't configure the loggers if this signal is connected,
728 so you can use this to completely override the logging configuration
729 with your own.
730
731 If you'd like to augment the logging configuration setup by
732 Celery then you can use the :signal:`after_setup_logger` and
733 :signal:`after_setup_task_logger` signals.
734
735 Provides arguments:
736
737 * ``loglevel``
738
739 The level of the logging object.
740
741 * ``logfile``
742
743 The name of the logfile.
744
745 * ``format``
746
747 The log format string.
748
749 * ``colorize``
750
751 Specify if log messages are colored or not.
752
753 .. signal:: after_setup_logger
754
755 ``after_setup_logger``
756 ~~~~~~~~~~~~~~~~~~~~~~
757
758 Sent after the setup of every global logger (not task loggers).
759 Used to augment logging configuration.
760
761 Provides arguments:
762
763 * ``logger``
764
765 The logger object.
766
767 * ``loglevel``
768
769 The level of the logging object.
770
771 * ``logfile``
772
773 The name of the logfile.
774
775 * ``format``
776
777 The log format string.
778
779 * ``colorize``
780
781 Specify if log messages are colored or not.
782
783 .. signal:: after_setup_task_logger
784
785 ``after_setup_task_logger``
786 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
787
788 Sent after the setup of every single task logger.
789 Used to augment logging configuration.
790
791 Provides arguments:
792
793 * ``logger``
794
795 The logger object.
796
797 * ``loglevel``
798
799 The level of the logging object.
800
801 * ``logfile``
802
803 The name of the logfile.
804
805 * ``format``
806
807 The log format string.
808
809 * ``colorize``
810
811 Specify if log messages are colored or not.
812
813 Command signals
814 ---------------
815
816 .. signal:: user_preload_options
817
818 ``user_preload_options``
819 ~~~~~~~~~~~~~~~~~~~~~~~~
820
821 This signal is sent after any of the Celery command line programs
822 are finished parsing the user preload options.
823
824 It can be used to add additional command-line arguments to the
825 :program:`celery` umbrella command:
826
827 .. code-block:: python
828
829 from celery import Celery, signals
830 from click import Option
831
832 app = Celery()
833
834 # Celery 5.0+ uses click for its command-line interface.
835 # Use click.option to add new command-line arguments.
836 app.user_options['preload'].add(Option(
837 ('--monitoring',), is_flag=True,
838 help='Enable our external monitoring utility, blahblah',
839 ))
840
841 @signals.user_preload_options.connect
842 def handle_preload_options(options, **kwargs):
843 if options.get('monitoring'):
844 enable_monitoring()
845
846
847
848 Sender is the :class:`~celery.bin.base.Command` instance, and the value depends
849 on the program that was called (e.g., for the umbrella command it'll be
850 a :class:`~celery.bin.celery.CeleryCommand`) object).
851
852 Provides arguments:
853
854 * ``app``
855
856 The app instance.
857
858 * ``options``
859
860 Mapping of the parsed user preload options (with default values).
861
862 Deprecated Signals
863 ------------------
864
865 .. signal:: task_sent
866
867 ``task_sent``
868 ~~~~~~~~~~~~~
869
870 This signal is deprecated, please use :signal:`after_task_publish` instead.