Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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 = dict((k, self.expanduser(v))
  282. for k, v in items(vars(options))
  283. if not k.startswith('_'))
  284. args = [self.expanduser(arg) for arg in args]
  285. self.check_args(args)
  286. return options, args
  287. def check_args(self, args):
  288. if not self.supports_args and args:
  289. self.die(ARGV_DISABLED.format(', '.join(args)), EX_USAGE)
  290. def error(self, s):
  291. self.out(s, fh=self.stderr)
  292. def out(self, s, fh=None):
  293. print(s, file=fh or self.stdout)
  294. def die(self, msg, status=EX_FAILURE):
  295. self.error(msg)
  296. sys.exit(status)
  297. def early_version(self, argv):
  298. if '--version' in argv:
  299. print(self.version, file=self.stdout)
  300. sys.exit(0)
  301. def parse_options(self, prog_name, arguments, command=None):
  302. """Parse the available options."""
  303. # Don't want to load configuration to just print the version,
  304. # so we handle --version manually here.
  305. self.parser = self.create_parser(prog_name, command)
  306. return self.parser.parse_args(arguments)
  307. def create_parser(self, prog_name, command=None):
  308. option_list = (
  309. self.preload_options +
  310. self.get_options() +
  311. tuple(self.app.user_options['preload'])
  312. )
  313. return self.prepare_parser(self.Parser(
  314. prog=prog_name,
  315. usage=self.usage(command),
  316. version=self.version,
  317. epilog=self.epilog,
  318. formatter=HelpFormatter(),
  319. description=self.description,
  320. option_list=option_list,
  321. ))
  322. def prepare_parser(self, parser):
  323. docs = [self.parse_doc(doc) for doc in (self.doc, __doc__) if doc]
  324. for doc in docs:
  325. for long_opt, help in items(doc):
  326. option = parser.get_option(long_opt)
  327. if option is not None:
  328. option.help = ' '.join(help).format(default=option.default)
  329. return parser
  330. def setup_app_from_commandline(self, argv):
  331. preload_options = self.parse_preload_options(argv)
  332. quiet = preload_options.get('quiet')
  333. if quiet is not None:
  334. self.quiet = quiet
  335. try:
  336. self.no_color = preload_options['no_color']
  337. except KeyError:
  338. pass
  339. workdir = preload_options.get('working_directory')
  340. if workdir:
  341. os.chdir(workdir)
  342. app = (preload_options.get('app') or
  343. os.environ.get('CELERY_APP') or
  344. self.app)
  345. preload_loader = preload_options.get('loader')
  346. if preload_loader:
  347. # Default app takes loader from this env (Issue #1066).
  348. os.environ['CELERY_LOADER'] = preload_loader
  349. loader = (preload_loader,
  350. os.environ.get('CELERY_LOADER') or
  351. 'default')
  352. broker = preload_options.get('broker', None)
  353. if broker:
  354. os.environ['CELERY_BROKER_URL'] = broker
  355. config = preload_options.get('config')
  356. if config:
  357. os.environ['CELERY_CONFIG_MODULE'] = config
  358. if self.respects_app_option:
  359. if app:
  360. self.app = self.find_app(app)
  361. elif self.app is None:
  362. self.app = self.get_app(loader=loader)
  363. if self.enable_config_from_cmdline:
  364. argv = self.process_cmdline_config(argv)
  365. else:
  366. self.app = Celery(fixups=[])
  367. user_preload = tuple(self.app.user_options['preload'] or ())
  368. if user_preload:
  369. user_options = self.preparse_options(argv, user_preload)
  370. for user_option in user_preload:
  371. user_options.setdefault(user_option.dest, user_option.default)
  372. signals.user_preload_options.send(
  373. sender=self, app=self.app, options=user_options,
  374. )
  375. return argv
  376. def find_app(self, app):
  377. from celery.app.utils import find_app
  378. return find_app(app, symbol_by_name=self.symbol_by_name)
  379. def symbol_by_name(self, name, imp=import_from_cwd):
  380. return symbol_by_name(name, imp=imp)
  381. get_cls_by_name = symbol_by_name # XXX compat
  382. def process_cmdline_config(self, argv):
  383. try:
  384. cargs_start = argv.index('--')
  385. except ValueError:
  386. return argv
  387. argv, cargs = argv[:cargs_start], argv[cargs_start + 1:]
  388. self.app.config_from_cmdline(cargs, namespace=self.namespace)
  389. return argv
  390. def parse_preload_options(self, args):
  391. return self.preparse_options(args, self.preload_options)
  392. def add_append_opt(self, acc, opt, value):
  393. acc.setdefault(opt.dest, opt.default or [])
  394. acc[opt.dest].append(value)
  395. def preparse_options(self, args, options):
  396. acc = {}
  397. opts = {}
  398. for opt in options:
  399. for t in (opt._long_opts, opt._short_opts):
  400. opts.update(dict(zip(t, [opt] * len(t))))
  401. index = 0
  402. length = len(args)
  403. while index < length:
  404. arg = args[index]
  405. if arg.startswith('--'):
  406. if '=' in arg:
  407. key, value = arg.split('=', 1)
  408. opt = opts.get(key)
  409. if opt:
  410. if opt.action == 'append':
  411. self.add_append_opt(acc, opt, value)
  412. else:
  413. acc[opt.dest] = value
  414. else:
  415. opt = opts.get(arg)
  416. if opt and opt.takes_value():
  417. # optparse also supports ['--opt', 'value']
  418. # (Issue #1668)
  419. if opt.action == 'append':
  420. self.add_append_opt(acc, opt, args[index + 1])
  421. else:
  422. acc[opt.dest] = args[index + 1]
  423. index += 1
  424. elif opt and opt.action == 'store_true':
  425. acc[opt.dest] = True
  426. elif arg.startswith('-'):
  427. opt = opts.get(arg)
  428. if opt:
  429. if opt.takes_value():
  430. try:
  431. acc[opt.dest] = args[index + 1]
  432. except IndexError:
  433. raise ValueError(
  434. 'Missing required argument for {0}'.format(
  435. arg))
  436. index += 1
  437. elif opt.action == 'store_true':
  438. acc[opt.dest] = True
  439. index += 1
  440. return acc
  441. def parse_doc(self, doc):
  442. options, in_option = defaultdict(list), None
  443. for line in doc.splitlines():
  444. if line.startswith('.. cmdoption::'):
  445. m = find_long_opt.match(line)
  446. if m:
  447. in_option = m.groups()[0].strip()
  448. assert in_option, 'missing long opt'
  449. elif in_option and line.startswith(' ' * 4):
  450. options[in_option].append(
  451. find_rst_ref.sub(r'\1', line.strip()).replace('`', ''))
  452. return options
  453. def with_pool_option(self, argv):
  454. """Return tuple of ``(short_opts, long_opts)`` if the command
  455. supports a pool argument, and used to monkey patch eventlet/gevent
  456. environments as early as possible.
  457. E.g::
  458. has_pool_option = (['-P'], ['--pool'])
  459. """
  460. pass
  461. def node_format(self, s, nodename, **extra):
  462. return node_format(s, nodename, **extra)
  463. def host_format(self, s, **extra):
  464. return host_format(s, **extra)
  465. def _get_default_app(self, *args, **kwargs):
  466. from celery._state import get_current_app
  467. return get_current_app() # omit proxy
  468. def pretty_list(self, n):
  469. c = self.colored
  470. if not n:
  471. return '- empty -'
  472. return '\n'.join(
  473. str(c.reset(c.white('*'), ' {0}'.format(item))) for item in n
  474. )
  475. def pretty_dict_ok_error(self, n):
  476. c = self.colored
  477. try:
  478. return (c.green('OK'),
  479. text.indent(self.pretty(n['ok'])[1], 4))
  480. except KeyError:
  481. pass
  482. return (c.red('ERROR'),
  483. text.indent(self.pretty(n['error'])[1], 4))
  484. def say_remote_command_reply(self, replies):
  485. c = self.colored
  486. node = next(iter(replies)) # <-- take first.
  487. reply = replies[node]
  488. status, preply = self.pretty(reply)
  489. self.say_chat('->', c.cyan(node, ': ') + status,
  490. text.indent(preply, 4) if self.show_reply else '')
  491. def pretty(self, n):
  492. OK = str(self.colored.green('OK'))
  493. if isinstance(n, list):
  494. return OK, self.pretty_list(n)
  495. if isinstance(n, dict):
  496. if 'ok' in n or 'error' in n:
  497. return self.pretty_dict_ok_error(n)
  498. else:
  499. return OK, json.dumps(n, sort_keys=True, indent=4)
  500. if isinstance(n, string_t):
  501. return OK, string(n)
  502. return OK, pformat(n)
  503. def say_chat(self, direction, title, body=''):
  504. c = self.colored
  505. if direction == '<-' and self.quiet:
  506. return
  507. dirstr = not self.quiet and c.bold(c.white(direction), ' ') or ''
  508. self.out(c.reset(dirstr, title))
  509. if body and self.show_body:
  510. self.out(body)
  511. @property
  512. def colored(self):
  513. if self._colored is None:
  514. self._colored = term.colored(enabled=not self.no_color)
  515. return self._colored
  516. @colored.setter
  517. def colored(self, obj):
  518. self._colored = obj
  519. @property
  520. def no_color(self):
  521. return self._no_color
  522. @no_color.setter
  523. def no_color(self, value):
  524. self._no_color = value
  525. if self._colored is not None:
  526. self._colored.enabled = not self._no_color
  527. def daemon_options(default_pidfile=None, default_logfile=None):
  528. return (
  529. Option('-f', '--logfile', default=default_logfile),
  530. Option('--pidfile', default=default_pidfile),
  531. Option('--uid', default=None),
  532. Option('--gid', default=None),
  533. Option('--umask', default=None),
  534. Option('--executable', default=None),
  535. )