PageRenderTime 27ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/celery/bin/base.py

https://github.com/dctrwatson/celery
Python | 541 lines | 471 code | 26 blank | 44 comment | 44 complexity | a7a57dbbcd84183b4f2a282759a0aca6 MD5 | raw file
  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 of the process after detaching. Default is 0.
  35. .. cmdoption:: --workdir
  36. Optional directory to change to after detaching.
  37. """
  38. from __future__ import absolute_import, print_function
  39. import os
  40. import re
  41. import socket
  42. import sys
  43. import warnings
  44. from collections import defaultdict
  45. from heapq import heappush
  46. from optparse import OptionParser, IndentedHelpFormatter, make_option as Option
  47. from pprint import pformat
  48. from types import ModuleType
  49. import celery
  50. from celery.exceptions import CDeprecationWarning, CPendingDeprecationWarning
  51. from celery.five import items, string, string_t
  52. from celery.platforms import (
  53. EX_FAILURE, EX_OK, EX_USAGE,
  54. maybe_patch_concurrency,
  55. )
  56. from celery.utils import term
  57. from celery.utils import text
  58. from celery.utils.imports import symbol_by_name, import_from_cwd
  59. # always enable DeprecationWarnings, so our users can see them.
  60. for warning in (CDeprecationWarning, CPendingDeprecationWarning):
  61. warnings.simplefilter('once', warning, 0)
  62. ARGV_DISABLED = """
  63. Unrecognized command-line arguments: {0}
  64. Try --help?
  65. """
  66. find_long_opt = re.compile(r'.+?(--.+?)(?:\s|,|$)')
  67. find_rst_ref = re.compile(r':\w+:`(.+?)`')
  68. find_sformat = re.compile(r'%(\w)')
  69. class Error(Exception):
  70. def __init__(self, reason, status=EX_FAILURE):
  71. self.reason = reason
  72. self.status = status
  73. super(Error, self).__init__(reason, status)
  74. def __str__(self):
  75. return self.reason
  76. class Extensions(object):
  77. def __init__(self, namespace, register):
  78. self.names = []
  79. self.namespace = namespace
  80. self.register = register
  81. def add(self, cls, name):
  82. heappush(self.names, name)
  83. self.register(cls, name=name)
  84. def load(self):
  85. try:
  86. from pkg_resources import iter_entry_points
  87. except ImportError:
  88. return
  89. for ep in iter_entry_points(self.namespace):
  90. sym = ':'.join([ep.module_name, ep.attrs[0]])
  91. try:
  92. cls = symbol_by_name(sym)
  93. except (ImportError, SyntaxError) as exc:
  94. warnings.warn(
  95. 'Cannot load extension {0!r}: {1!r}'.format(sym, exc))
  96. else:
  97. self.add(cls, ep.name)
  98. return self.names
  99. class HelpFormatter(IndentedHelpFormatter):
  100. def format_epilog(self, epilog):
  101. if epilog:
  102. return '\n{0}\n\n'.format(epilog)
  103. return ''
  104. def format_description(self, description):
  105. return text.ensure_2lines(text.fill_paragraphs(
  106. text.dedent(description), self.width))
  107. class Command(object):
  108. """Base class for command-line applications.
  109. :keyword app: The current app.
  110. :keyword get_app: Callable returning the current app if no app provided.
  111. """
  112. Parser = OptionParser
  113. #: Arg list used in help.
  114. args = ''
  115. #: Application version.
  116. version = celery.VERSION_BANNER
  117. #: If false the parser will raise an exception if positional
  118. #: args are provided.
  119. supports_args = True
  120. #: List of options (without preload options).
  121. option_list = ()
  122. # module Rst documentation to parse help from (if any)
  123. doc = None
  124. # Some programs (multi) does not want to load the app specified
  125. # (Issue #1008).
  126. respects_app_option = True
  127. #: List of options to parse before parsing other options.
  128. preload_options = (
  129. Option('-A', '--app', default=None),
  130. Option('-b', '--broker', default=None),
  131. Option('--loader', default=None),
  132. Option('--config', default=None),
  133. Option('--workdir', default=None, dest='working_directory'),
  134. Option('--no-color', '-C', action='store_true', default=None),
  135. Option('--quiet', '-q', action='store_true'),
  136. )
  137. #: Enable if the application should support config from the cmdline.
  138. enable_config_from_cmdline = False
  139. #: Default configuration namespace.
  140. namespace = 'celery'
  141. #: Text to print at end of --help
  142. epilog = None
  143. #: Text to print in --help before option list.
  144. description = ''
  145. #: Set to true if this command doesn't have subcommands
  146. leaf = True
  147. # used by :meth:`say_remote_control_reply`.
  148. show_body = True
  149. # used by :meth:`say_chat`.
  150. show_reply = True
  151. prog_name = 'celery'
  152. def __init__(self, app=None, get_app=None, no_color=False,
  153. stdout=None, stderr=None, quiet=False):
  154. self.app = app
  155. self.get_app = get_app or self._get_default_app
  156. self.stdout = stdout or sys.stdout
  157. self.stderr = stderr or sys.stderr
  158. self.no_color = no_color
  159. self.colored = term.colored(enabled=not self.no_color)
  160. self.quiet = quiet
  161. if not self.description:
  162. self.description = self.__doc__
  163. def __call__(self, *args, **kwargs):
  164. try:
  165. ret = self.run(*args, **kwargs)
  166. except Error as exc:
  167. self.error(self.colored.red('Error: {0}'.format(exc)))
  168. return exc.status
  169. return ret if ret is not None else EX_OK
  170. def run(self, *args, **options):
  171. """This is the body of the command called by :meth:`handle_argv`."""
  172. raise NotImplementedError('subclass responsibility')
  173. def execute_from_commandline(self, argv=None):
  174. """Execute application from command-line.
  175. :keyword argv: The list of command-line arguments.
  176. Defaults to ``sys.argv``.
  177. """
  178. if argv is None:
  179. argv = list(sys.argv)
  180. # Should we load any special concurrency environment?
  181. self.maybe_patch_concurrency(argv)
  182. self.on_concurrency_setup()
  183. # Dump version and exit if '--version' arg set.
  184. self.early_version(argv)
  185. argv = self.setup_app_from_commandline(argv)
  186. self.prog_name = os.path.basename(argv[0])
  187. return self.handle_argv(self.prog_name, argv[1:])
  188. def run_from_argv(self, prog_name, argv=None, command=None):
  189. return self.handle_argv(prog_name,
  190. sys.argv if argv is None else argv, command)
  191. def maybe_patch_concurrency(self, argv=None):
  192. argv = argv or sys.argv
  193. pool_option = self.with_pool_option(argv)
  194. if pool_option:
  195. maybe_patch_concurrency(argv, *pool_option)
  196. short_opts, long_opts = pool_option
  197. def on_concurrency_setup(self):
  198. pass
  199. def usage(self, command):
  200. return '%prog {0} [options] {self.args}'.format(command, self=self)
  201. def get_options(self):
  202. """Get supported command-line options."""
  203. return self.option_list
  204. def expanduser(self, value):
  205. if isinstance(value, string_t):
  206. return os.path.expanduser(value)
  207. return value
  208. def handle_argv(self, prog_name, argv, command=None):
  209. """Parses command-line arguments from ``argv`` and dispatches
  210. to :meth:`run`.
  211. :param prog_name: The program name (``argv[0]``).
  212. :param argv: Command arguments.
  213. Exits with an error message if :attr:`supports_args` is disabled
  214. and ``argv`` contains positional arguments.
  215. """
  216. options, args = self.prepare_args(
  217. *self.parse_options(prog_name, argv, command))
  218. return self(*args, **options)
  219. def prepare_args(self, options, args):
  220. if options:
  221. options = dict((k, self.expanduser(v))
  222. for k, v in items(vars(options))
  223. if not k.startswith('_'))
  224. args = [self.expanduser(arg) for arg in args]
  225. self.check_args(args)
  226. return options, args
  227. def check_args(self, args):
  228. if not self.supports_args and args:
  229. self.die(ARGV_DISABLED.format(', '.join(args)), EX_USAGE)
  230. def error(self, s):
  231. self.out(s, fh=self.stderr)
  232. def out(self, s, fh=None):
  233. print(s, file=fh or self.stdout)
  234. def die(self, msg, status=EX_FAILURE):
  235. self.error(msg)
  236. sys.exit(status)
  237. def early_version(self, argv):
  238. if '--version' in argv:
  239. print(self.version, file=self.stdout)
  240. sys.exit(0)
  241. def parse_options(self, prog_name, arguments, command=None):
  242. """Parse the available options."""
  243. # Don't want to load configuration to just print the version,
  244. # so we handle --version manually here.
  245. self.parser = self.create_parser(prog_name, command)
  246. return self.parser.parse_args(arguments)
  247. def create_parser(self, prog_name, command=None):
  248. return self.prepare_parser(self.Parser(
  249. prog=prog_name,
  250. usage=self.usage(command),
  251. version=self.version,
  252. epilog=self.epilog,
  253. formatter=HelpFormatter(),
  254. description=self.description,
  255. option_list=(self.preload_options + self.get_options()),
  256. ))
  257. def prepare_parser(self, parser):
  258. docs = [self.parse_doc(doc) for doc in (self.doc, __doc__) if doc]
  259. for doc in docs:
  260. for long_opt, help in items(doc):
  261. option = parser.get_option(long_opt)
  262. if option is not None:
  263. option.help = ' '.join(help).format(default=option.default)
  264. return parser
  265. def setup_app_from_commandline(self, argv):
  266. preload_options = self.parse_preload_options(argv)
  267. quiet = preload_options.get('quiet')
  268. if quiet is not None:
  269. self.quiet = quiet
  270. self.colored.enabled = \
  271. not preload_options.get('no_color', self.no_color)
  272. workdir = preload_options.get('working_directory')
  273. if workdir:
  274. os.chdir(workdir)
  275. app = (preload_options.get('app') or
  276. os.environ.get('CELERY_APP') or
  277. self.app)
  278. preload_loader = preload_options.get('loader')
  279. if preload_loader:
  280. # Default app takes loader from this env (Issue #1066).
  281. os.environ['CELERY_LOADER'] = preload_loader
  282. loader = (preload_loader,
  283. os.environ.get('CELERY_LOADER') or
  284. 'default')
  285. broker = preload_options.get('broker', None)
  286. if broker:
  287. os.environ['CELERY_BROKER_URL'] = broker
  288. config = preload_options.get('config')
  289. if config:
  290. os.environ['CELERY_CONFIG_MODULE'] = config
  291. if self.respects_app_option:
  292. if app and self.respects_app_option:
  293. self.app = self.find_app(app)
  294. elif self.app is None:
  295. self.app = self.get_app(loader=loader)
  296. if self.enable_config_from_cmdline:
  297. argv = self.process_cmdline_config(argv)
  298. else:
  299. self.app = celery.Celery()
  300. return argv
  301. def find_app(self, app):
  302. try:
  303. sym = self.symbol_by_name(app)
  304. except AttributeError:
  305. # last part was not an attribute, but a module
  306. sym = import_from_cwd(app)
  307. if isinstance(sym, ModuleType):
  308. try:
  309. return sym.celery
  310. except AttributeError:
  311. if getattr(sym, '__path__', None):
  312. return self.find_app('{0}.celery:'.format(
  313. app.replace(':', '')))
  314. from celery.app.base import Celery
  315. for suspect in vars(sym).itervalues():
  316. if isinstance(suspect, Celery):
  317. return suspect
  318. raise
  319. return sym
  320. def symbol_by_name(self, name):
  321. return symbol_by_name(name, imp=import_from_cwd)
  322. get_cls_by_name = symbol_by_name # XXX compat
  323. def process_cmdline_config(self, argv):
  324. try:
  325. cargs_start = argv.index('--')
  326. except ValueError:
  327. return argv
  328. argv, cargs = argv[:cargs_start], argv[cargs_start + 1:]
  329. self.app.config_from_cmdline(cargs, namespace=self.namespace)
  330. return argv
  331. def parse_preload_options(self, args):
  332. acc = {}
  333. opts = {}
  334. for opt in self.preload_options:
  335. for t in (opt._long_opts, opt._short_opts):
  336. opts.update(dict(zip(t, [opt.dest] * len(t))))
  337. index = 0
  338. length = len(args)
  339. while index < length:
  340. arg = args[index]
  341. if arg.startswith('--') and '=' in arg:
  342. key, value = arg.split('=', 1)
  343. dest = opts.get(key)
  344. if dest:
  345. acc[dest] = value
  346. elif arg.startswith('-'):
  347. dest = opts.get(arg)
  348. if dest:
  349. acc[dest] = args[index + 1]
  350. index += 1
  351. index += 1
  352. return acc
  353. def parse_doc(self, doc):
  354. options, in_option = defaultdict(list), None
  355. for line in doc.splitlines():
  356. if line.startswith('.. cmdoption::'):
  357. m = find_long_opt.match(line)
  358. if m:
  359. in_option = m.groups()[0].strip()
  360. assert in_option, 'missing long opt'
  361. elif in_option and line.startswith(' ' * 4):
  362. options[in_option].append(
  363. find_rst_ref.sub(r'\1', line.strip()).replace('`', ''))
  364. return options
  365. def with_pool_option(self, argv):
  366. """Returns tuple of ``(short_opts, long_opts)`` if the command
  367. supports a pool argument, and used to monkey patch eventlet/gevent
  368. environments as early as possible.
  369. E.g::
  370. has_pool_option = (['-P'], ['--pool'])
  371. """
  372. pass
  373. def simple_format(self, s, match=find_sformat, expand=r'\1', **keys):
  374. if s:
  375. host = socket.gethostname()
  376. name, _, domain = host.partition('.')
  377. keys = dict({'%': '%', 'h': host, 'n': name, 'd': domain}, **keys)
  378. return match.sub(lambda m: keys[m.expand(expand)], s)
  379. def _get_default_app(self, *args, **kwargs):
  380. from celery._state import get_current_app
  381. return get_current_app() # omit proxy
  382. def pretty_list(self, n):
  383. c = self.colored
  384. if not n:
  385. return '- empty -'
  386. return '\n'.join(
  387. str(c.reset(c.white('*'), ' {0}'.format(item))) for item in n
  388. )
  389. def pretty_dict_ok_error(self, n):
  390. c = self.colored
  391. try:
  392. return (c.green('OK'),
  393. text.indent(self.pretty(n['ok'])[1], 4))
  394. except KeyError:
  395. pass
  396. return (c.red('ERROR'),
  397. text.indent(self.pretty(n['error'])[1], 4))
  398. def say_remote_command_reply(self, replies):
  399. c = self.colored
  400. node = next(iter(replies)) # <-- take first.
  401. reply = replies[node]
  402. status, preply = self.pretty(reply)
  403. self.say_chat('->', c.cyan(node, ': ') + status,
  404. text.indent(preply, 4) if self.show_reply else '')
  405. def pretty(self, n):
  406. OK = str(self.colored.green('OK'))
  407. if isinstance(n, list):
  408. return OK, self.pretty_list(n)
  409. if isinstance(n, dict):
  410. if 'ok' in n or 'error' in n:
  411. return self.pretty_dict_ok_error(n)
  412. if isinstance(n, string_t):
  413. return OK, string(n)
  414. return OK, pformat(n)
  415. def say_chat(self, direction, title, body=''):
  416. c = self.colored
  417. if direction == '<-' and self.quiet:
  418. return
  419. dirstr = not self.quiet and c.bold(c.white(direction), ' ') or ''
  420. self.out(c.reset(dirstr, title))
  421. if body and self.show_body:
  422. self.out(body)
  423. def daemon_options(default_pidfile=None, default_logfile=None):
  424. return (
  425. Option('-f', '--logfile', default=default_logfile),
  426. Option('--pidfile', default=default_pidfile),
  427. Option('--uid', default=None),
  428. Option('--gid', default=None),
  429. Option('--umask', default=0, type='int'),
  430. )