base.py 21 KB

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