Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

worker.py 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. # -*- coding: utf-8 -*-
  2. """
  3. The :program:`celery worker` command (previously known as ``celeryd``)
  4. .. program:: celery worker
  5. .. seealso::
  6. See :ref:`preload-options`.
  7. .. cmdoption:: -c, --concurrency
  8. Number of child processes processing the queue. The default
  9. is the number of CPUs available on your system.
  10. .. cmdoption:: -P, --pool
  11. Pool implementation:
  12. prefork (default), eventlet, gevent, solo or threads.
  13. .. cmdoption:: -f, --logfile
  14. Path to log file. If no logfile is specified, `stderr` is used.
  15. .. cmdoption:: -l, --loglevel
  16. Logging level, choose between `DEBUG`, `INFO`, `WARNING`,
  17. `ERROR`, `CRITICAL`, or `FATAL`.
  18. .. cmdoption:: -n, --hostname
  19. Set custom hostname, e.g. 'w1.%h'. Expands: %h (hostname),
  20. %n (name) and %d, (domain).
  21. .. cmdoption:: -B, --beat
  22. Also run the `celery beat` periodic task scheduler. Please note that
  23. there must only be one instance of this service.
  24. .. cmdoption:: -Q, --queues
  25. List of queues to enable for this worker, separated by comma.
  26. By default all configured queues are enabled.
  27. Example: `-Q video,image`
  28. .. cmdoption:: -I, --include
  29. Comma separated list of additional modules to import.
  30. Example: -I foo.tasks,bar.tasks
  31. .. cmdoption:: -s, --schedule
  32. Path to the schedule database if running with the `-B` option.
  33. Defaults to `celerybeat-schedule`. The extension ".db" may be
  34. appended to the filename.
  35. .. cmdoption:: -O
  36. Apply optimization profile. Supported: default, fair
  37. .. cmdoption:: --scheduler
  38. Scheduler class to use. Default is celery.beat.PersistentScheduler
  39. .. cmdoption:: -S, --statedb
  40. Path to the state database. The extension '.db' may
  41. be appended to the filename. Default: {default}
  42. .. cmdoption:: -E, --events
  43. Send events that can be captured by monitors like :program:`celery events`,
  44. `celerymon`, and others.
  45. .. cmdoption:: --without-gossip
  46. Do not subscribe to other workers events.
  47. .. cmdoption:: --without-mingle
  48. Do not synchronize with other workers at startup.
  49. .. cmdoption:: --without-heartbeat
  50. Do not send event heartbeats.
  51. .. cmdoption:: --heartbeat-interval
  52. Interval in seconds at which to send worker heartbeat
  53. .. cmdoption:: --purge
  54. Purges all waiting tasks before the daemon is started.
  55. **WARNING**: This is unrecoverable, and the tasks will be
  56. deleted from the messaging server.
  57. .. cmdoption:: --time-limit
  58. Enables a hard time limit (in seconds int/float) for tasks.
  59. .. cmdoption:: --soft-time-limit
  60. Enables a soft time limit (in seconds int/float) for tasks.
  61. .. cmdoption:: --maxtasksperchild
  62. Maximum number of tasks a pool worker can execute before it's
  63. terminated and replaced by a new worker.
  64. .. cmdoption:: --pidfile
  65. Optional file used to store the workers pid.
  66. The worker will not start if this file already exists
  67. and the pid is still alive.
  68. .. cmdoption:: --autoscale
  69. Enable autoscaling by providing
  70. max_concurrency, min_concurrency. Example::
  71. --autoscale=10,3
  72. (always keep 3 processes, but grow to 10 if necessary)
  73. .. cmdoption:: --autoreload
  74. Enable autoreloading.
  75. .. cmdoption:: --no-execv
  76. Don't do execv after multiprocessing child fork.
  77. """
  78. from __future__ import absolute_import, unicode_literals
  79. import sys
  80. from celery import concurrency
  81. from celery.bin.base import Command, Option, daemon_options
  82. from celery.bin.celeryd_detach import detached_celeryd
  83. from celery.five import string_t
  84. from celery.platforms import maybe_drop_privileges
  85. from celery.utils import default_nodename
  86. from celery.utils.log import LOG_LEVELS, mlevel
  87. __all__ = ['worker', 'main']
  88. __MODULE_DOC__ = __doc__
  89. class worker(Command):
  90. """Start worker instance.
  91. Examples::
  92. celery worker --app=proj -l info
  93. celery worker -A proj -l info -Q hipri,lopri
  94. celery worker -A proj --concurrency=4
  95. celery worker -A proj --concurrency=1000 -P eventlet
  96. celery worker --autoscale=10,0
  97. """
  98. doc = __MODULE_DOC__ # parse help from this too
  99. namespace = 'celeryd'
  100. enable_config_from_cmdline = True
  101. supports_args = False
  102. def run_from_argv(self, prog_name, argv=None, command=None):
  103. command = sys.argv[0] if command is None else command
  104. argv = sys.argv[1:] if argv is None else argv
  105. # parse options before detaching so errors can be handled.
  106. options, args = self.prepare_args(
  107. *self.parse_options(prog_name, argv, command))
  108. self.maybe_detach([command] + argv)
  109. return self(*args, **options)
  110. def maybe_detach(self, argv, dopts=['-D', '--detach']):
  111. if any(arg in argv for arg in dopts):
  112. argv = [v for v in argv if v not in dopts]
  113. # will never return
  114. detached_celeryd(self.app).execute_from_commandline(argv)
  115. raise SystemExit(0)
  116. def run(self, hostname=None, pool_cls=None, app=None, uid=None, gid=None,
  117. loglevel=None, logfile=None, pidfile=None, state_db=None,
  118. **kwargs):
  119. maybe_drop_privileges(uid=uid, gid=gid)
  120. # Pools like eventlet/gevent needs to patch libs as early
  121. # as possible.
  122. pool_cls = (concurrency.get_implementation(pool_cls) or
  123. self.app.conf.CELERYD_POOL)
  124. if self.app.IS_WINDOWS and kwargs.get('beat'):
  125. self.die('-B option does not work on Windows. '
  126. 'Please run celery beat as a separate service.')
  127. hostname = self.host_format(default_nodename(hostname))
  128. if loglevel:
  129. try:
  130. loglevel = mlevel(loglevel)
  131. except KeyError: # pragma: no cover
  132. self.die('Unknown level {0!r}. Please use one of {1}.'.format(
  133. loglevel, '|'.join(
  134. l for l in LOG_LEVELS if isinstance(l, string_t))))
  135. return self.app.Worker(
  136. hostname=hostname, pool_cls=pool_cls, loglevel=loglevel,
  137. logfile=logfile, # node format handled by celery.app.log.setup
  138. pidfile=self.node_format(pidfile, hostname),
  139. state_db=self.node_format(state_db, hostname), **kwargs
  140. ).start()
  141. def with_pool_option(self, argv):
  142. # this command support custom pools
  143. # that may have to be loaded as early as possible.
  144. return (['-P'], ['--pool'])
  145. def get_options(self):
  146. conf = self.app.conf
  147. return (
  148. Option('-c', '--concurrency',
  149. default=conf.CELERYD_CONCURRENCY, type='int'),
  150. Option('-P', '--pool', default=conf.CELERYD_POOL, dest='pool_cls'),
  151. Option('--purge', '--discard', default=False, action='store_true'),
  152. Option('-l', '--loglevel', default=conf.CELERYD_LOG_LEVEL),
  153. Option('-n', '--hostname'),
  154. Option('-B', '--beat', action='store_true'),
  155. Option('-s', '--schedule', dest='schedule_filename',
  156. default=conf.CELERYBEAT_SCHEDULE_FILENAME),
  157. Option('--scheduler', dest='scheduler_cls'),
  158. Option('-S', '--statedb',
  159. default=conf.CELERYD_STATE_DB, dest='state_db'),
  160. Option('-E', '--events', default=conf.CELERY_SEND_EVENTS,
  161. action='store_true', dest='send_events'),
  162. Option('--time-limit', type='float', dest='task_time_limit',
  163. default=conf.CELERYD_TASK_TIME_LIMIT),
  164. Option('--soft-time-limit', dest='task_soft_time_limit',
  165. default=conf.CELERYD_TASK_SOFT_TIME_LIMIT, type='float'),
  166. Option('--maxtasksperchild', dest='max_tasks_per_child',
  167. default=conf.CELERYD_MAX_TASKS_PER_CHILD, type='int'),
  168. Option('--queues', '-Q', default=[]),
  169. Option('--exclude-queues', '-X', default=[]),
  170. Option('--include', '-I', default=[]),
  171. Option('--autoscale'),
  172. Option('--autoreload', action='store_true'),
  173. Option('--no-execv', action='store_true', default=False),
  174. Option('--without-gossip', action='store_true', default=False),
  175. Option('--without-mingle', action='store_true', default=False),
  176. Option('--without-heartbeat', action='store_true', default=False),
  177. Option('--heartbeat-interval', type='int'),
  178. Option('-O', dest='optimization'),
  179. Option('-D', '--detach', action='store_true'),
  180. ) + daemon_options() + tuple(self.app.user_options['worker'])
  181. def main(app=None):
  182. # Fix for setuptools generated scripts, so that it will
  183. # work with multiprocessing fork emulation.
  184. # (see multiprocessing.forking.get_preparation_data())
  185. if __name__ != '__main__': # pragma: no cover
  186. sys.modules['__main__'] = sys.modules[__name__]
  187. from billiard import freeze_support
  188. freeze_support()
  189. worker(app=app).execute_from_commandline()
  190. if __name__ == '__main__': # pragma: no cover
  191. main()