celery.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. # -*- coding: utf-8 -*-
  2. """
  3. The :program:`celery` umbrella command.
  4. .. program:: celery
  5. """
  6. from __future__ import absolute_import, unicode_literals
  7. import anyjson
  8. import os
  9. import sys
  10. from functools import partial
  11. from importlib import import_module
  12. from celery.five import string_t, values
  13. from celery.platforms import EX_OK, EX_FAILURE, EX_UNAVAILABLE, EX_USAGE
  14. from celery.utils import term
  15. from celery.utils import text
  16. from celery.utils.timeutils import maybe_iso8601
  17. # Cannot use relative imports here due to a Windows issue (#1111).
  18. from celery.bin.base import Command, Option, Extensions
  19. # Import commands from other modules
  20. from celery.bin.amqp import amqp
  21. from celery.bin.beat import beat
  22. from celery.bin.events import events
  23. from celery.bin.graph import graph
  24. from celery.bin.worker import worker
  25. __all__ = ['CeleryCommand', 'main']
  26. HELP = """
  27. ---- -- - - ---- Commands- -------------- --- ------------
  28. {commands}
  29. ---- -- - - --------- -- - -------------- --- ------------
  30. Type '{prog_name} <command> --help' for help using a specific command.
  31. """
  32. MIGRATE_PROGRESS_FMT = """\
  33. Migrating task {state.count}/{state.strtotal}: \
  34. {body[task]}[{body[id]}]\
  35. """
  36. DEBUG = os.environ.get('C_DEBUG', False)
  37. command_classes = [
  38. ('Main', ['worker', 'events', 'beat', 'shell', 'multi', 'amqp'], 'green'),
  39. ('Remote Control', ['status', 'inspect', 'control'], 'blue'),
  40. ('Utils', ['purge', 'list', 'migrate', 'call', 'result', 'report'], None),
  41. ]
  42. if DEBUG: # pragma: no cover
  43. command_classes.append(
  44. ('Debug', ['graph'], 'red'),
  45. )
  46. def determine_exit_status(ret):
  47. if isinstance(ret, int):
  48. return ret
  49. return EX_OK if ret else EX_FAILURE
  50. def main(argv=None):
  51. # Fix for setuptools generated scripts, so that it will
  52. # work with multiprocessing fork emulation.
  53. # (see multiprocessing.forking.get_preparation_data())
  54. try:
  55. if __name__ != '__main__': # pragma: no cover
  56. sys.modules['__main__'] = sys.modules[__name__]
  57. cmd = CeleryCommand()
  58. cmd.maybe_patch_concurrency()
  59. from billiard import freeze_support
  60. freeze_support()
  61. cmd.execute_from_commandline(argv)
  62. except KeyboardInterrupt:
  63. pass
  64. class multi(Command):
  65. """Start multiple worker instances."""
  66. respects_app_option = False
  67. def get_options(self):
  68. return ()
  69. def run_from_argv(self, prog_name, argv, command=None):
  70. from celery.bin.multi import MultiTool
  71. return MultiTool().execute_from_commandline(
  72. [command] + argv, prog_name,
  73. )
  74. class list_(Command):
  75. """Get info from broker.
  76. Examples::
  77. celery list bindings
  78. NOTE: For RabbitMQ the management plugin is required.
  79. """
  80. args = '[bindings]'
  81. def list_bindings(self, management):
  82. try:
  83. bindings = management.get_bindings()
  84. except NotImplementedError:
  85. raise self.Error('Your transport cannot list bindings.')
  86. fmt = lambda q, e, r: self.out('{0:<28} {1:<28} {2}'.format(q, e, r))
  87. fmt('Queue', 'Exchange', 'Routing Key')
  88. fmt('-' * 16, '-' * 16, '-' * 16)
  89. for b in bindings:
  90. fmt(b['destination'], b['source'], b['routing_key'])
  91. def run(self, what=None, *_, **kw):
  92. topics = {'bindings': self.list_bindings}
  93. available = ', '.join(topics)
  94. if not what:
  95. raise self.UsageError(
  96. 'You must specify one of {0}'.format(available))
  97. if what not in topics:
  98. raise self.UsageError(
  99. 'unknown topic {0!r} (choose one of: {1})'.format(
  100. what, available))
  101. with self.app.connection() as conn:
  102. self.app.amqp.TaskConsumer(conn).declare()
  103. topics[what](conn.manager)
  104. class call(Command):
  105. """Call a task by name.
  106. Examples::
  107. celery call tasks.add --args='[2, 2]'
  108. celery call tasks.add --args='[2, 2]' --countdown=10
  109. """
  110. args = '<task_name>'
  111. option_list = Command.option_list + (
  112. Option('--args', '-a', help='positional arguments (json).'),
  113. Option('--kwargs', '-k', help='keyword arguments (json).'),
  114. Option('--eta', help='scheduled time (ISO-8601).'),
  115. Option('--countdown', type='float',
  116. help='eta in seconds from now (float/int).'),
  117. Option('--expires', help='expiry time (ISO-8601/float/int).'),
  118. Option('--serializer', default='json', help='defaults to json.'),
  119. Option('--queue', help='custom queue name.'),
  120. Option('--exchange', help='custom exchange name.'),
  121. Option('--routing-key', help='custom routing key.'),
  122. )
  123. def run(self, name, *_, **kw):
  124. # Positional args.
  125. args = kw.get('args') or ()
  126. if isinstance(args, string_t):
  127. args = anyjson.loads(args)
  128. # Keyword args.
  129. kwargs = kw.get('kwargs') or {}
  130. if isinstance(kwargs, string_t):
  131. kwargs = anyjson.loads(kwargs)
  132. # Expires can be int/float.
  133. expires = kw.get('expires') or None
  134. try:
  135. expires = float(expires)
  136. except (TypeError, ValueError):
  137. # or a string describing an ISO 8601 datetime.
  138. try:
  139. expires = maybe_iso8601(expires)
  140. except (TypeError, ValueError):
  141. raise
  142. res = self.app.send_task(name, args=args, kwargs=kwargs,
  143. countdown=kw.get('countdown'),
  144. serializer=kw.get('serializer'),
  145. queue=kw.get('queue'),
  146. exchange=kw.get('exchange'),
  147. routing_key=kw.get('routing_key'),
  148. eta=maybe_iso8601(kw.get('eta')),
  149. expires=expires)
  150. self.out(res.id)
  151. class purge(Command):
  152. """Erase all messages from all known task queues.
  153. WARNING: There is no undo operation for this command.
  154. """
  155. fmt_purged = 'Purged {mnum} {messages} from {qnum} known task {queues}.'
  156. fmt_empty = 'No messages purged from {qnum} {queues}'
  157. def run(self, *args, **kwargs):
  158. queues = len(self.app.amqp.queues)
  159. messages = self.app.control.purge()
  160. fmt = self.fmt_purged if messages else self.fmt_empty
  161. self.out(fmt.format(
  162. mnum=messages, qnum=queues,
  163. messages=text.pluralize(messages, 'message'),
  164. queues=text.pluralize(queues, 'queue')))
  165. class result(Command):
  166. """Gives the return value for a given task id.
  167. Examples::
  168. celery result 8f511516-e2f5-4da4-9d2f-0fb83a86e500
  169. celery result 8f511516-e2f5-4da4-9d2f-0fb83a86e500 -t tasks.add
  170. celery result 8f511516-e2f5-4da4-9d2f-0fb83a86e500 --traceback
  171. """
  172. args = '<task_id>'
  173. option_list = Command.option_list + (
  174. Option('--task', '-t', help='name of task (if custom backend)'),
  175. Option('--traceback', action='store_true',
  176. help='show traceback instead'),
  177. )
  178. def run(self, task_id, *args, **kwargs):
  179. result_cls = self.app.AsyncResult
  180. task = kwargs.get('task')
  181. traceback = kwargs.get('traceback', False)
  182. if task:
  183. result_cls = self.app.tasks[task].AsyncResult
  184. result = result_cls(task_id)
  185. if traceback:
  186. value = result.traceback
  187. else:
  188. value = result.get()
  189. self.out(self.pretty(value)[1])
  190. class _RemoteControl(Command):
  191. name = None
  192. choices = None
  193. leaf = False
  194. option_list = Command.option_list + (
  195. Option('--timeout', '-t', type='float',
  196. help='Timeout in seconds (float) waiting for reply'),
  197. Option('--destination', '-d',
  198. help='Comma separated list of destination node names.'))
  199. def __init__(self, *args, **kwargs):
  200. self.show_body = kwargs.pop('show_body', True)
  201. self.show_reply = kwargs.pop('show_reply', True)
  202. super(_RemoteControl, self).__init__(*args, **kwargs)
  203. @classmethod
  204. def get_command_info(self, command,
  205. indent=0, prefix='', color=None, help=False):
  206. if help:
  207. help = '|' + text.indent(self.choices[command][1], indent + 4)
  208. else:
  209. help = None
  210. try:
  211. # see if it uses args.
  212. meth = getattr(self, command)
  213. return text.join([
  214. '|' + text.indent('{0}{1} {2}'.format(
  215. prefix, color(command), meth.__doc__), indent),
  216. help,
  217. ])
  218. except AttributeError:
  219. return text.join([
  220. '|' + text.indent(prefix + str(color(command)), indent), help,
  221. ])
  222. @classmethod
  223. def list_commands(self, indent=0, prefix='', color=None, help=False):
  224. color = color if color else lambda x: x
  225. prefix = prefix + ' ' if prefix else ''
  226. return '\n'.join(self.get_command_info(c, indent, prefix, color, help)
  227. for c in sorted(self.choices))
  228. @property
  229. def epilog(self):
  230. return '\n'.join([
  231. '[Commands]',
  232. self.list_commands(indent=4, help=True)
  233. ])
  234. def usage(self, command):
  235. return '%prog {0} [options] {1} <command> [arg1 .. argN]'.format(
  236. command, self.args)
  237. def call(self, *args, **kwargs):
  238. raise NotImplementedError('get_obj')
  239. def run(self, *args, **kwargs):
  240. if not args:
  241. raise self.UsageError(
  242. 'Missing {0.name} method. See --help'.format(self))
  243. return self.do_call_method(args, **kwargs)
  244. def do_call_method(self, args, **kwargs):
  245. method = args[0]
  246. if method == 'help':
  247. raise self.Error("Did you mean '{0.name} --help'?".format(self))
  248. if method not in self.choices:
  249. raise self.UsageError(
  250. 'Unknown {0.name} method {1}'.format(self, method))
  251. if self.app.connection().transport.driver_type == 'sql':
  252. raise self.Error('Broadcast not supported by SQL broker transport')
  253. destination = kwargs.get('destination')
  254. timeout = kwargs.get('timeout') or self.choices[method][0]
  255. if destination and isinstance(destination, string_t):
  256. destination = [dest.strip() for dest in destination.split(',')]
  257. try:
  258. handler = getattr(self, method)
  259. except AttributeError:
  260. handler = self.call
  261. replies = handler(method, *args[1:], timeout=timeout,
  262. destination=destination,
  263. callback=self.say_remote_command_reply)
  264. if not replies:
  265. raise self.Error('No nodes replied within time constraint.',
  266. status=EX_UNAVAILABLE)
  267. return replies
  268. class inspect(_RemoteControl):
  269. """Inspect the worker at runtime.
  270. Availability: RabbitMQ (amqp), Redis, and MongoDB transports.
  271. Examples::
  272. celery inspect active --timeout=5
  273. celery inspect scheduled -d worker1@example.com
  274. celery inspect revoked -d w1@e.com,w2@e.com
  275. """
  276. name = 'inspect'
  277. choices = {
  278. 'active': (1.0, 'dump active tasks (being processed)'),
  279. 'active_queues': (1.0, 'dump queues being consumed from'),
  280. 'scheduled': (1.0, 'dump scheduled tasks (eta/countdown/retry)'),
  281. 'reserved': (1.0, 'dump reserved tasks (waiting to be processed)'),
  282. 'stats': (1.0, 'dump worker statistics'),
  283. 'revoked': (1.0, 'dump of revoked task ids'),
  284. 'registered': (1.0, 'dump of registered tasks'),
  285. 'ping': (0.2, 'ping worker(s)'),
  286. 'clock': (1.0, 'get value of logical clock'),
  287. 'conf': (1.0, 'dump worker configuration'),
  288. 'report': (1.0, 'get bugreport info'),
  289. 'memsample': (1.0, 'sample memory (requires psutil)'),
  290. 'memdump': (1.0, 'dump memory samples (requires psutil)'),
  291. 'objgraph': (60.0, 'create object graph (requires objgraph)'),
  292. }
  293. def call(self, method, *args, **options):
  294. i = self.app.control.inspect(**options)
  295. return getattr(i, method)(*args)
  296. def objgraph(self, type_='Request', *args, **kwargs):
  297. return self.call('objgraph', type_)
  298. class control(_RemoteControl):
  299. """Workers remote control.
  300. Availability: RabbitMQ (amqp), Redis, and MongoDB transports.
  301. Examples::
  302. celery control enable_events --timeout=5
  303. celery control -d worker1@example.com enable_events
  304. celery control -d w1.e.com,w2.e.com enable_events
  305. celery control -d w1.e.com add_consumer queue_name
  306. celery control -d w1.e.com cancel_consumer queue_name
  307. celery control -d w1.e.com add_consumer queue exchange direct rkey
  308. """
  309. name = 'control'
  310. choices = {
  311. 'enable_events': (1.0, 'tell worker(s) to enable events'),
  312. 'disable_events': (1.0, 'tell worker(s) to disable events'),
  313. 'add_consumer': (1.0, 'tell worker(s) to start consuming a queue'),
  314. 'cancel_consumer': (1.0, 'tell worker(s) to stop consuming a queue'),
  315. 'rate_limit': (
  316. 1.0, 'tell worker(s) to modify the rate limit for a task type'),
  317. 'time_limit': (
  318. 1.0, 'tell worker(s) to modify the time limit for a task type.'),
  319. 'autoscale': (1.0, 'change autoscale settings'),
  320. 'pool_grow': (1.0, 'start more pool processes'),
  321. 'pool_shrink': (1.0, 'use less pool processes'),
  322. }
  323. def call(self, method, *args, **options):
  324. return getattr(self.app.control, method)(*args, reply=True, **options)
  325. def pool_grow(self, method, n=1, **kwargs):
  326. """[N=1]"""
  327. return self.call(method, int(n), **kwargs)
  328. def pool_shrink(self, method, n=1, **kwargs):
  329. """[N=1]"""
  330. return self.call(method, int(n), **kwargs)
  331. def autoscale(self, method, max=None, min=None, **kwargs):
  332. """[max] [min]"""
  333. return self.call(method, int(max), int(min), **kwargs)
  334. def rate_limit(self, method, task_name, rate_limit, **kwargs):
  335. """<task_name> <rate_limit> (e.g. 5/s | 5/m | 5/h)>"""
  336. return self.call(method, task_name, rate_limit, reply=True, **kwargs)
  337. def time_limit(self, method, task_name, soft, hard=None, **kwargs):
  338. """<task_name> <soft_secs> [hard_secs]"""
  339. return self.call(method, task_name,
  340. float(soft), float(hard), reply=True, **kwargs)
  341. def add_consumer(self, method, queue, exchange=None,
  342. exchange_type='direct', routing_key=None, **kwargs):
  343. """<queue> [exchange [type [routing_key]]]"""
  344. return self.call(method, queue, exchange,
  345. exchange_type, routing_key, reply=True, **kwargs)
  346. def cancel_consumer(self, method, queue, **kwargs):
  347. """<queue>"""
  348. return self.call(method, queue, reply=True, **kwargs)
  349. class status(Command):
  350. """Show list of workers that are online."""
  351. option_list = inspect.option_list
  352. def run(self, *args, **kwargs):
  353. I = inspect(
  354. app=self.app,
  355. no_color=kwargs.get('no_color', False),
  356. stdout=self.stdout, stderr=self.stderr,
  357. show_reply=False, show_body=False, quiet=True,
  358. )
  359. replies = I.run('ping', **kwargs)
  360. if not replies:
  361. raise self.Error('No nodes replied within time constraint',
  362. status=EX_UNAVAILABLE)
  363. nodecount = len(replies)
  364. if not kwargs.get('quiet', False):
  365. self.out('\n{0} {1} online.'.format(
  366. nodecount, text.pluralize(nodecount, 'node')))
  367. class migrate(Command):
  368. """Migrate tasks from one broker to another.
  369. Examples::
  370. celery migrate redis://localhost amqp://guest@localhost//
  371. celery migrate django:// redis://localhost
  372. NOTE: This command is experimental, make sure you have
  373. a backup of the tasks before you continue.
  374. """
  375. args = '<source_url> <dest_url>'
  376. option_list = Command.option_list + (
  377. Option('--limit', '-n', type='int',
  378. help='Number of tasks to consume (int)'),
  379. Option('--timeout', '-t', type='float', default=1.0,
  380. help='Timeout in seconds (float) waiting for tasks'),
  381. Option('--ack-messages', '-a', action='store_true',
  382. help='Ack messages from source broker.'),
  383. Option('--tasks', '-T',
  384. help='List of task names to filter on.'),
  385. Option('--queues', '-Q',
  386. help='List of queues to migrate.'),
  387. Option('--forever', '-F', action='store_true',
  388. help='Continually migrate tasks until killed.'),
  389. )
  390. progress_fmt = MIGRATE_PROGRESS_FMT
  391. def on_migrate_task(self, state, body, message):
  392. self.out(self.progress_fmt.format(state=state, body=body))
  393. def run(self, source, destination, **kwargs):
  394. from kombu import Connection
  395. from celery.contrib.migrate import migrate_tasks
  396. migrate_tasks(Connection(source),
  397. Connection(destination),
  398. callback=self.on_migrate_task,
  399. **kwargs)
  400. class shell(Command): # pragma: no cover
  401. """Start shell session with convenient access to celery symbols.
  402. The following symbols will be added to the main globals:
  403. - celery: the current application.
  404. - chord, group, chain, chunks,
  405. xmap, xstarmap subtask, Task
  406. - all registered tasks.
  407. Example Session:
  408. .. code-block:: bash
  409. $ celery shell
  410. >>> celery
  411. <Celery default:0x1012d9fd0>
  412. >>> add
  413. <@task: tasks.add>
  414. >>> add.delay(2, 2)
  415. <AsyncResult: 537b48c7-d6d3-427a-a24a-d1b4414035be>
  416. """
  417. option_list = Command.option_list + (
  418. Option('--ipython', '-I',
  419. action='store_true', dest='force_ipython',
  420. help='force iPython.'),
  421. Option('--bpython', '-B',
  422. action='store_true', dest='force_bpython',
  423. help='force bpython.'),
  424. Option('--python', '-P',
  425. action='store_true', dest='force_python',
  426. help='force default Python shell.'),
  427. Option('--without-tasks', '-T', action='store_true',
  428. help="don't add tasks to locals."),
  429. Option('--eventlet', action='store_true',
  430. help='use eventlet.'),
  431. Option('--gevent', action='store_true', help='use gevent.'),
  432. )
  433. def run(self, force_ipython=False, force_bpython=False,
  434. force_python=False, without_tasks=False, eventlet=False,
  435. gevent=False, **kwargs):
  436. sys.path.insert(0, os.getcwd())
  437. if eventlet:
  438. import_module('celery.concurrency.eventlet')
  439. if gevent:
  440. import_module('celery.concurrency.gevent')
  441. import celery
  442. import celery.task.base
  443. self.app.loader.import_default_modules()
  444. self.locals = {'celery': self.app,
  445. 'Task': celery.Task,
  446. 'chord': celery.chord,
  447. 'group': celery.group,
  448. 'chain': celery.chain,
  449. 'chunks': celery.chunks,
  450. 'xmap': celery.xmap,
  451. 'xstarmap': celery.xstarmap,
  452. 'subtask': celery.subtask}
  453. if not without_tasks:
  454. self.locals.update(dict(
  455. (task.__name__, task) for task in values(self.app.tasks)
  456. if not task.name.startswith('celery.')),
  457. )
  458. if force_python:
  459. return self.invoke_fallback_shell()
  460. elif force_bpython:
  461. return self.invoke_bpython_shell()
  462. elif force_ipython:
  463. return self.invoke_ipython_shell()
  464. return self.invoke_default_shell()
  465. def invoke_default_shell(self):
  466. try:
  467. import IPython # noqa
  468. except ImportError:
  469. try:
  470. import bpython # noqa
  471. except ImportError:
  472. return self.invoke_fallback_shell()
  473. else:
  474. return self.invoke_bpython_shell()
  475. else:
  476. return self.invoke_ipython_shell()
  477. def invoke_fallback_shell(self):
  478. import code
  479. try:
  480. import readline
  481. except ImportError:
  482. pass
  483. else:
  484. import rlcompleter
  485. readline.set_completer(
  486. rlcompleter.Completer(self.locals).complete)
  487. readline.parse_and_bind('tab:complete')
  488. code.interact(local=self.locals)
  489. def invoke_ipython_shell(self):
  490. try:
  491. from IPython.frontend.terminal import embed
  492. embed.TerminalInteractiveShell(user_ns=self.locals).mainloop()
  493. except ImportError: # ipython < 0.11
  494. from IPython.Shell import IPShell
  495. IPShell(argv=[], user_ns=self.locals).mainloop()
  496. def invoke_bpython_shell(self):
  497. import bpython
  498. bpython.embed(self.locals)
  499. class help(Command):
  500. """Show help screen and exit."""
  501. def usage(self, command):
  502. return '%prog <command> [options] {0.args}'.format(self)
  503. def run(self, *args, **kwargs):
  504. self.parser.print_help()
  505. self.out(HELP.format(prog_name=self.prog_name,
  506. commands=CeleryCommand.list_commands()))
  507. return EX_USAGE
  508. class report(Command):
  509. """Shows information useful to include in bugreports."""
  510. def run(self, *args, **kwargs):
  511. self.out(self.app.bugreport())
  512. return EX_OK
  513. class CeleryCommand(Command):
  514. namespace = 'celery'
  515. ext_fmt = '{self.namespace}.commands'
  516. commands = {
  517. 'amqp': amqp,
  518. 'beat': beat,
  519. 'call': call,
  520. 'control': control,
  521. 'events': events,
  522. 'graph': graph,
  523. 'help': help,
  524. 'inspect': inspect,
  525. 'list': list_,
  526. 'migrate': migrate,
  527. 'multi': multi,
  528. 'purge': purge,
  529. 'report': report,
  530. 'result': result,
  531. 'shell': shell,
  532. 'status': status,
  533. 'worker': worker,
  534. }
  535. enable_config_from_cmdline = True
  536. prog_name = 'celery'
  537. @classmethod
  538. def register_command(cls, fun, name=None):
  539. cls.commands[name or fun.__name__] = fun
  540. return fun
  541. def execute(self, command, argv=None):
  542. try:
  543. cls = self.commands[command]
  544. except KeyError:
  545. cls, argv = self.commands['help'], ['help']
  546. cls = self.commands.get(command) or self.commands['help']
  547. try:
  548. return cls(
  549. app=self.app, on_error=self.on_error,
  550. on_usage_error=partial(self.on_usage_error, command=command),
  551. ).run_from_argv(self.prog_name, argv[1:], command=argv[0])
  552. except self.UsageError as exc:
  553. self.on_usage_error(exc)
  554. return exc.status
  555. except self.Error as exc:
  556. self.on_error(exc)
  557. return exc.status
  558. def on_usage_error(self, exc, command=None):
  559. if command:
  560. helps = '{self.prog_name} {command} --help'
  561. else:
  562. helps = '{self.prog_name} --help'
  563. self.error(self.colored.magenta("Error: {0}".format(exc)))
  564. self.error("""Please try '{0}'""".format(helps.format(
  565. self=self, command=command,
  566. )))
  567. def remove_options_at_beginning(self, argv, index=0):
  568. if argv:
  569. while index < len(argv):
  570. value = argv[index]
  571. if value.startswith('--'):
  572. pass
  573. elif value.startswith('-'):
  574. index += 1
  575. else:
  576. return argv[index:]
  577. index += 1
  578. return []
  579. def prepare_prog_name(self, name):
  580. if name == '__main__.py':
  581. return sys.modules['__main__'].__file__
  582. return name
  583. def handle_argv(self, prog_name, argv):
  584. self.prog_name = self.prepare_prog_name(prog_name)
  585. argv = self.remove_options_at_beginning(argv)
  586. _, argv = self.prepare_args(None, argv)
  587. try:
  588. command = argv[0]
  589. except IndexError:
  590. command, argv = 'help', ['help']
  591. return self.execute(command, argv)
  592. def execute_from_commandline(self, argv=None):
  593. argv = sys.argv if argv is None else argv
  594. if 'multi' in argv[1:3]: # Issue 1008
  595. self.respects_app_option = False
  596. try:
  597. sys.exit(determine_exit_status(
  598. super(CeleryCommand, self).execute_from_commandline(argv)))
  599. except KeyboardInterrupt:
  600. sys.exit(EX_FAILURE)
  601. @classmethod
  602. def get_command_info(self, command, indent=0, color=None):
  603. colored = term.colored().names[color] if color else lambda x: x
  604. obj = self.commands[command]
  605. cmd = 'celery {0}'.format(colored(command))
  606. if obj.leaf:
  607. return '|' + text.indent(cmd, indent)
  608. return text.join([
  609. ' ',
  610. '|' + text.indent('{0} --help'.format(cmd), indent),
  611. obj.list_commands(indent, 'celery {0}'.format(command), colored),
  612. ])
  613. @classmethod
  614. def list_commands(self, indent=0):
  615. white = term.colored().white
  616. ret = []
  617. for cls, commands, color in command_classes:
  618. ret.extend([
  619. text.indent('+ {0}: '.format(white(cls)), indent),
  620. '\n'.join(self.get_command_info(command, indent + 4, color)
  621. for command in commands),
  622. ''
  623. ])
  624. return '\n'.join(ret).strip()
  625. def with_pool_option(self, argv):
  626. if len(argv) > 1 and 'worker' in argv[0:3]:
  627. # this command supports custom pools
  628. # that may have to be loaded as early as possible.
  629. return (['-P'], ['--pool'])
  630. def on_concurrency_setup(self):
  631. self.load_extension_commands()
  632. def load_extension_commands(self):
  633. names = Extensions(self.ext_fmt.format(self=self),
  634. self.register_command).load()
  635. if names:
  636. command_classes.append(('Extensions', names, 'magenta'))
  637. def command(*args, **kwargs):
  638. """Deprecated: Use classmethod :meth:`CeleryCommand.register_command`
  639. instead."""
  640. _register = CeleryCommand.register_command
  641. return _register(args[0]) if args else _register
  642. if __name__ == '__main__': # pragma: no cover
  643. main()