multi.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. # -*- coding: utf-8 -*-
  2. """Start multiple worker instances from the command-line.
  3. .. program:: celery multi
  4. Examples
  5. ========
  6. .. code-block:: console
  7. $ # Single worker with explicit name and events enabled.
  8. $ celery multi start Leslie -E
  9. $ # Pidfiles and logfiles are stored in the current directory
  10. $ # by default. Use --pidfile and --logfile argument to change
  11. $ # this. The abbreviation %n will be expanded to the current
  12. $ # node name.
  13. $ celery multi start Leslie -E --pidfile=/var/run/celery/%n.pid
  14. --logfile=/var/log/celery/%n%I.log
  15. $ # You need to add the same arguments when you restart,
  16. $ # as these aren't persisted anywhere.
  17. $ celery multi restart Leslie -E --pidfile=/var/run/celery/%n.pid
  18. --logfile=/var/run/celery/%n%I.log
  19. $ # To stop the node, you need to specify the same pidfile.
  20. $ celery multi stop Leslie --pidfile=/var/run/celery/%n.pid
  21. $ # 3 workers, with 3 processes each
  22. $ celery multi start 3 -c 3
  23. celery worker -n celery1@myhost -c 3
  24. celery worker -n celery2@myhost -c 3
  25. celery worker -n celery3@myhost -c 3
  26. $ # start 3 named workers
  27. $ celery multi start image video data -c 3
  28. celery worker -n image@myhost -c 3
  29. celery worker -n video@myhost -c 3
  30. celery worker -n data@myhost -c 3
  31. $ # specify custom hostname
  32. $ celery multi start 2 --hostname=worker.example.com -c 3
  33. celery worker -n celery1@worker.example.com -c 3
  34. celery worker -n celery2@worker.example.com -c 3
  35. $ # specify fully qualified nodenames
  36. $ celery multi start foo@worker.example.com bar@worker.example.com -c 3
  37. $ # fully qualified nodenames but using the current hostname
  38. $ celery multi start foo@%h bar@%h
  39. $ # Advanced example starting 10 workers in the background:
  40. $ # * Three of the workers processes the images and video queue
  41. $ # * Two of the workers processes the data queue with loglevel DEBUG
  42. $ # * the rest processes the default' queue.
  43. $ celery multi start 10 -l INFO -Q:1-3 images,video -Q:4,5 data
  44. -Q default -L:4,5 DEBUG
  45. $ # You can show the commands necessary to start the workers with
  46. $ # the 'show' command:
  47. $ celery multi show 10 -l INFO -Q:1-3 images,video -Q:4,5 data
  48. -Q default -L:4,5 DEBUG
  49. $ # Additional options are added to each celery worker' comamnd,
  50. $ # but you can also modify the options for ranges of, or specific workers
  51. $ # 3 workers: Two with 3 processes, and one with 10 processes.
  52. $ celery multi start 3 -c 3 -c:1 10
  53. celery worker -n celery1@myhost -c 10
  54. celery worker -n celery2@myhost -c 3
  55. celery worker -n celery3@myhost -c 3
  56. $ # can also specify options for named workers
  57. $ celery multi start image video data -c 3 -c:image 10
  58. celery worker -n image@myhost -c 10
  59. celery worker -n video@myhost -c 3
  60. celery worker -n data@myhost -c 3
  61. $ # ranges and lists of workers in options is also allowed:
  62. $ # (-c:1-3 can also be written as -c:1,2,3)
  63. $ celery multi start 5 -c 3 -c:1-3 10
  64. celery worker -n celery1@myhost -c 10
  65. celery worker -n celery2@myhost -c 10
  66. celery worker -n celery3@myhost -c 10
  67. celery worker -n celery4@myhost -c 3
  68. celery worker -n celery5@myhost -c 3
  69. $ # lists also works with named workers
  70. $ celery multi start foo bar baz xuzzy -c 3 -c:foo,bar,baz 10
  71. celery worker -n foo@myhost -c 10
  72. celery worker -n bar@myhost -c 10
  73. celery worker -n baz@myhost -c 10
  74. celery worker -n xuzzy@myhost -c 3
  75. """
  76. from __future__ import absolute_import, print_function, unicode_literals
  77. import os
  78. import sys
  79. from functools import wraps
  80. from kombu.utils.objects import cached_property
  81. from celery import VERSION_BANNER
  82. from celery.apps.multi import Cluster
  83. from celery.platforms import EX_FAILURE, EX_OK
  84. from celery.utils import term
  85. from celery.utils.text import pluralize
  86. __all__ = ['MultiTool']
  87. USAGE = """\
  88. usage: {prog_name} start <node1 node2 nodeN|range> [worker options]
  89. {prog_name} stop <n1 n2 nN|range> [-SIG (default: -TERM)]
  90. {prog_name} restart <n1 n2 nN|range> [-SIG] [worker options]
  91. {prog_name} kill <n1 n2 nN|range>
  92. {prog_name} show <n1 n2 nN|range> [worker options]
  93. {prog_name} get hostname <n1 n2 nN|range> [-qv] [worker options]
  94. {prog_name} names <n1 n2 nN|range>
  95. {prog_name} expand template <n1 n2 nN|range>
  96. {prog_name} help
  97. additional options (must appear after command name):
  98. * --nosplash: Don't display program info.
  99. * --quiet: Don't show as much output.
  100. * --verbose: Show more output.
  101. * --no-color: Don't display colors.
  102. """
  103. def main():
  104. sys.exit(MultiTool().execute_from_commandline(sys.argv))
  105. def splash(fun):
  106. @wraps(fun)
  107. def _inner(self, *args, **kwargs):
  108. self.splash()
  109. return fun(self, *args, **kwargs)
  110. return _inner
  111. class TermLogger(object):
  112. splash_text = 'celery multi v{version}'
  113. splash_context = {'version': VERSION_BANNER}
  114. #: Final exit code.
  115. retcode = 0
  116. def setup_terminal(self, stdout, stderr,
  117. nosplash=False, quiet=False, verbose=False,
  118. no_color=False, **kwargs):
  119. self.stdout = stdout or sys.stdout
  120. self.stderr = stderr or sys.stderr
  121. self.nosplash = nosplash
  122. self.quiet = quiet
  123. self.verbose = verbose
  124. self.no_color = no_color
  125. def ok(self, m, newline=True, file=None):
  126. self.say(m, newline=newline, file=file)
  127. return EX_OK
  128. def say(self, m, newline=True, file=None):
  129. print(m, file=file or self.stdout, end='\n' if newline else '')
  130. def carp(self, m, newline=True, file=None):
  131. return self.say(m, newline, file or self.stderr)
  132. def error(self, msg=None):
  133. if msg:
  134. self.carp(msg)
  135. self.usage()
  136. return EX_FAILURE
  137. def info(self, msg, newline=True):
  138. if self.verbose:
  139. self.note(msg, newline=newline)
  140. def note(self, msg, newline=True):
  141. if not self.quiet:
  142. self.say(str(msg), newline=newline)
  143. @splash
  144. def usage(self):
  145. self.say(USAGE.format(prog_name=self.prog_name))
  146. def splash(self):
  147. if not self.nosplash:
  148. self.note(self.colored.cyan(
  149. self.splash_text.format(**self.splash_context)))
  150. @cached_property
  151. def colored(self):
  152. return term.colored(enabled=not self.no_color)
  153. class MultiTool(TermLogger):
  154. reserved_options = [
  155. ('--nosplash', 'nosplash'),
  156. ('--quiet', 'quiet'),
  157. ('-q', 'quiet'),
  158. ('--verbose', 'verbose'),
  159. ('--no-color', 'no_color'),
  160. ]
  161. def __init__(self, env=None, cmd=None,
  162. fh=None, stdout=None, stderr=None, **kwargs):
  163. """fh is an old alias to stdout."""
  164. self.env = env
  165. self.cmd = cmd
  166. self.setup_terminal(stdout or fh, stderr, **kwargs)
  167. self.fh = self.stdout
  168. self.prog_name = 'celery multi'
  169. self.commands = {
  170. 'start': self.start,
  171. 'show': self.show,
  172. 'stop': self.stop,
  173. 'stopwait': self.stopwait,
  174. 'stop_verify': self.stopwait, # compat alias
  175. 'restart': self.restart,
  176. 'kill': self.kill,
  177. 'names': self.names,
  178. 'expand': self.expand,
  179. 'get': self.get,
  180. 'help': self.help,
  181. }
  182. def execute_from_commandline(self, argv, cmd=None):
  183. # Reserve the --nosplash|--quiet|-q/--verbose options.
  184. argv = self._handle_reserved_options(argv)
  185. self.cmd = cmd if cmd is not None else self.cmd
  186. self.prog_name = os.path.basename(argv.pop(0))
  187. if not self.validate_arguments(argv):
  188. return self.error()
  189. return self.call_command(argv[0], argv[1:])
  190. def validate_arguments(self, argv):
  191. return argv and argv[0][0] != '-'
  192. def call_command(self, command, argv):
  193. try:
  194. return self.commands[command](*argv) or EX_OK
  195. except KeyError:
  196. return self.error('Invalid command: {0}'.format(command))
  197. def _handle_reserved_options(self, argv):
  198. argv = list(argv) # don't modify callers argv.
  199. for arg, attr in self.reserved_options:
  200. if arg in argv:
  201. setattr(self, attr, bool(argv.pop(argv.index(arg))))
  202. return argv
  203. @splash
  204. def start(self, *argv):
  205. self.note('> Starting nodes...')
  206. return int(any(self.Cluster(argv).start()))
  207. @splash
  208. def stop(self, *argv, **kwargs):
  209. return self.Cluster(argv).stop(**kwargs)
  210. @splash
  211. def stopwait(self, *argv, **kwargs):
  212. return self.Cluster(argv).stopwait(**kwargs)
  213. stop_verify = stopwait # compat
  214. @splash
  215. def restart(self, *argv, **kwargs):
  216. return int(any(self.Cluster(argv).restart(**kwargs)))
  217. def names(self, *argv):
  218. self.say('\n'.join(n.name for n in self.Cluster(argv)))
  219. def get(self, wanted, *argv):
  220. try:
  221. node = self.Cluster(argv).find(wanted)
  222. except KeyError:
  223. return EX_FAILURE
  224. else:
  225. return self.ok(' '.join(node.argv))
  226. def show(self, *argv):
  227. return self.ok('\n'.join(
  228. ' '.join(node.argv_with_executable)
  229. for node in self.Cluster(argv)
  230. ))
  231. @splash
  232. def kill(self, *argv):
  233. return self.Cluster(argv).kill()
  234. def expand(self, template, *argv):
  235. return self.ok('\n'.join(
  236. node.expander(template)
  237. for node in self.Cluster(argv)
  238. ))
  239. def help(self, *argv):
  240. self.say(__doc__)
  241. def Cluster(self, argv, cmd=None):
  242. return Cluster(
  243. argv, cmd if cmd is not None else self.cmd,
  244. env=self.env,
  245. on_stopping_preamble=self.on_stopping_preamble,
  246. on_send_signal=self.on_send_signal,
  247. on_still_waiting_for=self.on_still_waiting_for,
  248. on_still_waiting_progress=self.on_still_waiting_progress,
  249. on_still_waiting_end=self.on_still_waiting_end,
  250. on_node_start=self.on_node_start,
  251. on_node_restart=self.on_node_restart,
  252. on_node_shutdown_ok=self.on_node_shutdown_ok,
  253. on_node_status=self.on_node_status,
  254. on_node_signal_dead=self.on_node_signal_dead,
  255. on_node_signal=self.on_node_signal,
  256. on_node_down=self.on_node_down,
  257. on_child_spawn=self.on_child_spawn,
  258. on_child_signalled=self.on_child_signalled,
  259. on_child_failure=self.on_child_failure,
  260. )
  261. def on_stopping_preamble(self, nodes):
  262. self.note(self.colored.blue('> Stopping nodes...'))
  263. def on_send_signal(self, node, sig):
  264. self.note('\t> {0.name}: {1} -> {0.pid}'.format(node, sig))
  265. def on_still_waiting_for(self, nodes):
  266. num_left = len(nodes)
  267. if num_left:
  268. self.note(self.colored.blue(
  269. '> Waiting for {0} {1} -> {2}...'.format(
  270. num_left, pluralize(num_left, 'node'),
  271. ', '.join(str(node.pid) for node in nodes)),
  272. ), newline=False)
  273. def on_still_waiting_progress(self, nodes):
  274. self.note('.', newline=False)
  275. def on_still_waiting_end(self):
  276. self.note('')
  277. def on_node_signal_dead(self, node):
  278. self.note(
  279. 'Could not signal {0.name} ({0.pid}): No such process'.format(
  280. node))
  281. def on_node_start(self, node):
  282. self.note('\t> {0.name}: '.format(node), newline=False)
  283. def on_node_restart(self, node):
  284. self.note(self.colored.blue(
  285. '> Restarting node {0.name}: '.format(node)), newline=False)
  286. def on_node_down(self, node):
  287. self.note('> {0.name}: {1.DOWN}'.format(node, self))
  288. def on_node_shutdown_ok(self, node):
  289. self.note('\n\t> {0.name}: {1.OK}'.format(node, self))
  290. def on_node_status(self, node, retval):
  291. self.note(retval and self.FAILED or self.OK)
  292. def on_node_signal(self, node, sig):
  293. self.note('Sending {sig} to node {0.name} ({0.pid})'.format(
  294. node, sig=sig))
  295. def on_child_spawn(self, node, argstr, env):
  296. self.info(' {0}'.format(argstr))
  297. def on_child_signalled(self, node, signum):
  298. self.note('* Child was terminated by signal {0}'.format(signum))
  299. def on_child_failure(self, node, retcode):
  300. self.note('* Child terminated with exit code {0}'.format(retcode))
  301. @cached_property
  302. def OK(self):
  303. return str(self.colored.green('OK'))
  304. @cached_property
  305. def FAILED(self):
  306. return str(self.colored.red('FAILED'))
  307. @cached_property
  308. def DOWN(self):
  309. return str(self.colored.magenta('DOWN'))
  310. if __name__ == '__main__': # pragma: no cover
  311. main()