workers.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. .. _guide-workers:
  2. ===============
  3. Workers Guide
  4. ===============
  5. .. contents::
  6. :local:
  7. :depth: 1
  8. .. _worker-starting:
  9. Starting the worker
  10. ===================
  11. .. sidebar:: Daemonizing
  12. You probably want to use a daemonization tool to start
  13. in the background. See :ref:`daemonizing` for help
  14. detaching the worker using popular daemonization tools.
  15. You can start the worker in the foreground by executing the command::
  16. $ celery worker --app=app -l info
  17. For a full list of available command line options see
  18. :mod:`~celery.bin.celeryd`, or simply do::
  19. $ celery worker --help
  20. You can also start multiple workers on the same machine. If you do so
  21. be sure to give a unique name to each individual worker by specifying a
  22. host name with the :option:`--hostname|-n` argument::
  23. $ celery worker --loglevel=INFO --concurrency=10 -n worker1.example.com
  24. $ celery worker --loglevel=INFO --concurrency=10 -n worker2.example.com
  25. $ celery worker --loglevel=INFO --concurrency=10 -n worker3.example.com
  26. .. _worker-stopping:
  27. Stopping the worker
  28. ===================
  29. Shutdown should be accomplished using the :sig:`TERM` signal.
  30. When shutdown is initiated the worker will finish all currently executing
  31. tasks before it actually terminates, so if these tasks are important you should
  32. wait for it to finish before doing anything drastic (like sending the :sig:`KILL`
  33. signal).
  34. If the worker won't shutdown after considerate time, for example because
  35. of tasks stuck in an infinite-loop, you can use the :sig:`KILL` signal to
  36. force terminate the worker, but be aware that currently executing tasks will
  37. be lost (unless the tasks have the :attr:`~@Task.acks_late`
  38. option set).
  39. Also as processes can't override the :sig:`KILL` signal, the worker will
  40. not be able to reap its children, so make sure to do so manually. This
  41. command usually does the trick::
  42. $ ps auxww | grep 'celery worker' | awk '{print $2}' | xargs kill -9
  43. .. _worker-restarting:
  44. Restarting the worker
  45. =====================
  46. Other than stopping then starting the worker to restart, you can also
  47. restart the worker using the :sig:`HUP` signal::
  48. $ kill -HUP $pid
  49. The worker will then replace itself with a new instance using the same
  50. arguments as it was started with.
  51. .. note::
  52. Restarting by :sig:`HUP` only works if the worker is running
  53. in the background as a daemon (it does not have a controlling
  54. terminal).
  55. :sig:`HUP` is disabled on OS X because of a limitation on
  56. that platform.
  57. .. _worker-process-signals:
  58. Process Signals
  59. ===============
  60. The worker's main process overrides the following signals:
  61. +--------------+-------------------------------------------------+
  62. | :sig:`TERM` | Warm shutdown, wait for tasks to complete. |
  63. +--------------+-------------------------------------------------+
  64. | :sig:`QUIT` | Cold shutdown, terminate ASAP |
  65. +--------------+-------------------------------------------------+
  66. | :sig:`USR1` | Dump traceback for all active threads. |
  67. +--------------+-------------------------------------------------+
  68. | :sig:`USR2` | Remote debug, see :mod:`celery.contrib.rdb`. |
  69. +--------------+-------------------------------------------------+
  70. .. _worker-concurrency:
  71. Concurrency
  72. ===========
  73. By default multiprocessing is used to perform concurrent execution of tasks,
  74. but you can also use :ref:`Eventlet <concurrency-eventlet>`. The number
  75. of worker processes/threads can be changed using the :option:`--concurrency`
  76. argument and defaults to the number of CPUs available on the machine.
  77. .. admonition:: Number of processes (multiprocessing)
  78. More pool processes are usually better, but there's a cut-off point where
  79. adding more pool processes affects performance in negative ways.
  80. There is even some evidence to support that having multiple worker
  81. instances running, may perform better than having a single worker.
  82. For example 3 workers with 10 pool processes each. You need to experiment
  83. to find the numbers that works best for you, as this varies based on
  84. application, work load, task run times and other factors.
  85. .. _worker-remote-control:
  86. Remote control
  87. ==============
  88. .. versionadded:: 2.0
  89. .. sidebar:: The ``celery`` command
  90. The :program:`celery` program is used to execute remote control
  91. commands from the command line. It supports all of the commands
  92. listed below. See :ref:`monitoring-celeryctl` for more information.
  93. pool support: *processes, eventlet, gevent*, blocking:*threads/solo* (see note)
  94. broker support: *amqp, redis, mongodb*
  95. Workers have the ability to be remote controlled using a high-priority
  96. broadcast message queue. The commands can be directed to all, or a specific
  97. list of workers.
  98. Commands can also have replies. The client can then wait for and collect
  99. those replies. Since there's no central authority to know how many
  100. workers are available in the cluster, there is also no way to estimate
  101. how many workers may send a reply, so the client has a configurable
  102. timeout — the deadline in seconds for replies to arrive in. This timeout
  103. defaults to one second. If the worker doesn't reply within the deadline
  104. it doesn't necessarily mean the worker didn't reply, or worse is dead, but
  105. may simply be caused by network latency or the worker being slow at processing
  106. commands, so adjust the timeout accordingly.
  107. In addition to timeouts, the client can specify the maximum number
  108. of replies to wait for. If a destination is specified, this limit is set
  109. to the number of destination hosts.
  110. .. note::
  111. The solo and threads pool supports remote control commands,
  112. but any task executing will block any waiting control command,
  113. so it is of limited use if the worker is very busy. In that
  114. case you must increase the timeout waitin for replies in the client.
  115. .. _worker-broadcast-fun:
  116. The :meth:`~@control.broadcast` function.
  117. ----------------------------------------------------
  118. This is the client function used to send commands to the workers.
  119. Some remote control commands also have higher-level interfaces using
  120. :meth:`~@control.broadcast` in the background, like
  121. :meth:`~@control.rate_limit` and :meth:`~@control.ping`.
  122. Sending the :control:`rate_limit` command and keyword arguments::
  123. >>> celery.control.broadcast("rate_limit",
  124. ... arguments={"task_name": "myapp.mytask",
  125. ... "rate_limit": "200/m"})
  126. This will send the command asynchronously, without waiting for a reply.
  127. To request a reply you have to use the `reply` argument::
  128. >>> celery.control.broadcast("rate_limit", {
  129. ... "task_name": "myapp.mytask", "rate_limit": "200/m"}, reply=True)
  130. [{'worker1.example.com': 'New rate limit set successfully'},
  131. {'worker2.example.com': 'New rate limit set successfully'},
  132. {'worker3.example.com': 'New rate limit set successfully'}]
  133. Using the `destination` argument you can specify a list of workers
  134. to receive the command::
  135. >>> celery.control.broadcast("rate_limit", {
  136. ... "task_name": "myapp.mytask",
  137. ... "rate_limit": "200/m"}, reply=True,
  138. ... destination=["worker1.example.com"])
  139. [{'worker1.example.com': 'New rate limit set successfully'}]
  140. Of course, using the higher-level interface to set rate limits is much
  141. more convenient, but there are commands that can only be requested
  142. using :meth:`~@control.broadcast`.
  143. .. control:: revoke
  144. Revoking tasks
  145. ==============
  146. pool support: all
  147. broker support: *amqp, redis, mongodb*
  148. All worker nodes keeps a memory of revoked task ids, either in-memory or
  149. persistent on disk (see :ref:`worker-persistent-revokes`).
  150. When a worker receives a revoke request it will skip executing
  151. the task, but it won't terminate an already executing task unless
  152. the `terminate` option is set.
  153. If `terminate` is set the worker child process processing the task
  154. will be terminated. The default signal sent is `TERM`, but you can
  155. specify this using the `signal` argument. Signal can be the uppercase name
  156. of any signal defined in the :mod:`signal` module in the Python Standard
  157. Library.
  158. Terminating a task also revokes it.
  159. **Example**
  160. ::
  161. >>> celery.control.revoke("d9078da5-9915-40a0-bfa1-392c7bde42ed")
  162. >>> celery.control.revoke("d9078da5-9915-40a0-bfa1-392c7bde42ed",
  163. ... terminate=True)
  164. >>> celery.control.revoke("d9078da5-9915-40a0-bfa1-392c7bde42ed",
  165. ... terminate=True, signal="SIGKILL")
  166. .. _worker-persistent-revokes:
  167. Persistent revokes
  168. ------------------
  169. Revoking tasks works by sending a broadcast message to all the workers,
  170. the workers then keep a list of revoked tasks in memory.
  171. If you want tasks to remain revoked after worker restart you need to
  172. specify a file for these to be stored in, either by using the `--statedb`
  173. argument to :program:`celery worker` or the :setting:`CELERYD_STATE_DB`
  174. setting.
  175. Note that remote control commands must be working for revokes to work.
  176. Remote control commands are only supported by the amqp, redis and mongodb
  177. transports at this point.
  178. .. _worker-time-limits:
  179. Time Limits
  180. ===========
  181. .. versionadded:: 2.0
  182. pool support: *processes*
  183. .. sidebar:: Soft, or hard?
  184. The time limit is set in two values, `soft` and `hard`.
  185. The soft time limit allows the task to catch an exception
  186. to clean up before it is killed: the hard timeout is not catchable
  187. and force terminates the task.
  188. A single task can potentially run forever, if you have lots of tasks
  189. waiting for some event that will never happen you will block the worker
  190. from processing new tasks indefinitely. The best way to defend against
  191. this scenario happening is enabling time limits.
  192. The time limit (`--time-limit`) is the maximum number of seconds a task
  193. may run before the process executing it is terminated and replaced by a
  194. new process. You can also enable a soft time limit (`--soft-time-limit`),
  195. this raises an exception the task can catch to clean up before the hard
  196. time limit kills it:
  197. .. code-block:: python
  198. from myapp import celery
  199. from celery.exceptions import SoftTimeLimitExceeded
  200. @celery.task()
  201. def mytask():
  202. try:
  203. do_work()
  204. except SoftTimeLimitExceeded:
  205. clean_up_in_a_hurry()
  206. Time limits can also be set using the :setting:`CELERYD_TASK_TIME_LIMIT` /
  207. :setting:`CELERYD_SOFT_TASK_TIME_LIMIT` settings.
  208. .. note::
  209. Time limits do not currently work on Windows and other
  210. platforms that do not support the ``SIGUSR1`` signal.
  211. Changing time limits at runtime
  212. -------------------------------
  213. .. versionadded:: 2.3
  214. broker support: *amqp, redis, mongodb*
  215. There is a remote control command that enables you to change both soft
  216. and hard time limits for a task — named ``time_limit``.
  217. Example changing the time limit for the ``tasks.crawl_the_web`` task
  218. to have a soft time limit of one minute, and a hard time limit of
  219. two minutes::
  220. >>> celery.control.time_limit("tasks.crawl_the_web",
  221. soft=60, hard=120, reply=True)
  222. [{'worker1.example.com': {'ok': 'time limits set successfully'}}]
  223. Only tasks that starts executing after the time limit change will be affected.
  224. .. _worker-rate-limits:
  225. Rate Limits
  226. ===========
  227. .. control:: rate_limit
  228. Changing rate-limits at runtime
  229. -------------------------------
  230. Example changing the rate limit for the `myapp.mytask` task to accept
  231. 200 tasks a minute on all servers::
  232. >>> celery.control.rate_limit("myapp.mytask", "200/m")
  233. Example changing the rate limit on a single host by specifying the
  234. destination host name::
  235. >>> celery.control.rate_limit("myapp.mytask", "200/m",
  236. ... destination=["worker1.example.com"])
  237. .. warning::
  238. This won't affect workers with the
  239. :setting:`CELERY_DISABLE_RATE_LIMITS` setting enabled.
  240. .. _worker-maxtasksperchild:
  241. Max tasks per child setting
  242. ===========================
  243. .. versionadded:: 2.0
  244. pool support: *processes*
  245. With this option you can configure the maximum number of tasks
  246. a worker can execute before it's replaced by a new process.
  247. This is useful if you have memory leaks you have no control over
  248. for example from closed source C extensions.
  249. The option can be set using the workers `--maxtasksperchild` argument
  250. or using the :setting:`CELERYD_MAX_TASKS_PER_CHILD` setting.
  251. .. _worker-autoscaling:
  252. Autoscaling
  253. ===========
  254. .. versionadded:: 2.2
  255. pool support: *processes*, *gevent*
  256. The *autoscaler* component is used to dynamically resize the pool
  257. based on load:
  258. - The autoscaler adds more pool processes when there is work to do,
  259. - and starts removing processes when the workload is low.
  260. It's enabled by the :option:`--autoscale` option, which needs two
  261. numbers: the maximum and minumum number of pool processes::
  262. --autoscale=AUTOSCALE
  263. Enable autoscaling by providing
  264. max_concurrency,min_concurrency. Example:
  265. --autoscale=10,3 (always keep 3 processes, but grow to
  266. 10 if necessary).
  267. You can also define your own rules for the autoscaler by subclassing
  268. :class:`~celery.worker.autoscaler.Autoscaler`.
  269. Some ideas for metrics include load average or the amount of memory available.
  270. You can specify a custom autoscaler with the :setting:`CELERYD_AUTOSCALER` setting.
  271. .. _worker-autoreloading:
  272. Autoreloading
  273. =============
  274. .. versionadded:: 2.5
  275. pool support: *processes, eventlet, gevent, threads, solo*
  276. Starting :program:`celery worker` with the :option:`--autoreload` option will
  277. enable the worker to watch for file system changes to all imported task
  278. modules imported (and also any non-task modules added to the
  279. :setting:`CELERY_IMPORTS` setting or the :option:`-I|--include` option).
  280. This is an experimental feature intended for use in development only,
  281. using auto-reload in production is discouraged as the behavior of reloading
  282. a module in Python is undefined, and may cause hard to diagnose bugs and
  283. crashes. Celery uses the same approach as the auto-reloader found in e.g.
  284. the Django ``runserver`` command.
  285. When auto-reload is enabled the worker starts an additional thread
  286. that watches for changes in the file system. New modules are imported,
  287. and already imported modules are reloaded whenever a change is detected,
  288. and if the processes pool is used the child processes will finish the work
  289. they are doing and exit, so that they can be replaced by fresh processes
  290. effectively reloading the code.
  291. File system notification backends are pluggable, and it comes with three
  292. implementations:
  293. * inotify (Linux)
  294. Used if the :mod:`pyinotify` library is installed.
  295. If you are running on Linux this is the recommended implementation,
  296. to install the :mod:`pyinotify` library you have to run the following
  297. command::
  298. $ pip install pyinotify
  299. * kqueue (OS X/BSD)
  300. * stat
  301. The fallback implementation simply polls the files using ``stat`` and is very
  302. expensive.
  303. You can force an implementation by setting the :envvar:`CELERYD_FSNOTIFY`
  304. environment variable::
  305. $ env CELERYD_FSNOTIFY=stat celery worker -l info --autoreload
  306. .. _worker-autoreload:
  307. .. control:: pool_restart
  308. Pool Restart Command
  309. --------------------
  310. .. versionadded:: 2.5
  311. The remote control command :control:`pool_restart` sends restart requests to
  312. the workers child processes. It is particularly useful for forcing
  313. the worker to import new modules, or for reloading already imported
  314. modules. This command does not interrupt executing tasks.
  315. Example
  316. ~~~~~~~
  317. Running the following command will result in the `foo` and `bar` modules
  318. being imported by the worker processes:
  319. .. code-block:: python
  320. >>> celery.control.broadcast("pool_restart",
  321. ... arguments={"modules": ["foo", "bar"]})
  322. Use the ``reload`` argument to reload modules it has already imported:
  323. .. code-block:: python
  324. >>> celery.control.broadcast("pool_restart",
  325. ... arguments={"modules": ["foo"],
  326. ... "reload": True})
  327. If you don't specify any modules then all known tasks modules will
  328. be imported/reloaded:
  329. .. code-block:: python
  330. >>> celery.control.broadcast("pool_restart", arguments={"reload": True})
  331. The ``modules`` argument is a list of modules to modify. ``reload``
  332. specifies whether to reload modules if they have previously been imported.
  333. By default ``reload`` is disabled. The `pool_restart` command uses the
  334. Python :func:`reload` function to reload modules, or you can provide
  335. your own custom reloader by passing the ``reloader`` argument.
  336. .. note::
  337. Module reloading comes with caveats that are documented in :func:`reload`.
  338. Please read this documentation and make sure your modules are suitable
  339. for reloading.
  340. .. seealso::
  341. - http://pyunit.sourceforge.net/notes/reloading.html
  342. - http://www.indelible.org/ink/python-reloading/
  343. - http://docs.python.org/library/functions.html#reload
  344. .. _worker-inspect:
  345. Inspecting workers
  346. ==================
  347. :class:`@control.inspect` lets you inspect running workers. It
  348. uses remote control commands under the hood.
  349. You can also use the ``celery`` command to inspect workers,
  350. and it supports the same commands as the :class:`@Celery.control` interface.
  351. .. code-block:: python
  352. # Inspect all nodes.
  353. >>> i = celery.control.inspect()
  354. # Specify multiple nodes to inspect.
  355. >>> i = celery.control.inspect(["worker1.example.com",
  356. "worker2.example.com"])
  357. # Specify a single node to inspect.
  358. >>> i = celery.control.inspect("worker1.example.com")
  359. .. _worker-inspect-registered-tasks:
  360. Dump of registered tasks
  361. ------------------------
  362. You can get a list of tasks registered in the worker using the
  363. :meth:`~@control.inspect.registered`::
  364. >>> i.registered()
  365. [{'worker1.example.com': ['tasks.add',
  366. 'tasks.sleeptask']}]
  367. .. _worker-inspect-active-tasks:
  368. Dump of currently executing tasks
  369. ---------------------------------
  370. You can get a list of active tasks using
  371. :meth:`~@control.inspect.active`::
  372. >>> i.active()
  373. [{'worker1.example.com':
  374. [{"name": "tasks.sleeptask",
  375. "id": "32666e9b-809c-41fa-8e93-5ae0c80afbbf",
  376. "args": "(8,)",
  377. "kwargs": "{}"}]}]
  378. .. _worker-inspect-eta-schedule:
  379. Dump of scheduled (ETA) tasks
  380. -----------------------------
  381. You can get a list of tasks waiting to be scheduled by using
  382. :meth:`~@control.inspect.scheduled`::
  383. >>> i.scheduled()
  384. [{'worker1.example.com':
  385. [{"eta": "2010-06-07 09:07:52", "priority": 0,
  386. "request": {
  387. "name": "tasks.sleeptask",
  388. "id": "1a7980ea-8b19-413e-91d2-0b74f3844c4d",
  389. "args": "[1]",
  390. "kwargs": "{}"}},
  391. {"eta": "2010-06-07 09:07:53", "priority": 0,
  392. "request": {
  393. "name": "tasks.sleeptask",
  394. "id": "49661b9a-aa22-4120-94b7-9ee8031d219d",
  395. "args": "[2]",
  396. "kwargs": "{}"}}]}]
  397. .. note::
  398. These are tasks with an eta/countdown argument, not periodic tasks.
  399. .. _worker-inspect-reserved:
  400. Dump of reserved tasks
  401. ----------------------
  402. Reserved tasks are tasks that has been received, but is still waiting to be
  403. executed.
  404. You can get a list of these using
  405. :meth:`~@control.inspect.reserved`::
  406. >>> i.reserved()
  407. [{'worker1.example.com':
  408. [{"name": "tasks.sleeptask",
  409. "id": "32666e9b-809c-41fa-8e93-5ae0c80afbbf",
  410. "args": "(8,)",
  411. "kwargs": "{}"}]}]
  412. Additional Commands
  413. ===================
  414. .. control:: shutdown
  415. Remote shutdown
  416. ---------------
  417. This command will gracefully shut down the worker remotely::
  418. >>> celery.control.broadcast("shutdown") # shutdown all workers
  419. >>> celery.control.broadcast("shutdown, destination="worker1.example.com")
  420. .. control:: ping
  421. Ping
  422. ----
  423. This command requests a ping from alive workers.
  424. The workers reply with the string 'pong', and that's just about it.
  425. It will use the default one second timeout for replies unless you specify
  426. a custom timeout::
  427. >>> celery.control.ping(timeout=0.5)
  428. [{'worker1.example.com': 'pong'},
  429. {'worker2.example.com': 'pong'},
  430. {'worker3.example.com': 'pong'}]
  431. :meth:`~@control.ping` also supports the `destination` argument,
  432. so you can specify which workers to ping::
  433. >>> ping(['worker2.example.com', 'worker3.example.com'])
  434. [{'worker2.example.com': 'pong'},
  435. {'worker3.example.com': 'pong'}]
  436. .. _worker-enable-events:
  437. .. control:: enable_events
  438. .. control:: disable_events
  439. Enable/disable events
  440. ---------------------
  441. You can enable/disable events by using the `enable_events`,
  442. `disable_events` commands. This is useful to temporarily monitor
  443. a worker using :program:`celery events`/:program:`celerymon`.
  444. .. code-block:: python
  445. >>> celery.control.enable_events()
  446. >>> celery.control.disable_events()
  447. .. _worker-custom-control-commands:
  448. Writing your own remote control commands
  449. ========================================
  450. Remote control commands are registered in the control panel and
  451. they take a single argument: the current
  452. :class:`~celery.worker.control.ControlDispatch` instance.
  453. From there you have access to the active
  454. :class:`~celery.worker.consumer.Consumer` if needed.
  455. Here's an example control command that restarts the broker connection:
  456. .. code-block:: python
  457. from celery.worker.control import Panel
  458. @Panel.register
  459. def reset_connection(panel):
  460. panel.logger.critical("Connection reset by remote control.")
  461. panel.consumer.reset_connection()
  462. return {"ok": "connection reset"}