workers.rst 19 KB

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