base.py 20 KB

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