workers.rst 20 KB

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