Debian Codegraph @

docs/userguide/extending.rst

raw
1 .. _guide-extending:
2
3 ==========================
4 Extensions and Bootsteps
5 ==========================
6
7 .. contents::
8 :local:
9 :depth: 2
10
11 .. _extending-custom-consumers:
12
13 Custom Message Consumers
14 ========================
15
16 You may want to embed custom Kombu consumers to manually process your messages.
17
18 For that purpose a special :class:`~celery.bootstep.ConsumerStep` bootstep class
19 exists, where you only need to define the ``get_consumers`` method, that must
20 return a list of :class:`kombu.Consumer` objects to start
21 whenever the connection is established:
22
23 .. code-block:: python
24
25 from celery import Celery
26 from celery import bootsteps
27 from kombu import Consumer, Exchange, Queue
28
29 my_queue = Queue('custom', Exchange('custom'), 'routing_key')
30
31 app = Celery(broker='amqp://')
32
33
34 class MyConsumerStep(bootsteps.ConsumerStep):
35
36 def get_consumers(self, channel):
37 return [Consumer(channel,
38 queues=[my_queue],
39 callbacks=[self.handle_message],
40 accept=['json'])]
41
42 def handle_message(self, body, message):
43 print('Received message: {0!r}'.format(body))
44 message.ack()
45 app.steps['consumer'].add(MyConsumerStep)
46
47 def send_me_a_message(who, producer=None):
48 with app.producer_or_acquire(producer) as producer:
49 producer.publish(
50 {'hello': who},
51 serializer='json',
52 exchange=my_queue.exchange,
53 routing_key='routing_key',
54 declare=[my_queue],
55 retry=True,
56 )
57
58 if __name__ == '__main__':
59 send_me_a_message('world!')
60
61
62 .. note::
63
64 Kombu Consumers can take use of two different message callback dispatching
65 mechanisms. The first one is the ``callbacks`` argument that accepts
66 a list of callbacks with a ``(body, message)`` signature,
67 the second one is the ``on_message`` argument that takes a single
68 callback with a ``(message,)`` signature. The latter won't
69 automatically decode and deserialize the payload.
70
71 .. code-block:: python
72
73 def get_consumers(self, channel):
74 return [Consumer(channel, queues=[my_queue],
75 on_message=self.on_message)]
76
77
78 def on_message(self, message):
79 payload = message.decode()
80 print(
81 'Received message: {0!r} {props!r} rawlen={s}'.format(
82 payload, props=message.properties, s=len(message.body),
83 ))
84 message.ack()
85
86 .. _extending-blueprints:
87
88 Blueprints
89 ==========
90
91 Bootsteps is a technique to add functionality to the workers.
92 A bootstep is a custom class that defines hooks to do custom actions
93 at different stages in the worker. Every bootstep belongs to a blueprint,
94 and the worker currently defines two blueprints: **Worker**, and **Consumer**
95
96 ----------------------------------------------------------
97
98 **Figure A:** Bootsteps in the Worker and Consumer blueprints. Starting
99 from the bottom up the first step in the worker blueprint
100 is the Timer, and the last step is to start the Consumer blueprint,
101 that then establishes the broker connection and starts
102 consuming messages.
103
104 .. figure:: ../images/worker_graph_full.png
105
106 ----------------------------------------------------------
107
108 .. _extending-worker_blueprint:
109
110 Worker
111 ======
112
113 The Worker is the first blueprint to start, and with it starts major components like
114 the event loop, processing pool, and the timer used for ETA tasks and other
115 timed events.
116
117 When the worker is fully started it continues with the Consumer blueprint,
118 that sets up how tasks are executed, connects to the broker and starts
119 the message consumers.
120
121 The :class:`~celery.worker.WorkController` is the core worker implementation,
122 and contains several methods and attributes that you can use in your bootstep.
123
124 .. _extending-worker_blueprint-attributes:
125
126 Attributes
127 ----------
128
129 .. _extending-worker-app:
130
131 .. attribute:: app
132
133 The current app instance.
134
135 .. _extending-worker-hostname:
136
137 .. attribute:: hostname
138
139 The workers node name (e.g., `[email protected]`)
140
141 .. _extending-worker-blueprint:
142
143 .. attribute:: blueprint
144
145 This is the worker :class:`~celery.bootsteps.Blueprint`.
146
147 .. _extending-worker-hub:
148
149 .. attribute:: hub
150
151 Event loop object (:class:`~kombu.asynchronous.Hub`). You can use
152 this to register callbacks in the event loop.
153
154 This is only supported by async I/O enabled transports (amqp, redis),
155 in which case the `worker.use_eventloop` attribute should be set.
156
157 Your worker bootstep must require the Hub bootstep to use this:
158
159 .. code-block:: python
160
161 class WorkerStep(bootsteps.StartStopStep):
162 requires = {'celery.worker.components:Hub'}
163
164 .. _extending-worker-pool:
165
166 .. attribute:: pool
167
168 The current process/eventlet/gevent/thread pool.
169 See :class:`celery.concurrency.base.BasePool`.
170
171 Your worker bootstep must require the Pool bootstep to use this:
172
173 .. code-block:: python
174
175 class WorkerStep(bootsteps.StartStopStep):
176 requires = {'celery.worker.components:Pool'}
177
178 .. _extending-worker-timer:
179
180 .. attribute:: timer
181
182 :class:`~kombu.asynchronous.timer.Timer` used to schedule functions.
183
184 Your worker bootstep must require the Timer bootstep to use this:
185
186 .. code-block:: python
187
188 class WorkerStep(bootsteps.StartStopStep):
189 requires = {'celery.worker.components:Timer'}
190
191 .. _extending-worker-statedb:
192
193 .. attribute:: statedb
194
195 :class:`Database <celery.worker.state.Persistent>`` to persist state between
196 worker restarts.
197
198 This is only defined if the ``statedb`` argument is enabled.
199
200 Your worker bootstep must require the ``Statedb`` bootstep to use this:
201
202 .. code-block:: python
203
204 class WorkerStep(bootsteps.StartStopStep):
205 requires = {'celery.worker.components:Statedb'}
206
207 .. _extending-worker-autoscaler:
208
209 .. attribute:: autoscaler
210
211 :class:`~celery.worker.autoscaler.Autoscaler` used to automatically grow
212 and shrink the number of processes in the pool.
213
214 This is only defined if the ``autoscale`` argument is enabled.
215
216 Your worker bootstep must require the `Autoscaler` bootstep to use this:
217
218 .. code-block:: python
219
220 class WorkerStep(bootsteps.StartStopStep):
221 requires = ('celery.worker.autoscaler:Autoscaler',)
222
223 Example worker bootstep
224 -----------------------
225
226 An example Worker bootstep could be:
227
228 .. code-block:: python
229
230 from celery import bootsteps
231
232 class ExampleWorkerStep(bootsteps.StartStopStep):
233 requires = {'celery.worker.components:Pool'}
234
235 def __init__(self, worker, **kwargs):
236 print('Called when the WorkController instance is constructed')
237 print('Arguments to WorkController: {0!r}'.format(kwargs))
238
239 def create(self, worker):
240 # this method can be used to delegate the action methods
241 # to another object that implements ``start`` and ``stop``.
242 return self
243
244 def start(self, worker):
245 print('Called when the worker is started.')
246
247 def stop(self, worker):
248 print('Called when the worker shuts down.')
249
250 def terminate(self, worker):
251 print('Called when the worker terminates')
252
253
254 Every method is passed the current ``WorkController`` instance as the first
255 argument.
256
257 Another example could use the timer to wake up at regular intervals:
258
259 .. code-block:: python
260
261 from celery import bootsteps
262
263
264 class DeadlockDetection(bootsteps.StartStopStep):
265 requires = {'celery.worker.components:Timer'}
266
267 def __init__(self, worker, deadlock_timeout=3600):
268 self.timeout = deadlock_timeout
269 self.requests = []
270 self.tref = None
271
272 def start(self, worker):
273 # run every 30 seconds.
274 self.tref = worker.timer.call_repeatedly(
275 30.0, self.detect, (worker,), priority=10,
276 )
277
278 def stop(self, worker):
279 if self.tref:
280 self.tref.cancel()
281 self.tref = None
282
283 def detect(self, worker):
284 # update active requests
285 for req in worker.active_requests:
286 if req.time_start and time() - req.time_start > self.timeout:
287 raise SystemExit()
288
289 Customizing Task Handling Logs
290 ------------------------------
291
292 The Celery worker emits messages to the Python logging subsystem for various
293 events throughout the lifecycle of a task.
294 These messages can be customized by overriding the ``LOG_<TYPE>`` format
295 strings which are defined in :file:`celery/app/trace.py`.
296 For example:
297
298 .. code-block:: python
299
300 import celery.app.trace
301
302 celery.app.trace.LOG_SUCCESS = "This is a custom message"
303
304 The various format strings are all provided with the task name and ID for
305 ``%`` formatting, and some of them receive extra fields like the return value
306 or the exception which caused a task to fail.
307 These fields can be used in custom format strings like so:
308
309 .. code-block:: python
310
311 import celery.app.trace
312
313 celery.app.trace.LOG_REJECTED = "%(name)r is cursed and I won't run it: %(exc)s"
314
315 .. _extending-consumer_blueprint:
316
317 Consumer
318 ========
319
320 The Consumer blueprint establishes a connection to the broker, and
321 is restarted every time this connection is lost. Consumer bootsteps
322 include the worker heartbeat, the remote control command consumer, and
323 importantly, the task consumer.
324
325 When you create consumer bootsteps you must take into account that it must
326 be possible to restart your blueprint. An additional 'shutdown' method is
327 defined for consumer bootsteps, this method is called when the worker is
328 shutdown.
329
330 .. _extending-consumer-attributes:
331
332 Attributes
333 ----------
334
335 .. _extending-consumer-app:
336
337 .. attribute:: app
338
339 The current app instance.
340
341 .. _extending-consumer-controller:
342
343 .. attribute:: controller
344
345 The parent :class:`~@WorkController` object that created this consumer.
346
347 .. _extending-consumer-hostname:
348
349 .. attribute:: hostname
350
351 The workers node name (e.g., `[email protected]`)
352
353 .. _extending-consumer-blueprint:
354
355 .. attribute:: blueprint
356
357 This is the worker :class:`~celery.bootsteps.Blueprint`.
358
359 .. _extending-consumer-hub:
360
361 .. attribute:: hub
362
363 Event loop object (:class:`~kombu.asynchronous.Hub`). You can use
364 this to register callbacks in the event loop.
365
366 This is only supported by async I/O enabled transports (amqp, redis),
367 in which case the `worker.use_eventloop` attribute should be set.
368
369 Your worker bootstep must require the Hub bootstep to use this:
370
371 .. code-block:: python
372
373 class WorkerStep(bootsteps.StartStopStep):
374 requires = {'celery.worker.components:Hub'}
375
376 .. _extending-consumer-connection:
377
378 .. attribute:: connection
379
380 The current broker connection (:class:`kombu.Connection`).
381
382 A consumer bootstep must require the 'Connection' bootstep
383 to use this:
384
385 .. code-block:: python
386
387 class Step(bootsteps.StartStopStep):
388 requires = {'celery.worker.consumer.connection:Connection'}
389
390 .. _extending-consumer-event_dispatcher:
391
392 .. attribute:: event_dispatcher
393
394 A :class:`@events.Dispatcher` object that can be used to send events.
395
396 A consumer bootstep must require the `Events` bootstep to use this.
397
398 .. code-block:: python
399
400 class Step(bootsteps.StartStopStep):
401 requires = {'celery.worker.consumer.events:Events'}
402
403 .. _extending-consumer-gossip:
404
405 .. attribute:: gossip
406
407 Worker to worker broadcast communication
408 (:class:`~celery.worker.consumer.gossip.Gossip`).
409
410 A consumer bootstep must require the `Gossip` bootstep to use this.
411
412 .. code-block:: python
413
414 class RatelimitStep(bootsteps.StartStopStep):
415 """Rate limit tasks based on the number of workers in the
416 cluster."""
417 requires = {'celery.worker.consumer.gossip:Gossip'}
418
419 def start(self, c):
420 self.c = c
421 self.c.gossip.on.node_join.add(self.on_cluster_size_change)
422 self.c.gossip.on.node_leave.add(self.on_cluster_size_change)
423 self.c.gossip.on.node_lost.add(self.on_node_lost)
424 self.tasks = [
425 self.app.tasks['proj.tasks.add']
426 self.app.tasks['proj.tasks.mul']
427 ]
428 self.last_size = None
429
430 def on_cluster_size_change(self, worker):
431 cluster_size = len(list(self.c.gossip.state.alive_workers()))
432 if cluster_size != self.last_size:
433 for task in self.tasks:
434 task.rate_limit = 1.0 / cluster_size
435 self.c.reset_rate_limits()
436 self.last_size = cluster_size
437
438 def on_node_lost(self, worker):
439 # may have processed heartbeat too late, so wake up soon
440 # in order to see if the worker recovered.
441 self.c.timer.call_after(10.0, self.on_cluster_size_change)
442
443 **Callbacks**
444
445 - ``<set> gossip.on.node_join``
446
447 Called whenever a new node joins the cluster, providing a
448 :class:`~celery.events.state.Worker` instance.
449
450 - ``<set> gossip.on.node_leave``
451
452 Called whenever a new node leaves the cluster (shuts down),
453 providing a :class:`~celery.events.state.Worker` instance.
454
455 - ``<set> gossip.on.node_lost``
456
457 Called whenever heartbeat was missed for a worker instance in the
458 cluster (heartbeat not received or processed in time),
459 providing a :class:`~celery.events.state.Worker` instance.
460
461 This doesn't necessarily mean the worker is actually offline, so use a time
462 out mechanism if the default heartbeat timeout isn't sufficient.
463
464 .. _extending-consumer-pool:
465
466 .. attribute:: pool
467
468 The current process/eventlet/gevent/thread pool.
469 See :class:`celery.concurrency.base.BasePool`.
470
471 .. _extending-consumer-timer:
472
473 .. attribute:: timer
474
475 :class:`Timer <celery.utils.timer2.Schedule` used to schedule functions.
476
477 .. _extending-consumer-heart:
478
479 .. attribute:: heart
480
481 Responsible for sending worker event heartbeats
482 (:class:`~celery.worker.heartbeat.Heart`).
483
484 Your consumer bootstep must require the `Heart` bootstep to use this:
485
486 .. code-block:: python
487
488 class Step(bootsteps.StartStopStep):
489 requires = {'celery.worker.consumer.heart:Heart'}
490
491 .. _extending-consumer-task_consumer:
492
493 .. attribute:: task_consumer
494
495 The :class:`kombu.Consumer` object used to consume task messages.
496
497 Your consumer bootstep must require the `Tasks` bootstep to use this:
498
499 .. code-block:: python
500
501 class Step(bootsteps.StartStopStep):
502 requires = {'celery.worker.consumer.tasks:Tasks'}
503
504 .. _extending-consumer-strategies:
505
506 .. attribute:: strategies
507
508 Every registered task type has an entry in this mapping,
509 where the value is used to execute an incoming message of this task type
510 (the task execution strategy). This mapping is generated by the Tasks
511 bootstep when the consumer starts:
512
513 .. code-block:: python
514
515 for name, task in app.tasks.items():
516 strategies[name] = task.start_strategy(app, consumer)
517 task.__trace__ = celery.app.trace.build_tracer(
518 name, task, loader, hostname
519 )
520
521 Your consumer bootstep must require the `Tasks` bootstep to use this:
522
523 .. code-block:: python
524
525 class Step(bootsteps.StartStopStep):
526 requires = {'celery.worker.consumer.tasks:Tasks'}
527
528 .. _extending-consumer-task_buckets:
529
530 .. attribute:: task_buckets
531
532 A :class:`~collections.defaultdict` used to look-up the rate limit for
533 a task by type.
534 Entries in this dict may be None (for no limit) or a
535 :class:`~kombu.utils.limits.TokenBucket` instance implementing
536 ``consume(tokens)`` and ``expected_time(tokens)``.
537
538 TokenBucket implements the `token bucket algorithm`_, but any algorithm
539 may be used as long as it conforms to the same interface and defines the
540 two methods above.
541
542 .. _`token bucket algorithm`: https://en.wikipedia.org/wiki/Token_bucket
543
544 .. _extending_consumer-qos:
545
546 .. attribute:: qos
547
548 The :class:`~kombu.common.QoS` object can be used to change the
549 task channels current prefetch_count value:
550
551 .. code-block:: python
552
553 # increment at next cycle
554 consumer.qos.increment_eventually(1)
555 # decrement at next cycle
556 consumer.qos.decrement_eventually(1)
557 consumer.qos.set(10)
558
559
560 Methods
561 -------
562
563 .. method:: consumer.reset_rate_limits()
564
565 Updates the ``task_buckets`` mapping for all registered task types.
566
567 .. method:: consumer.bucket_for_task(type, Bucket=TokenBucket)
568
569 Creates rate limit bucket for a task using its ``task.rate_limit``
570 attribute.
571
572 .. method:: consumer.add_task_queue(name, exchange=None, exchange_type=None,
573 routing_key=None, \*\*options):
574
575 Adds new queue to consume from. This will persist on connection restart.
576
577 .. method:: consumer.cancel_task_queue(name)
578
579 Stop consuming from queue by name. This will persist on connection
580 restart.
581
582 .. method:: apply_eta_task(request)
583
584 Schedule ETA task to execute based on the ``request.eta`` attribute.
585 (:class:`~celery.worker.request.Request`)
586
587
588
589 .. _extending-bootsteps:
590
591 Installing Bootsteps
592 ====================
593
594 ``app.steps['worker']`` and ``app.steps['consumer']`` can be modified
595 to add new bootsteps:
596
597 .. code-block:: pycon
598
599 >>> app = Celery()
600 >>> app.steps['worker'].add(MyWorkerStep) # < add class, don't instantiate
601 >>> app.steps['consumer'].add(MyConsumerStep)
602
603 >>> app.steps['consumer'].update([StepA, StepB])
604
605 >>> app.steps['consumer']
606 {step:proj.StepB{()}, step:proj.MyConsumerStep{()}, step:proj.StepA{()}
607
608 The order of steps isn't important here as the order is decided by the
609 resulting dependency graph (``Step.requires``).
610
611 To illustrate how you can install bootsteps and how they work, this is an example step that
612 prints some useless debugging information.
613 It can be added both as a worker and consumer bootstep:
614
615
616 .. code-block:: python
617
618 from celery import Celery
619 from celery import bootsteps
620
621 class InfoStep(bootsteps.Step):
622
623 def __init__(self, parent, **kwargs):
624 # here we can prepare the Worker/Consumer object
625 # in any way we want, set attribute defaults, and so on.
626 print('{0!r} is in init'.format(parent))
627
628 def start(self, parent):
629 # our step is started together with all other Worker/Consumer
630 # bootsteps.
631 print('{0!r} is starting'.format(parent))
632
633 def stop(self, parent):
634 # the Consumer calls stop every time the consumer is
635 # restarted (i.e., connection is lost) and also at shutdown.
636 # The Worker will call stop at shutdown only.
637 print('{0!r} is stopping'.format(parent))
638
639 def shutdown(self, parent):
640 # shutdown is called by the Consumer at shutdown, it's not
641 # called by Worker.
642 print('{0!r} is shutting down'.format(parent))
643
644 app = Celery(broker='amqp://')
645 app.steps['worker'].add(InfoStep)
646 app.steps['consumer'].add(InfoStep)
647
648 Starting the worker with this step installed will give us the following
649 logs:
650
651 .. code-block:: text
652
653 <Worker: [email protected] (initializing)> is in init
654 <Consumer: [email protected] (initializing)> is in init
655 [2013-05-29 16:18:20,544: WARNING/MainProcess]
656 <Worker: [email protected] (running)> is starting
657 [2013-05-29 16:18:21,577: WARNING/MainProcess]
658 <Consumer: [email protected] (running)> is starting
659 <Consumer: [email protected] (closing)> is stopping
660 <Worker: [email protected] (closing)> is stopping
661 <Consumer: [email protected] (terminating)> is shutting down
662
663 The ``print`` statements will be redirected to the logging subsystem after
664 the worker has been initialized, so the "is starting" lines are time-stamped.
665 You may notice that this does no longer happen at shutdown, this is because
666 the ``stop`` and ``shutdown`` methods are called inside a *signal handler*,
667 and it's not safe to use logging inside such a handler.
668 Logging with the Python logging module isn't :term:`reentrant`:
669 meaning you cannot interrupt the function then
670 call it again later. It's important that the ``stop`` and ``shutdown`` methods
671 you write is also :term:`reentrant`.
672
673 Starting the worker with :option:`--loglevel=debug <celery worker --loglevel>`
674 will show us more information about the boot process:
675
676 .. code-block:: text
677
678 [2013-05-29 16:18:20,509: DEBUG/MainProcess] | Worker: Preparing bootsteps.
679 [2013-05-29 16:18:20,511: DEBUG/MainProcess] | Worker: Building graph...
680 <celery.apps.worker.Worker object at 0x101ad8410> is in init
681 [2013-05-29 16:18:20,511: DEBUG/MainProcess] | Worker: New boot order:
682 {Hub, Pool, Timer, StateDB, Autoscaler, InfoStep, Beat, Consumer}
683 [2013-05-29 16:18:20,514: DEBUG/MainProcess] | Consumer: Preparing bootsteps.
684 [2013-05-29 16:18:20,514: DEBUG/MainProcess] | Consumer: Building graph...
685 <celery.worker.consumer.Consumer object at 0x101c2d8d0> is in init
686 [2013-05-29 16:18:20,515: DEBUG/MainProcess] | Consumer: New boot order:
687 {Connection, Mingle, Events, Gossip, InfoStep, Agent,
688 Heart, Control, Tasks, event loop}
689 [2013-05-29 16:18:20,522: DEBUG/MainProcess] | Worker: Starting Hub
690 [2013-05-29 16:18:20,522: DEBUG/MainProcess] ^-- substep ok
691 [2013-05-29 16:18:20,522: DEBUG/MainProcess] | Worker: Starting Pool
692 [2013-05-29 16:18:20,542: DEBUG/MainProcess] ^-- substep ok
693 [2013-05-29 16:18:20,543: DEBUG/MainProcess] | Worker: Starting InfoStep
694 [2013-05-29 16:18:20,544: WARNING/MainProcess]
695 <celery.apps.worker.Worker object at 0x101ad8410> is starting
696 [2013-05-29 16:18:20,544: DEBUG/MainProcess] ^-- substep ok
697 [2013-05-29 16:18:20,544: DEBUG/MainProcess] | Worker: Starting Consumer
698 [2013-05-29 16:18:20,544: DEBUG/MainProcess] | Consumer: Starting Connection
699 [2013-05-29 16:18:20,559: INFO/MainProcess] Connected to amqp://[email protected]:5672//
700 [2013-05-29 16:18:20,560: DEBUG/MainProcess] ^-- substep ok
701 [2013-05-29 16:18:20,560: DEBUG/MainProcess] | Consumer: Starting Mingle
702 [2013-05-29 16:18:20,560: INFO/MainProcess] mingle: searching for neighbors
703 [2013-05-29 16:18:21,570: INFO/MainProcess] mingle: no one here
704 [2013-05-29 16:18:21,570: DEBUG/MainProcess] ^-- substep ok
705 [2013-05-29 16:18:21,571: DEBUG/MainProcess] | Consumer: Starting Events
706 [2013-05-29 16:18:21,572: DEBUG/MainProcess] ^-- substep ok
707 [2013-05-29 16:18:21,572: DEBUG/MainProcess] | Consumer: Starting Gossip
708 [2013-05-29 16:18:21,577: DEBUG/MainProcess] ^-- substep ok
709 [2013-05-29 16:18:21,577: DEBUG/MainProcess] | Consumer: Starting InfoStep
710 [2013-05-29 16:18:21,577: WARNING/MainProcess]
711 <celery.worker.consumer.Consumer object at 0x101c2d8d0> is starting
712 [2013-05-29 16:18:21,578: DEBUG/MainProcess] ^-- substep ok
713 [2013-05-29 16:18:21,578: DEBUG/MainProcess] | Consumer: Starting Heart
714 [2013-05-29 16:18:21,579: DEBUG/MainProcess] ^-- substep ok
715 [2013-05-29 16:18:21,579: DEBUG/MainProcess] | Consumer: Starting Control
716 [2013-05-29 16:18:21,583: DEBUG/MainProcess] ^-- substep ok
717 [2013-05-29 16:18:21,583: DEBUG/MainProcess] | Consumer: Starting Tasks
718 [2013-05-29 16:18:21,606: DEBUG/MainProcess] basic.qos: prefetch_count->80
719 [2013-05-29 16:18:21,606: DEBUG/MainProcess] ^-- substep ok
720 [2013-05-29 16:18:21,606: DEBUG/MainProcess] | Consumer: Starting event loop
721 [2013-05-29 16:18:21,608: WARNING/MainProcess] [email protected] ready.
722
723
724 .. _extending-programs:
725
726 Command-line programs
727 =====================
728
729 .. _extending-commandoptions:
730
731 Adding new command-line options
732 -------------------------------
733
734 .. _extending-command-options:
735
736 Command-specific options
737 ~~~~~~~~~~~~~~~~~~~~~~~~
738
739 You can add additional command-line options to the ``worker``, ``beat``, and
740 ``events`` commands by modifying the :attr:`~@user_options` attribute of the
741 application instance.
742
743 Celery commands uses the :mod:`click` module to parse command-line
744 arguments, and so to add custom arguments you need to add :class:`click.Option` instances
745 to the relevant set.
746
747 Example adding a custom option to the :program:`celery worker` command:
748
749 .. code-block:: python
750
751 from celery import Celery
752 from click import Option
753
754 app = Celery(broker='amqp://')
755
756 app.user_options['worker'].add(Option(('--enable-my-option',),
757 is_flag=True,
758 help='Enable custom option.'))
759
760
761 All bootsteps will now receive this argument as a keyword argument to
762 ``Bootstep.__init__``:
763
764 .. code-block:: python
765
766 from celery import bootsteps
767
768 class MyBootstep(bootsteps.Step):
769
770 def __init__(self, parent, enable_my_option=False, **options):
771 super().__init__(parent, **options)
772 if enable_my_option:
773 party()
774
775 app.steps['worker'].add(MyBootstep)
776
777 .. _extending-preload_options:
778
779 Preload options
780 ~~~~~~~~~~~~~~~
781
782 The :program:`celery` umbrella command supports the concept of 'preload
783 options'. These are special options passed to all sub-commands.
784
785 You can add new preload options, for example to specify a configuration
786 template:
787
788 .. code-block:: python
789
790 from celery import Celery
791 from celery import signals
792 from click import Option
793
794 app = Celery()
795
796 app.user_options['preload'].add(Option(('-Z', '--template'),
797 default='default',
798 help='Configuration template to use.'))
799
800 @signals.user_preload_options.connect
801 def on_preload_parsed(options, **kwargs):
802 use_template(options['template'])
803
804 .. _extending-subcommands:
805
806 Adding new :program:`celery` sub-commands
807 -----------------------------------------
808
809 New commands can be added to the :program:`celery` umbrella command by using
810 `setuptools entry-points`_.
811
812 .. _`setuptools entry-points`:
813 http://reinout.vanrees.org/weblog/2010/01/06/zest-releaser-entry-points.html
814
815
816 Entry-points is special meta-data that can be added to your packages ``setup.py`` program,
817 and then after installation, read from the system using the :mod:`importlib` module.
818
819 Celery recognizes ``celery.commands`` entry-points to install additional
820 sub-commands, where the value of the entry-point must point to a valid click
821 command.
822
823 This is how the :pypi:`Flower` monitoring extension may add the :program:`celery flower` command,
824 by adding an entry-point in :file:`setup.py`:
825
826 .. code-block:: python
827
828 setup(
829 name='flower',
830 entry_points={
831 'celery.commands': [
832 'flower = flower.command:flower',
833 ],
834 }
835 )
836
837 The command definition is in two parts separated by the equal sign, where the
838 first part is the name of the sub-command (flower), then the second part is
839 the fully qualified symbol path to the function that implements the command:
840
841 .. code-block:: text
842
843 flower.command:flower
844
845 The module path and the name of the attribute should be separated by colon
846 as above.
847
848
849 In the module :file:`flower/command.py`, the command function may be defined
850 as the following:
851
852 .. code-block:: python
853
854 import click
855
856 @click.command()
857 @click.option('--port', default=8888, type=int, help='Webserver port')
858 @click.option('--debug', is_flag=True)
859 def flower(port, debug):
860 print('Running our command')
861
862
863 Worker API
864 ==========
865
866
867 :class:`~kombu.asynchronous.Hub` - The workers async event loop
868 ---------------------------------------------------------------
869 :supported transports: amqp, redis
870
871 .. versionadded:: 3.0
872
873 The worker uses asynchronous I/O when the amqp or redis broker transports are
874 used. The eventual goal is for all transports to use the event-loop, but that
875 will take some time so other transports still use a threading-based solution.
876
877 .. method:: hub.add(fd, callback, flags)
878
879
880 .. method:: hub.add_reader(fd, callback, \*args)
881
882 Add callback to be called when ``fd`` is readable.
883
884 The callback will stay registered until explicitly removed using
885 :meth:`hub.remove(fd) <hub.remove>`, or the file descriptor is
886 automatically discarded because it's no longer valid.
887
888 Note that only one callback can be registered for any given
889 file descriptor at a time, so calling ``add`` a second time will remove
890 any callback that was previously registered for that file descriptor.
891
892 A file descriptor is any file-like object that supports the ``fileno``
893 method, or it can be the file descriptor number (int).
894
895 .. method:: hub.add_writer(fd, callback, \*args)
896
897 Add callback to be called when ``fd`` is writable.
898 See also notes for :meth:`hub.add_reader` above.
899
900 .. method:: hub.remove(fd)
901
902 Remove all callbacks for file descriptor ``fd`` from the loop.
903
904 Timer - Scheduling events
905 -------------------------
906
907 .. method:: timer.call_after(secs, callback, args=(), kwargs=(),
908 priority=0)
909
910 .. method:: timer.call_repeatedly(secs, callback, args=(), kwargs=(),
911 priority=0)
912
913 .. method:: timer.call_at(eta, callback, args=(), kwargs=(),
914 priority=0)