workers.rst 22 KB

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