OpenStack Compute (Nova) Client
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.

shell.py 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  1. # Copyright 2010 Jacob Kaplan-Moss
  2. # Copyright 2011 OpenStack Foundation
  3. # All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """
  17. Command-line interface to the OpenStack Nova API.
  18. """
  19. from __future__ import print_function
  20. import argparse
  21. import getpass
  22. import glob
  23. import imp
  24. import itertools
  25. import logging
  26. import os
  27. import pkgutil
  28. import sys
  29. from keystoneclient.auth.identity.generic import password
  30. from keystoneclient.auth.identity.generic import token
  31. from keystoneclient.auth.identity import v3 as identity
  32. from keystoneclient import session as ksession
  33. from oslo_utils import encodeutils
  34. from oslo_utils import strutils
  35. import pkg_resources
  36. import six
  37. HAS_KEYRING = False
  38. all_errors = ValueError
  39. try:
  40. import keyring
  41. HAS_KEYRING = True
  42. except ImportError:
  43. pass
  44. import novaclient
  45. import novaclient.auth_plugin
  46. from novaclient import client
  47. from novaclient import exceptions as exc
  48. import novaclient.extension
  49. from novaclient.i18n import _
  50. from novaclient.openstack.common import cliutils
  51. from novaclient import utils
  52. from novaclient.v2 import shell as shell_v2
  53. DEFAULT_OS_COMPUTE_API_VERSION = "2"
  54. DEFAULT_NOVA_ENDPOINT_TYPE = 'publicURL'
  55. # NOTE(cyeoh): Having the service type dependent on the API version
  56. # is pretty ugly, but we have to do this because traditionally the
  57. # catalog entry for compute points directly to the V2 API rather than
  58. # the root, and then doing version discovery.
  59. DEFAULT_NOVA_SERVICE_TYPE_MAP = {'1.1': 'compute',
  60. '2': 'compute',
  61. '3': 'computev3'}
  62. logger = logging.getLogger(__name__)
  63. def positive_non_zero_float(text):
  64. if text is None:
  65. return None
  66. try:
  67. value = float(text)
  68. except ValueError:
  69. msg = _("%s must be a float") % text
  70. raise argparse.ArgumentTypeError(msg)
  71. if value <= 0:
  72. msg = _("%s must be greater than 0") % text
  73. raise argparse.ArgumentTypeError(msg)
  74. return value
  75. class SecretsHelper(object):
  76. def __init__(self, args, client):
  77. self.args = args
  78. self.client = client
  79. self.key = None
  80. self._password = None
  81. def _validate_string(self, text):
  82. if text is None or len(text) == 0:
  83. return False
  84. return True
  85. def _make_key(self):
  86. if self.key is not None:
  87. return self.key
  88. keys = [
  89. self.client.auth_url,
  90. self.client.projectid,
  91. self.client.user,
  92. self.client.region_name,
  93. self.client.endpoint_type,
  94. self.client.service_type,
  95. self.client.service_name,
  96. self.client.volume_service_name,
  97. ]
  98. for (index, key) in enumerate(keys):
  99. if key is None:
  100. keys[index] = '?'
  101. else:
  102. keys[index] = str(keys[index])
  103. self.key = "/".join(keys)
  104. return self.key
  105. def _prompt_password(self, verify=True):
  106. pw = None
  107. if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
  108. # Check for Ctl-D
  109. try:
  110. while True:
  111. pw1 = getpass.getpass('OS Password: ')
  112. if verify:
  113. pw2 = getpass.getpass('Please verify: ')
  114. else:
  115. pw2 = pw1
  116. if pw1 == pw2 and self._validate_string(pw1):
  117. pw = pw1
  118. break
  119. except EOFError:
  120. pass
  121. return pw
  122. def save(self, auth_token, management_url, tenant_id):
  123. if not HAS_KEYRING or not self.args.os_cache:
  124. return
  125. if (auth_token == self.auth_token and
  126. management_url == self.management_url):
  127. # Nothing changed....
  128. return
  129. if not all([management_url, auth_token, tenant_id]):
  130. raise ValueError(_("Unable to save empty management url/auth "
  131. "token"))
  132. value = "|".join([str(auth_token),
  133. str(management_url),
  134. str(tenant_id)])
  135. keyring.set_password("novaclient_auth", self._make_key(), value)
  136. @property
  137. def password(self):
  138. # Cache password so we prompt user at most once
  139. if self._password:
  140. pass
  141. elif self._validate_string(self.args.os_password):
  142. self._password = self.args.os_password
  143. else:
  144. verify_pass = strutils.bool_from_string(
  145. cliutils.env("OS_VERIFY_PASSWORD", default=False), True)
  146. self._password = self._prompt_password(verify_pass)
  147. if not self._password:
  148. raise exc.CommandError(
  149. 'Expecting a password provided via either '
  150. '--os-password, env[OS_PASSWORD], or '
  151. 'prompted response')
  152. return self._password
  153. @property
  154. def management_url(self):
  155. if not HAS_KEYRING or not self.args.os_cache:
  156. return None
  157. management_url = None
  158. try:
  159. block = keyring.get_password('novaclient_auth', self._make_key())
  160. if block:
  161. _token, management_url, _tenant_id = block.split('|', 2)
  162. except all_errors:
  163. pass
  164. return management_url
  165. @property
  166. def auth_token(self):
  167. # Now is where it gets complicated since we
  168. # want to look into the keyring module, if it
  169. # exists and see if anything was provided in that
  170. # file that we can use.
  171. if not HAS_KEYRING or not self.args.os_cache:
  172. return None
  173. token = None
  174. try:
  175. block = keyring.get_password('novaclient_auth', self._make_key())
  176. if block:
  177. token, _management_url, _tenant_id = block.split('|', 2)
  178. except all_errors:
  179. pass
  180. return token
  181. @property
  182. def tenant_id(self):
  183. if not HAS_KEYRING or not self.args.os_cache:
  184. return None
  185. tenant_id = None
  186. try:
  187. block = keyring.get_password('novaclient_auth', self._make_key())
  188. if block:
  189. _token, _management_url, tenant_id = block.split('|', 2)
  190. except all_errors:
  191. pass
  192. return tenant_id
  193. class NovaClientArgumentParser(argparse.ArgumentParser):
  194. def __init__(self, *args, **kwargs):
  195. super(NovaClientArgumentParser, self).__init__(*args, **kwargs)
  196. def error(self, message):
  197. """error(message: string)
  198. Prints a usage message incorporating the message to stderr and
  199. exits.
  200. """
  201. self.print_usage(sys.stderr)
  202. # FIXME(lzyeval): if changes occur in argparse.ArgParser._check_value
  203. choose_from = ' (choose from'
  204. progparts = self.prog.partition(' ')
  205. self.exit(2, _("error: %(errmsg)s\nTry '%(mainp)s help %(subp)s'"
  206. " for more information.\n") %
  207. {'errmsg': message.split(choose_from)[0],
  208. 'mainp': progparts[0],
  209. 'subp': progparts[2]})
  210. def _get_option_tuples(self, option_string):
  211. """returns (action, option, value) candidates for an option prefix
  212. Returns [first candidate] if all candidates refers to current and
  213. deprecated forms of the same options: "nova boot ... --key KEY"
  214. parsing succeed because --key could only match --key-name,
  215. --key_name which are current/deprecated forms of the same option.
  216. """
  217. option_tuples = (super(NovaClientArgumentParser, self)
  218. ._get_option_tuples(option_string))
  219. if len(option_tuples) > 1:
  220. normalizeds = [option.replace('_', '-')
  221. for action, option, value in option_tuples]
  222. if len(set(normalizeds)) == 1:
  223. return option_tuples[:1]
  224. return option_tuples
  225. class OpenStackComputeShell(object):
  226. times = []
  227. def _append_global_identity_args(self, parser):
  228. # Register the CLI arguments that have moved to the session object.
  229. ksession.Session.register_cli_options(parser)
  230. parser.set_defaults(insecure=cliutils.env('NOVACLIENT_INSECURE',
  231. default=False))
  232. identity.Password.register_argparse_arguments(parser)
  233. parser.set_defaults(os_username=cliutils.env('OS_USERNAME',
  234. 'NOVA_USERNAME'))
  235. parser.set_defaults(os_password=cliutils.env('OS_PASSWORD',
  236. 'NOVA_PASSWORD'))
  237. parser.set_defaults(os_auth_url=cliutils.env('OS_AUTH_URL',
  238. 'NOVA_URL'))
  239. def get_base_parser(self):
  240. parser = NovaClientArgumentParser(
  241. prog='nova',
  242. description=__doc__.strip(),
  243. epilog='See "nova help COMMAND" '
  244. 'for help on a specific command.',
  245. add_help=False,
  246. formatter_class=OpenStackHelpFormatter,
  247. )
  248. # Global arguments
  249. parser.add_argument(
  250. '-h', '--help',
  251. action='store_true',
  252. help=argparse.SUPPRESS,
  253. )
  254. parser.add_argument('--version',
  255. action='version',
  256. version=novaclient.__version__)
  257. parser.add_argument(
  258. '--debug',
  259. default=False,
  260. action='store_true',
  261. help=_("Print debugging output"))
  262. parser.add_argument(
  263. '--os-cache',
  264. default=strutils.bool_from_string(
  265. cliutils.env('OS_CACHE', default=False), True),
  266. action='store_true',
  267. help=_("Use the auth token cache. Defaults to False if "
  268. "env[OS_CACHE] is not set."))
  269. parser.add_argument(
  270. '--timings',
  271. default=False,
  272. action='store_true',
  273. help=_("Print call timing info"))
  274. parser.add_argument(
  275. '--os-auth-token',
  276. default=cliutils.env('OS_AUTH_TOKEN'),
  277. help='Defaults to env[OS_AUTH_TOKEN]')
  278. parser.add_argument(
  279. '--os_username',
  280. help=argparse.SUPPRESS)
  281. parser.add_argument(
  282. '--os_password',
  283. help=argparse.SUPPRESS)
  284. parser.add_argument(
  285. '--os-tenant-name',
  286. metavar='<auth-tenant-name>',
  287. default=cliutils.env('OS_TENANT_NAME', 'NOVA_PROJECT_ID'),
  288. help=_('Defaults to env[OS_TENANT_NAME].'))
  289. parser.add_argument(
  290. '--os_tenant_name',
  291. help=argparse.SUPPRESS)
  292. parser.add_argument(
  293. '--os-tenant-id',
  294. metavar='<auth-tenant-id>',
  295. default=cliutils.env('OS_TENANT_ID'),
  296. help=_('Defaults to env[OS_TENANT_ID].'))
  297. parser.add_argument(
  298. '--os_auth_url',
  299. help=argparse.SUPPRESS)
  300. parser.add_argument(
  301. '--os-region-name',
  302. metavar='<region-name>',
  303. default=cliutils.env('OS_REGION_NAME', 'NOVA_REGION_NAME'),
  304. help=_('Defaults to env[OS_REGION_NAME].'))
  305. parser.add_argument(
  306. '--os_region_name',
  307. help=argparse.SUPPRESS)
  308. parser.add_argument(
  309. '--os-auth-system',
  310. metavar='<auth-system>',
  311. default=cliutils.env('OS_AUTH_SYSTEM'),
  312. help='Defaults to env[OS_AUTH_SYSTEM].')
  313. parser.add_argument(
  314. '--os_auth_system',
  315. help=argparse.SUPPRESS)
  316. parser.add_argument(
  317. '--service-type',
  318. metavar='<service-type>',
  319. help=_('Defaults to compute for most actions'))
  320. parser.add_argument(
  321. '--service_type',
  322. help=argparse.SUPPRESS)
  323. parser.add_argument(
  324. '--service-name',
  325. metavar='<service-name>',
  326. default=cliutils.env('NOVA_SERVICE_NAME'),
  327. help=_('Defaults to env[NOVA_SERVICE_NAME]'))
  328. parser.add_argument(
  329. '--service_name',
  330. help=argparse.SUPPRESS)
  331. parser.add_argument(
  332. '--volume-service-name',
  333. metavar='<volume-service-name>',
  334. default=cliutils.env('NOVA_VOLUME_SERVICE_NAME'),
  335. help=_('Defaults to env[NOVA_VOLUME_SERVICE_NAME]'))
  336. parser.add_argument(
  337. '--volume_service_name',
  338. help=argparse.SUPPRESS)
  339. parser.add_argument(
  340. '--os-endpoint-type',
  341. metavar='<endpoint-type>',
  342. dest='endpoint_type',
  343. default=cliutils.env(
  344. 'NOVA_ENDPOINT_TYPE',
  345. default=cliutils.env(
  346. 'OS_ENDPOINT_TYPE',
  347. default=DEFAULT_NOVA_ENDPOINT_TYPE)),
  348. help=_('Defaults to env[NOVA_ENDPOINT_TYPE], '
  349. 'env[OS_ENDPOINT_TYPE] or ') +
  350. DEFAULT_NOVA_ENDPOINT_TYPE + '.')
  351. parser.add_argument(
  352. '--endpoint-type',
  353. help=argparse.SUPPRESS)
  354. # NOTE(dtroyer): We can't add --endpoint_type here due to argparse
  355. # thinking usage-list --end is ambiguous; but it
  356. # works fine with only --endpoint-type present
  357. # Go figure. I'm leaving this here for doc purposes.
  358. # parser.add_argument('--endpoint_type',
  359. # help=argparse.SUPPRESS)
  360. parser.add_argument(
  361. '--os-compute-api-version',
  362. metavar='<compute-api-ver>',
  363. default=cliutils.env('OS_COMPUTE_API_VERSION',
  364. default=DEFAULT_OS_COMPUTE_API_VERSION),
  365. help=_('Accepts 1.1 or 3, '
  366. 'defaults to env[OS_COMPUTE_API_VERSION].'))
  367. parser.add_argument(
  368. '--os_compute_api_version',
  369. help=argparse.SUPPRESS)
  370. parser.add_argument(
  371. '--bypass-url',
  372. metavar='<bypass-url>',
  373. dest='bypass_url',
  374. default=cliutils.env('NOVACLIENT_BYPASS_URL'),
  375. help="Use this API endpoint instead of the Service Catalog. "
  376. "Defaults to env[NOVACLIENT_BYPASS_URL]")
  377. parser.add_argument('--bypass_url',
  378. help=argparse.SUPPRESS)
  379. # The auth-system-plugins might require some extra options
  380. novaclient.auth_plugin.load_auth_system_opts(parser)
  381. self._append_global_identity_args(parser)
  382. return parser
  383. def get_subcommand_parser(self, version):
  384. parser = self.get_base_parser()
  385. self.subcommands = {}
  386. subparsers = parser.add_subparsers(metavar='<subcommand>')
  387. try:
  388. actions_module = {
  389. '1.1': shell_v2,
  390. '2': shell_v2,
  391. '3': shell_v2,
  392. }[version]
  393. except KeyError:
  394. actions_module = shell_v2
  395. self._find_actions(subparsers, actions_module)
  396. self._find_actions(subparsers, self)
  397. for extension in self.extensions:
  398. self._find_actions(subparsers, extension.module)
  399. self._add_bash_completion_subparser(subparsers)
  400. return parser
  401. def _discover_extensions(self, version):
  402. extensions = []
  403. for name, module in itertools.chain(
  404. self._discover_via_python_path(),
  405. self._discover_via_contrib_path(version),
  406. self._discover_via_entry_points()):
  407. extension = novaclient.extension.Extension(name, module)
  408. extensions.append(extension)
  409. return extensions
  410. def _discover_via_python_path(self):
  411. for (module_loader, name, _ispkg) in pkgutil.iter_modules():
  412. if name.endswith('_python_novaclient_ext'):
  413. if not hasattr(module_loader, 'load_module'):
  414. # Python 2.6 compat: actually get an ImpImporter obj
  415. module_loader = module_loader.find_module(name)
  416. module = module_loader.load_module(name)
  417. if hasattr(module, 'extension_name'):
  418. name = module.extension_name
  419. yield name, module
  420. def _discover_via_contrib_path(self, version):
  421. module_path = os.path.dirname(os.path.abspath(__file__))
  422. version_str = "v%s" % version.replace('.', '_')
  423. # NOTE(akurilin): v1.1, v2 and v3 have one implementation, so
  424. # we should discover contrib modules in one place.
  425. if version_str in ["v1_1", "v3"]:
  426. version_str = "v2"
  427. ext_path = os.path.join(module_path, version_str, 'contrib')
  428. ext_glob = os.path.join(ext_path, "*.py")
  429. for ext_path in glob.iglob(ext_glob):
  430. name = os.path.basename(ext_path)[:-3]
  431. if name == "__init__":
  432. continue
  433. module = imp.load_source(name, ext_path)
  434. yield name, module
  435. def _discover_via_entry_points(self):
  436. for ep in pkg_resources.iter_entry_points('novaclient.extension'):
  437. name = ep.name
  438. module = ep.load()
  439. yield name, module
  440. def _add_bash_completion_subparser(self, subparsers):
  441. subparser = subparsers.add_parser(
  442. 'bash_completion',
  443. add_help=False,
  444. formatter_class=OpenStackHelpFormatter
  445. )
  446. self.subcommands['bash_completion'] = subparser
  447. subparser.set_defaults(func=self.do_bash_completion)
  448. def _find_actions(self, subparsers, actions_module):
  449. for attr in (a for a in dir(actions_module) if a.startswith('do_')):
  450. # I prefer to be hyphen-separated instead of underscores.
  451. command = attr[3:].replace('_', '-')
  452. callback = getattr(actions_module, attr)
  453. desc = callback.__doc__ or ''
  454. action_help = desc.strip()
  455. arguments = getattr(callback, 'arguments', [])
  456. subparser = subparsers.add_parser(
  457. command,
  458. help=action_help,
  459. description=desc,
  460. add_help=False,
  461. formatter_class=OpenStackHelpFormatter)
  462. subparser.add_argument(
  463. '-h', '--help',
  464. action='help',
  465. help=argparse.SUPPRESS,
  466. )
  467. self.subcommands[command] = subparser
  468. for (args, kwargs) in arguments:
  469. subparser.add_argument(*args, **kwargs)
  470. subparser.set_defaults(func=callback)
  471. def setup_debugging(self, debug):
  472. if not debug:
  473. return
  474. streamformat = "%(levelname)s (%(module)s:%(lineno)d) %(message)s"
  475. # Set up the root logger to debug so that the submodules can
  476. # print debug messages
  477. logging.basicConfig(level=logging.DEBUG,
  478. format=streamformat)
  479. def _get_keystone_auth(self, session, auth_url, **kwargs):
  480. auth_token = kwargs.pop('auth_token', None)
  481. if auth_token:
  482. return token.Token(auth_url, auth_token, **kwargs)
  483. else:
  484. return password.Password(
  485. auth_url,
  486. username=kwargs.pop('username'),
  487. user_id=kwargs.pop('user_id'),
  488. password=kwargs.pop('password'),
  489. user_domain_id=kwargs.pop('user_domain_id'),
  490. user_domain_name=kwargs.pop('user_domain_name'),
  491. **kwargs)
  492. def main(self, argv):
  493. # Parse args once to find version and debug settings
  494. parser = self.get_base_parser()
  495. (options, args) = parser.parse_known_args(argv)
  496. self.setup_debugging(options.debug)
  497. # Discover available auth plugins
  498. novaclient.auth_plugin.discover_auth_systems()
  499. # build available subcommands based on version
  500. self.extensions = self._discover_extensions(
  501. options.os_compute_api_version)
  502. self._run_extension_hooks('__pre_parse_args__')
  503. # NOTE(dtroyer): Hackery to handle --endpoint_type due to argparse
  504. # thinking usage-list --end is ambiguous; but it
  505. # works fine with only --endpoint-type present
  506. # Go figure.
  507. if '--endpoint_type' in argv:
  508. spot = argv.index('--endpoint_type')
  509. argv[spot] = '--endpoint-type'
  510. subcommand_parser = self.get_subcommand_parser(
  511. options.os_compute_api_version)
  512. self.parser = subcommand_parser
  513. if options.help or not argv:
  514. subcommand_parser.print_help()
  515. return 0
  516. args = subcommand_parser.parse_args(argv)
  517. self._run_extension_hooks('__post_parse_args__', args)
  518. # Short-circuit and deal with help right away.
  519. if args.func == self.do_help:
  520. self.do_help(args)
  521. return 0
  522. elif args.func == self.do_bash_completion:
  523. self.do_bash_completion(args)
  524. return 0
  525. os_username = args.os_username
  526. os_user_id = args.os_user_id
  527. os_password = None # Fetched and set later as needed
  528. os_tenant_name = args.os_tenant_name
  529. os_tenant_id = args.os_tenant_id
  530. os_auth_url = args.os_auth_url
  531. os_region_name = args.os_region_name
  532. os_auth_system = args.os_auth_system
  533. endpoint_type = args.endpoint_type
  534. insecure = args.insecure
  535. service_type = args.service_type
  536. service_name = args.service_name
  537. volume_service_name = args.volume_service_name
  538. bypass_url = args.bypass_url
  539. os_cache = args.os_cache
  540. cacert = args.os_cacert
  541. timeout = args.timeout
  542. keystone_session = None
  543. keystone_auth = None
  544. # We may have either, both or none of these.
  545. # If we have both, we don't need USERNAME, PASSWORD etc.
  546. # Fill in the blanks from the SecretsHelper if possible.
  547. # Finally, authenticate unless we have both.
  548. # Note if we don't auth we probably don't have a tenant ID so we can't
  549. # cache the token.
  550. auth_token = args.os_auth_token if args.os_auth_token else None
  551. management_url = bypass_url if bypass_url else None
  552. if os_auth_system and os_auth_system != "keystone":
  553. auth_plugin = novaclient.auth_plugin.load_plugin(os_auth_system)
  554. else:
  555. auth_plugin = None
  556. if not endpoint_type:
  557. endpoint_type = DEFAULT_NOVA_ENDPOINT_TYPE
  558. # This allow users to use endpoint_type as (internal, public or admin)
  559. # just like other openstack clients (glance, cinder etc)
  560. if endpoint_type in ['internal', 'public', 'admin']:
  561. endpoint_type += 'URL'
  562. if not service_type:
  563. os_compute_api_version = (options.os_compute_api_version or
  564. DEFAULT_OS_COMPUTE_API_VERSION)
  565. try:
  566. service_type = DEFAULT_NOVA_SERVICE_TYPE_MAP[
  567. os_compute_api_version]
  568. except KeyError:
  569. service_type = DEFAULT_NOVA_SERVICE_TYPE_MAP[
  570. DEFAULT_OS_COMPUTE_API_VERSION]
  571. service_type = cliutils.get_service_type(args.func) or service_type
  572. # If we have an auth token but no management_url, we must auth anyway.
  573. # Expired tokens are handled by client.py:_cs_request
  574. must_auth = not (cliutils.isunauthenticated(args.func)
  575. or (auth_token and management_url))
  576. # Do not use Keystone session for cases with no session support. The
  577. # presence of auth_plugin means os_auth_system is present and is not
  578. # keystone.
  579. use_session = True
  580. if auth_plugin or bypass_url or os_cache or volume_service_name:
  581. use_session = False
  582. # FIXME(usrleon): Here should be restrict for project id same as
  583. # for os_username or os_password but for compatibility it is not.
  584. if must_auth:
  585. if auth_plugin:
  586. auth_plugin.parse_opts(args)
  587. if not auth_plugin or not auth_plugin.opts:
  588. if not os_username and not os_user_id:
  589. raise exc.CommandError(
  590. _("You must provide a username "
  591. "or user id via --os-username, --os-user-id, "
  592. "env[OS_USERNAME] or env[OS_USER_ID]"))
  593. if not any([args.os_tenant_name, args.os_tenant_id,
  594. args.os_project_id, args.os_project_name]):
  595. raise exc.CommandError(_("You must provide a project name or"
  596. " project id via --os-project-name,"
  597. " --os-project-id, env[OS_PROJECT_ID]"
  598. " or env[OS_PROJECT_NAME]. You may"
  599. " use os-project and os-tenant"
  600. " interchangeably."))
  601. if not os_auth_url:
  602. if os_auth_system and os_auth_system != 'keystone':
  603. os_auth_url = auth_plugin.get_auth_url()
  604. if not os_auth_url:
  605. raise exc.CommandError(
  606. _("You must provide an auth url "
  607. "via either --os-auth-url or env[OS_AUTH_URL] "
  608. "or specify an auth_system which defines a "
  609. "default url with --os-auth-system "
  610. "or env[OS_AUTH_SYSTEM]"))
  611. project_id = args.os_project_id or args.os_tenant_id
  612. project_name = args.os_project_name or args.os_tenant_name
  613. if use_session:
  614. # Not using Nova auth plugin, so use keystone
  615. with utils.record_time(self.times, args.timings,
  616. 'auth_url', args.os_auth_url):
  617. keystone_session = (ksession.Session
  618. .load_from_cli_options(args))
  619. keystone_auth = self._get_keystone_auth(
  620. keystone_session,
  621. args.os_auth_url,
  622. username=args.os_username,
  623. user_id=args.os_user_id,
  624. user_domain_id=args.os_user_domain_id,
  625. user_domain_name=args.os_user_domain_name,
  626. password=args.os_password,
  627. auth_token=args.os_auth_token,
  628. project_id=project_id,
  629. project_name=project_name,
  630. project_domain_id=args.os_project_domain_id,
  631. project_domain_name=args.os_project_domain_name)
  632. if (options.os_compute_api_version and
  633. options.os_compute_api_version != '1.0'):
  634. if not any([args.os_tenant_id, args.os_tenant_name,
  635. args.os_project_id, args.os_project_name]):
  636. raise exc.CommandError(_("You must provide a project name or"
  637. " project id via --os-project-name,"
  638. " --os-project-id, env[OS_PROJECT_ID]"
  639. " or env[OS_PROJECT_NAME]. You may"
  640. " use os-project and os-tenant"
  641. " interchangeably."))
  642. if not os_auth_url:
  643. raise exc.CommandError(
  644. _("You must provide an auth url "
  645. "via either --os-auth-url or env[OS_AUTH_URL]"))
  646. self.cs = client.Client(
  647. options.os_compute_api_version,
  648. os_username, os_password, os_tenant_name,
  649. tenant_id=os_tenant_id, user_id=os_user_id,
  650. auth_url=os_auth_url, insecure=insecure,
  651. region_name=os_region_name, endpoint_type=endpoint_type,
  652. extensions=self.extensions, service_type=service_type,
  653. service_name=service_name, auth_system=os_auth_system,
  654. auth_plugin=auth_plugin, auth_token=auth_token,
  655. volume_service_name=volume_service_name,
  656. timings=args.timings, bypass_url=bypass_url,
  657. os_cache=os_cache, http_log_debug=options.debug,
  658. cacert=cacert, timeout=timeout,
  659. session=keystone_session, auth=keystone_auth)
  660. # Now check for the password/token of which pieces of the
  661. # identifying keyring key can come from the underlying client
  662. if must_auth:
  663. helper = SecretsHelper(args, self.cs.client)
  664. if (auth_plugin and auth_plugin.opts and
  665. "os_password" not in auth_plugin.opts):
  666. use_pw = False
  667. else:
  668. use_pw = True
  669. tenant_id = helper.tenant_id
  670. # Allow commandline to override cache
  671. if not auth_token:
  672. auth_token = helper.auth_token
  673. if not management_url:
  674. management_url = helper.management_url
  675. if tenant_id and auth_token and management_url:
  676. self.cs.client.tenant_id = tenant_id
  677. self.cs.client.auth_token = auth_token
  678. self.cs.client.management_url = management_url
  679. self.cs.client.password_func = lambda: helper.password
  680. elif use_pw:
  681. # We're missing something, so auth with user/pass and save
  682. # the result in our helper.
  683. self.cs.client.password = helper.password
  684. self.cs.client.keyring_saver = helper
  685. try:
  686. # This does a couple of bits which are useful even if we've
  687. # got the token + service URL already. It exits fast in that case.
  688. if not cliutils.isunauthenticated(args.func):
  689. if not use_session:
  690. # Only call authenticate() if Nova auth plugin is used.
  691. # If keystone is used, authentication is handled as part
  692. # of session.
  693. self.cs.authenticate()
  694. except exc.Unauthorized:
  695. raise exc.CommandError(_("Invalid OpenStack Nova credentials."))
  696. except exc.AuthorizationFailure:
  697. raise exc.CommandError(_("Unable to authorize user"))
  698. if options.os_compute_api_version == "3" and service_type != 'image':
  699. # NOTE(cyeoh): create an image based client because the
  700. # images api is no longer proxied by the V3 API and we
  701. # sometimes need to be able to look up images information
  702. # via glance when connected to the nova api.
  703. image_service_type = 'image'
  704. # NOTE(hdd): the password is needed again because creating a new
  705. # Client without specifying bypass_url will force authentication.
  706. # We can't reuse self.cs's bypass_url, because that's the URL for
  707. # the nova service; we need to get glance's URL for this Client
  708. if not os_password:
  709. os_password = helper.password
  710. self.cs.image_cs = client.Client(
  711. options.os_compute_api_version, os_username,
  712. os_password, os_tenant_name, tenant_id=os_tenant_id,
  713. auth_url=os_auth_url, insecure=insecure,
  714. region_name=os_region_name, endpoint_type=endpoint_type,
  715. extensions=self.extensions, service_type=image_service_type,
  716. service_name=service_name, auth_system=os_auth_system,
  717. auth_plugin=auth_plugin,
  718. volume_service_name=volume_service_name,
  719. timings=args.timings, bypass_url=bypass_url,
  720. os_cache=os_cache, http_log_debug=options.debug,
  721. session=keystone_session, auth=keystone_auth,
  722. cacert=cacert, timeout=timeout)
  723. args.func(self.cs, args)
  724. if args.timings:
  725. self._dump_timings(self.times + self.cs.get_timings())
  726. def _dump_timings(self, timings):
  727. class Tyme(object):
  728. def __init__(self, url, seconds):
  729. self.url = url
  730. self.seconds = seconds
  731. results = [Tyme(url, end - start) for url, start, end in timings]
  732. total = 0.0
  733. for tyme in results:
  734. total += tyme.seconds
  735. results.append(Tyme("Total", total))
  736. utils.print_list(results, ["url", "seconds"], sortby_index=None)
  737. def _run_extension_hooks(self, hook_type, *args, **kwargs):
  738. """Run hooks for all registered extensions."""
  739. for extension in self.extensions:
  740. extension.run_hooks(hook_type, *args, **kwargs)
  741. def do_bash_completion(self, _args):
  742. """
  743. Prints all of the commands and options to stdout so that the
  744. nova.bash_completion script doesn't have to hard code them.
  745. """
  746. commands = set()
  747. options = set()
  748. for sc_str, sc in self.subcommands.items():
  749. commands.add(sc_str)
  750. for option in sc._optionals._option_string_actions.keys():
  751. options.add(option)
  752. commands.remove('bash-completion')
  753. commands.remove('bash_completion')
  754. print(' '.join(commands | options))
  755. @cliutils.arg(
  756. 'command',
  757. metavar='<subcommand>',
  758. nargs='?',
  759. help='Display help for <subcommand>')
  760. def do_help(self, args):
  761. """
  762. Display help about this program or one of its subcommands.
  763. """
  764. if args.command:
  765. if args.command in self.subcommands:
  766. self.subcommands[args.command].print_help()
  767. else:
  768. raise exc.CommandError(_("'%s' is not a valid subcommand") %
  769. args.command)
  770. else:
  771. self.parser.print_help()
  772. # I'm picky about my shell help.
  773. class OpenStackHelpFormatter(argparse.HelpFormatter):
  774. def __init__(self, prog, indent_increment=2, max_help_position=32,
  775. width=None):
  776. super(OpenStackHelpFormatter, self).__init__(prog, indent_increment,
  777. max_help_position, width)
  778. def start_section(self, heading):
  779. # Title-case the headings
  780. heading = '%s%s' % (heading[0].upper(), heading[1:])
  781. super(OpenStackHelpFormatter, self).start_section(heading)
  782. def main():
  783. try:
  784. argv = [encodeutils.safe_decode(a) for a in sys.argv[1:]]
  785. OpenStackComputeShell().main(argv)
  786. except Exception as e:
  787. logger.debug(e, exc_info=1)
  788. details = {'name': encodeutils.safe_encode(e.__class__.__name__),
  789. 'msg': encodeutils.safe_encode(six.text_type(e))}
  790. print("ERROR (%(name)s): %(msg)s" % details,
  791. file=sys.stderr)
  792. sys.exit(1)
  793. except KeyboardInterrupt:
  794. print("... terminating nova client", file=sys.stderr)
  795. sys.exit(130)
  796. if __name__ == "__main__":
  797. main()