workers.rst 21 KB

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