base.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. # -*- coding: utf-8 -*-
  2. """Base command-line interface."""
  3. from __future__ import absolute_import, print_function, unicode_literals
  4. import os
  5. import random
  6. import re
  7. import sys
  8. import warnings
  9. import json
  10. from collections import defaultdict
  11. from heapq import heappush
  12. from optparse import (
  13. OptionParser, OptionGroup, IndentedHelpFormatter, make_option as Option,
  14. )
  15. from pprint import pformat
  16. from celery import VERSION_BANNER, Celery, maybe_patch_concurrency
  17. from celery import signals
  18. from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning
  19. from celery.five import (
  20. getfullargspec, items, python_2_unicode_compatible, string, string_t,
  21. )
  22. from celery.platforms import EX_FAILURE, EX_OK, EX_USAGE
  23. from celery.utils import term
  24. from celery.utils import text
  25. from celery.utils.nodenames import node_format, host_format
  26. from celery.utils.imports import symbol_by_name, import_from_cwd
  27. try:
  28. input = raw_input
  29. except NameError: # pragma: no cover
  30. pass
  31. __all__ = [
  32. 'Error', 'UsageError', 'Extensions',
  33. 'HelpFormatter', 'Command', 'Option', 'daemon_options',
  34. ]
  35. # always enable DeprecationWarnings, so our users can see them.
  36. for warning in (CDeprecationWarning, CPendingDeprecationWarning):
  37. warnings.simplefilter('once', warning, 0)
  38. ARGV_DISABLED = """
  39. Unrecognized command-line arguments: {0}
  40. Try --help?
  41. """
  42. find_long_opt = re.compile(r'.+?(--.+?)(?:\s|,|$)')
  43. find_rst_ref = re.compile(r':\w+:`(.+?)`')
  44. find_rst_decl = re.compile(r'^\s*\.\. .+?::.+$')
  45. @python_2_unicode_compatible
  46. class Error(Exception):
  47. status = EX_FAILURE
  48. def __init__(self, reason, status=None):
  49. self.reason = reason
  50. self.status = status if status is not None else self.status
  51. super(Error, self).__init__(reason, status)
  52. def __str__(self):
  53. return self.reason
  54. class UsageError(Error):
  55. status = EX_USAGE
  56. class Extensions(object):
  57. def __init__(self, namespace, register):
  58. self.names = []
  59. self.namespace = namespace
  60. self.register = register
  61. def add(self, cls, name):
  62. heappush(self.names, name)
  63. self.register(cls, name=name)
  64. def load(self):
  65. try:
  66. from pkg_resources import iter_entry_points
  67. except ImportError: # pragma: no cover
  68. return
  69. for ep in iter_entry_points(self.namespace):
  70. sym = ':'.join([ep.module_name, ep.attrs[0]])
  71. try:
  72. cls = symbol_by_name(sym)
  73. except (ImportError, SyntaxError) as exc:
  74. warnings.warn(
  75. 'Cannot load extension {0!r}: {1!r}'.format(sym, exc))
  76. else:
  77. self.add(cls, ep.name)
  78. return self.names
  79. class HelpFormatter(IndentedHelpFormatter):
  80. def format_epilog(self, epilog):
  81. if epilog:
  82. return '\n{0}\n\n'.format(epilog)
  83. return ''
  84. def format_description(self, description):
  85. return text.ensure_newlines(
  86. text.fill_paragraphs(text.dedent(description), self.width))
  87. class Command(object):
  88. """Base class for command-line applications.
  89. Arguments:
  90. app (~@Celery): The app to use.
  91. get_app (Callable): Fucntion returning the current app
  92. when no app provided.
  93. """
  94. Error = Error
  95. UsageError = UsageError
  96. Parser = OptionParser
  97. #: Arg list used in help.
  98. args = ''
  99. #: Application version.
  100. version = VERSION_BANNER
  101. #: If false the parser will raise an exception if positional
  102. #: args are provided.
  103. supports_args = True
  104. #: List of options (without preload options).
  105. option_list = ()
  106. # module Rst documentation to parse help from (if any)
  107. doc = None
  108. # Some programs (multi) does not want to load the app specified
  109. # (Issue #1008).
  110. respects_app_option = True
  111. #: List of options to parse before parsing other options.
  112. preload_options = (
  113. Option('-A', '--app', default=None),
  114. Option('-b', '--broker', default=None),
  115. Option('--loader', default=None),
  116. Option('--config', default=None),
  117. Option('--workdir', default=None, dest='working_directory'),
  118. Option('--no-color', '-C', action='store_true', default=None),
  119. Option('--quiet', '-q', action='store_true'),
  120. )
  121. #: Enable if the application should support config from the cmdline.
  122. enable_config_from_cmdline = False
  123. #: Default configuration name-space.
  124. namespace = None
  125. #: Text to print at end of --help
  126. epilog = None
  127. #: Text to print in --help before option list.
  128. description = ''
  129. #: Set to true if this command doesn't have sub-commands
  130. leaf = True
  131. # used by :meth:`say_remote_command_reply`.
  132. show_body = True
  133. # used by :meth:`say_chat`.
  134. show_reply = True
  135. prog_name = 'celery'
  136. def __init__(self, app=None, get_app=None, no_color=False,
  137. stdout=None, stderr=None, quiet=False, on_error=None,
  138. on_usage_error=None):
  139. self.app = app
  140. self.get_app = get_app or self._get_default_app
  141. self.stdout = stdout or sys.stdout
  142. self.stderr = stderr or sys.stderr
  143. self._colored = None
  144. self._no_color = no_color
  145. self.quiet = quiet
  146. if not self.description:
  147. self.description = self._strip_restructeredtext(self.__doc__)
  148. if on_error:
  149. self.on_error = on_error
  150. if on_usage_error:
  151. self.on_usage_error = on_usage_error
  152. def run(self, *args, **options):
  153. """This is the body of the command called by :meth:`handle_argv`."""
  154. raise NotImplementedError('subclass responsibility')
  155. def on_error(self, exc):
  156. self.error(self.colored.red('Error: {0}'.format(exc)))
  157. def on_usage_error(self, exc):
  158. self.handle_error(exc)
  159. def on_concurrency_setup(self):
  160. pass
  161. def __call__(self, *args, **kwargs):
  162. random.seed() # maybe we were forked.
  163. self.verify_args(args)
  164. try:
  165. ret = self.run(*args, **kwargs)
  166. return ret if ret is not None else EX_OK
  167. except self.UsageError as exc:
  168. self.on_usage_error(exc)
  169. return exc.status
  170. except self.Error as exc:
  171. self.on_error(exc)
  172. return exc.status
  173. def verify_args(self, given, _index=0):
  174. S = getfullargspec(self.run)
  175. _index = 1 if S.args and S.args[0] == 'self' else _index
  176. required = S.args[_index:-len(S.defaults) if S.defaults else None]
  177. missing = required[len(given):]
  178. if missing:
  179. raise self.UsageError('Missing required {0}: {1}'.format(
  180. text.pluralize(len(missing), 'argument'),
  181. ', '.join(missing)
  182. ))
  183. def execute_from_commandline(self, argv=None):
  184. """Execute application from command-line.
  185. Arguments:
  186. argv (List[str]): The list of command-line arguments.
  187. Defaults to ``sys.argv``.
  188. """
  189. if argv is None:
  190. argv = list(sys.argv)
  191. # Should we load any special concurrency environment?
  192. self.maybe_patch_concurrency(argv)
  193. self.on_concurrency_setup()
  194. # Dump version and exit if '--version' arg set.
  195. self.early_version(argv)
  196. argv = self.setup_app_from_commandline(argv)
  197. self.prog_name = os.path.basename(argv[0])
  198. return self.handle_argv(self.prog_name, argv[1:])
  199. def run_from_argv(self, prog_name, argv=None, command=None):
  200. return self.handle_argv(prog_name,
  201. sys.argv if argv is None else argv, command)
  202. def maybe_patch_concurrency(self, argv=None):
  203. argv = argv or sys.argv
  204. pool_option = self.with_pool_option(argv)
  205. if pool_option:
  206. maybe_patch_concurrency(argv, *pool_option)
  207. short_opts, long_opts = pool_option
  208. def usage(self, command):
  209. return '%prog {0} [options] {self.args}'.format(command, self=self)
  210. def get_options(self):
  211. """Get supported command-line options."""
  212. return self.option_list
  213. def prepare_arguments(self, parser):
  214. pass
  215. def expanduser(self, value):
  216. if isinstance(value, string_t):
  217. return os.path.expanduser(value)
  218. return value
  219. def ask(self, q, choices, default=None):
  220. """Prompt user to choose from a tuple of string values.
  221. If a default is not specified the question will be repeated
  222. until the user gives a valid choice.
  223. Matching is case insensitive.
  224. Arguments:
  225. q (str): the question to ask (don't include questionark)
  226. choice (Tuple[str]): tuple of possible choices, must be lowercase.
  227. default (Any): Default value if any.
  228. """
  229. schoices = choices
  230. if default is not None:
  231. schoices = [c.upper() if c == default else c.lower()
  232. for c in choices]
  233. schoices = '/'.join(schoices)
  234. p = '{0} ({1})? '.format(q.capitalize(), schoices)
  235. while 1:
  236. val = input(p).lower()
  237. if val in choices:
  238. return val
  239. elif default is not None:
  240. break
  241. return default
  242. def handle_argv(self, prog_name, argv, command=None):
  243. """Parse command-line arguments from ``argv`` and dispatch
  244. to :meth:`run`.
  245. Warning:
  246. Exits with an error message if :attr:`supports_args` is disabled
  247. and ``argv`` contains positional arguments.
  248. Arguments:
  249. prog_name (str): The program name (``argv[0]``).
  250. argv (List[str]): Rest of command-line arguments.
  251. """
  252. options, args = self.prepare_args(
  253. *self.parse_options(prog_name, argv, command))
  254. return self(*args, **options)
  255. def prepare_args(self, options, args):
  256. if options:
  257. options = {
  258. k: self.expanduser(v)
  259. for k, v in items(vars(options)) if not k.startswith('_')
  260. }
  261. args = [self.expanduser(arg) for arg in args]
  262. self.check_args(args)
  263. return options, args
  264. def check_args(self, args):
  265. if not self.supports_args and args:
  266. self.die(ARGV_DISABLED.format(', '.join(args)), EX_USAGE)
  267. def error(self, s):
  268. self.out(s, fh=self.stderr)
  269. def out(self, s, fh=None):
  270. print(s, file=fh or self.stdout)
  271. def die(self, msg, status=EX_FAILURE):
  272. self.error(msg)
  273. sys.exit(status)
  274. def early_version(self, argv):
  275. if '--version' in argv:
  276. print(self.version, file=self.stdout)
  277. sys.exit(0)
  278. def parse_options(self, prog_name, arguments, command=None):
  279. """Parse the available options."""
  280. # Don't want to load configuration to just print the version,
  281. # so we handle --version manually here.
  282. self.parser = self.create_parser(prog_name, command)
  283. return self.parser.parse_args(arguments)
  284. def create_parser(self, prog_name, command=None):
  285. parser = self.Parser(
  286. prog=prog_name,
  287. usage=self.usage(command),
  288. version=self.version,
  289. epilog=self.epilog,
  290. formatter=HelpFormatter(),
  291. description=self.description,
  292. )
  293. parser.add_options(self.preload_options)
  294. for typ_ in reversed(type(self).mro()):
  295. try:
  296. prepare_arguments = typ_.prepare_arguments
  297. except AttributeError:
  298. continue
  299. prepare_arguments(self, parser)
  300. parser.add_options(self.get_options() or ())
  301. parser.add_options(self.app.user_options['preload'])
  302. return self.prepare_parser(parser)
  303. def prepare_parser(self, parser):
  304. docs = [self.parse_doc(doc) for doc in (self.doc, __doc__) if doc]
  305. for doc in docs:
  306. for long_opt, help in items(doc):
  307. option = parser.get_option(long_opt)
  308. if option is not None:
  309. option.help = ' '.join(help).format(default=option.default)
  310. return parser
  311. def setup_app_from_commandline(self, argv):
  312. preload_options = self.parse_preload_options(argv)
  313. quiet = preload_options.get('quiet')
  314. if quiet is not None:
  315. self.quiet = quiet
  316. try:
  317. self.no_color = preload_options['no_color']
  318. except KeyError:
  319. pass
  320. workdir = preload_options.get('working_directory')
  321. if workdir:
  322. os.chdir(workdir)
  323. app = (preload_options.get('app') or
  324. os.environ.get('CELERY_APP') or
  325. self.app)
  326. preload_loader = preload_options.get('loader')
  327. if preload_loader:
  328. # Default app takes loader from this env (Issue #1066).
  329. os.environ['CELERY_LOADER'] = preload_loader
  330. loader = (preload_loader,
  331. os.environ.get('CELERY_LOADER') or
  332. 'default')
  333. broker = preload_options.get('broker', None)
  334. if broker:
  335. os.environ['CELERY_BROKER_URL'] = broker
  336. config = preload_options.get('config')
  337. if config:
  338. os.environ['CELERY_CONFIG_MODULE'] = config
  339. if self.respects_app_option:
  340. if app:
  341. self.app = self.find_app(app)
  342. elif self.app is None:
  343. self.app = self.get_app(loader=loader)
  344. if self.enable_config_from_cmdline:
  345. argv = self.process_cmdline_config(argv)
  346. else:
  347. self.app = Celery(fixups=[])
  348. user_preload = tuple(self.app.user_options['preload'] or ())
  349. if user_preload:
  350. user_options = self.preparse_options(argv, user_preload)
  351. for user_option in user_preload:
  352. user_options.setdefault(user_option.dest, user_option.default)
  353. signals.user_preload_options.send(
  354. sender=self, app=self.app, options=user_options,
  355. )
  356. return argv
  357. def find_app(self, app):
  358. from celery.app.utils import find_app
  359. return find_app(app, symbol_by_name=self.symbol_by_name)
  360. def symbol_by_name(self, name, imp=import_from_cwd):
  361. return symbol_by_name(name, imp=imp)
  362. get_cls_by_name = symbol_by_name # XXX compat
  363. def process_cmdline_config(self, argv):
  364. try:
  365. cargs_start = argv.index('--')
  366. except ValueError:
  367. return argv
  368. argv, cargs = argv[:cargs_start], argv[cargs_start + 1:]
  369. self.app.config_from_cmdline(cargs, namespace=self.namespace)
  370. return argv
  371. def parse_preload_options(self, args):
  372. return self.preparse_options(args, self.preload_options)
  373. def add_append_opt(self, acc, opt, value):
  374. default = opt.default or []
  375. if opt.dest not in acc:
  376. acc[opt.dest] = default
  377. acc[opt.dest].append(value)
  378. def preparse_options(self, args, options):
  379. acc = {}
  380. opts = {}
  381. for opt in options:
  382. for t in (opt._long_opts, opt._short_opts):
  383. opts.update(dict(zip(t, [opt] * len(t))))
  384. index = 0
  385. length = len(args)
  386. while index < length:
  387. arg = args[index]
  388. if arg.startswith('--'):
  389. if '=' in arg:
  390. key, value = arg.split('=', 1)
  391. opt = opts.get(key)
  392. if opt:
  393. if opt.action == 'append':
  394. self.add_append_opt(acc, opt, value)
  395. else:
  396. acc[opt.dest] = value
  397. else:
  398. opt = opts.get(arg)
  399. if opt and opt.takes_value():
  400. # optparse also supports ['--opt', 'value']
  401. # (Issue #1668)
  402. if opt.action == 'append':
  403. self.add_append_opt(acc, opt, args[index + 1])
  404. else:
  405. acc[opt.dest] = args[index + 1]
  406. index += 1
  407. elif opt and opt.action == 'store_true':
  408. acc[opt.dest] = True
  409. elif arg.startswith('-'):
  410. opt = opts.get(arg)
  411. if opt:
  412. if opt.takes_value():
  413. try:
  414. acc[opt.dest] = args[index + 1]
  415. except IndexError:
  416. raise ValueError(
  417. 'Missing required argument for {0}'.format(
  418. arg))
  419. index += 1
  420. elif opt.action == 'store_true':
  421. acc[opt.dest] = True
  422. index += 1
  423. return acc
  424. def parse_doc(self, doc):
  425. options, in_option = defaultdict(list), None
  426. for line in doc.splitlines():
  427. if line.startswith('.. cmdoption::'):
  428. m = find_long_opt.match(line)
  429. if m:
  430. in_option = m.groups()[0].strip()
  431. assert in_option, 'missing long opt'
  432. elif in_option and line.startswith(' ' * 4):
  433. if not find_rst_decl.match(line):
  434. options[in_option].append(
  435. find_rst_ref.sub(
  436. r'\1', line.strip()).replace('`', ''))
  437. return options
  438. def _strip_restructeredtext(self, s):
  439. return '\n'.join(
  440. find_rst_ref.sub(r'\1', line.replace('`', ''))
  441. for line in (s or '').splitlines()
  442. if not find_rst_decl.match(line)
  443. )
  444. def with_pool_option(self, argv):
  445. """Return tuple of ``(short_opts, long_opts)`` if the command
  446. supports a pool argument, and used to monkey patch eventlet/gevent
  447. environments as early as possible.
  448. E.g::
  449. has_pool_option = (['-P'], ['--pool'])
  450. """
  451. pass
  452. def node_format(self, s, nodename, **extra):
  453. return node_format(s, nodename, **extra)
  454. def host_format(self, s, **extra):
  455. return host_format(s, **extra)
  456. def _get_default_app(self, *args, **kwargs):
  457. from celery._state import get_current_app
  458. return get_current_app() # omit proxy
  459. def pretty_list(self, n):
  460. c = self.colored
  461. if not n:
  462. return '- empty -'
  463. return '\n'.join(
  464. str(c.reset(c.white('*'), ' {0}'.format(item))) for item in n
  465. )
  466. def pretty_dict_ok_error(self, n):
  467. c = self.colored
  468. try:
  469. return (c.green('OK'),
  470. text.indent(self.pretty(n['ok'])[1], 4))
  471. except KeyError:
  472. pass
  473. return (c.red('ERROR'),
  474. text.indent(self.pretty(n['error'])[1], 4))
  475. def say_remote_command_reply(self, replies):
  476. c = self.colored
  477. node = next(iter(replies)) # <-- take first.
  478. reply = replies[node]
  479. status, preply = self.pretty(reply)
  480. self.say_chat('->', c.cyan(node, ': ') + status,
  481. text.indent(preply, 4) if self.show_reply else '')
  482. def pretty(self, n):
  483. OK = str(self.colored.green('OK'))
  484. if isinstance(n, list):
  485. return OK, self.pretty_list(n)
  486. if isinstance(n, dict):
  487. if 'ok' in n or 'error' in n:
  488. return self.pretty_dict_ok_error(n)
  489. else:
  490. return OK, json.dumps(n, sort_keys=True, indent=4)
  491. if isinstance(n, string_t):
  492. return OK, string(n)
  493. return OK, pformat(n)
  494. def say_chat(self, direction, title, body=''):
  495. c = self.colored
  496. if direction == '<-' and self.quiet:
  497. return
  498. dirstr = not self.quiet and c.bold(c.white(direction), ' ') or ''
  499. self.out(c.reset(dirstr, title))
  500. if body and self.show_body:
  501. self.out(body)
  502. @property
  503. def colored(self):
  504. if self._colored is None:
  505. self._colored = term.colored(enabled=not self.no_color)
  506. return self._colored
  507. @colored.setter
  508. def colored(self, obj):
  509. self._colored = obj
  510. @property
  511. def no_color(self):
  512. return self._no_color
  513. @no_color.setter
  514. def no_color(self, value):
  515. self._no_color = value
  516. if self._colored is not None:
  517. self._colored.enabled = not self._no_color
  518. def daemon_options(parser, default_pidfile=None, default_logfile=None):
  519. group = OptionGroup(parser, 'Daemonization Options')
  520. group.add_option('-f', '--logfile', default=default_logfile),
  521. group.add_option('--pidfile', default=default_pidfile),
  522. group.add_option('--uid', default=None),
  523. group.add_option('--gid', default=None),
  524. group.add_option('--umask', default=None),
  525. group.add_option('--executable', default=None),
  526. parser.add_option_group(group)