celery.py 26 KB

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