def test_client_manager_password(self, mock):

        client_manager = clientmanager.ClientManager(
            auth_url=AUTH_URL,
            username=USERNAME,
            password=PASSWORD,
            verify=False,
            api_version=API_VERSION,
        )

        self.assertEqual(
            AUTH_URL,
            client_manager._auth_url,
        )
        self.assertEqual(
            USERNAME,
            client_manager._username,
        )
        self.assertEqual(
            PASSWORD,
            client_manager._password,
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_v2.Password,
        )
        self.assertTrue(client_manager._insecure)
        self.assertFalse(client_manager._verify)
示例#2
0
    def test_client_manager_token_endpoint(self):

        client_manager = clientmanager.ClientManager(cli_options=FakeOptions(
            auth_type='token_endpoint',
            auth=dict(
                token=fakes.AUTH_TOKEN,
                url=fakes.AUTH_URL,
            ),
        ),
                                                     api_version=API_VERSION,
                                                     verify=True)
        client_manager.setup_auth()

        self.assertEqual(
            fakes.AUTH_URL,
            client_manager._url,
        )
        self.assertEqual(
            fakes.AUTH_TOKEN,
            client_manager.auth.get_token(None),
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_plugin.TokenEndpoint,
        )
        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
    def test_client_manager_token(self):

        client_manager = clientmanager.ClientManager(cli_options=FakeOptions(
            auth=dict(
                token=fakes.AUTH_TOKEN,
                auth_url=fakes.AUTH_URL,
            ),
            auth_type='v2token',
            interface=fakes.INTERFACE,
            region_name=fakes.REGION_NAME,
        ),
                                                     api_version=API_VERSION,
                                                     verify=True)
        client_manager.setup_auth()
        client_manager.auth_ref

        self.assertEqual(
            fakes.AUTH_URL,
            client_manager._auth_url,
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_v2.Token,
        )
        self.assertEqual(
            fakes.INTERFACE,
            client_manager._interface,
        )
        self.assertEqual(
            fakes.REGION_NAME,
            client_manager._region_name,
        )
        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
        self.assertTrue(client_manager.is_network_endpoint_enabled())
示例#4
0
    def initialize_app(self, argv):
        super(OpenStackShell, self).initialize_app(argv)

        # Argument precedence is really broken in multiple places
        # so we're just going to fix it here until o-c-c and osc-lib
        # get sorted out.
        # TODO(dtroyer): remove when os-client-config and osc-lib are fixed

        # First, throw away what has already been done with o-c-c and
        # use our own.
        try:
            cc = cloud_config.OSC_Config(override_defaults={
                'interface': None,
                'auth_type': self._auth_type,
            }, )
        except (IOError, OSError) as e:
            self.log.critical("Could not read clouds.yaml configuration file")
            self.print_help_if_requested()
            raise e

        if not self.options.debug:
            self.options.debug = None
        self.cloud = cc.get_one_cloud(
            cloud=self.options.cloud,
            argparse=self.options,
        )

        # Then, re-create the client_manager with the correct arguments
        self.client_manager = clientmanager.ClientManager(
            cli_options=self.cloud,
            api_version=self.api_version,
            pw_func=shell.prompt_for_password,
        )
示例#5
0
    def initialize_app(self, argv):
        super(OpenStackShell, self).initialize_app(argv)

        # Re-create the client_manager with our subclass
        self.client_manager = clientmanager.ClientManager(
            cli_options=self.cloud,
            api_version=self.api_version,
            pw_func=shell.prompt_for_password,
        )
示例#6
0
 def test_client_manager_select_auth_plugin_failure(self):
     client_manager = clientmanager.ClientManager(
         cli_options=FakeOptions(os_auth_plugin=''),
         api_version=API_VERSION,
         verify=True,
     )
     self.assertRaises(
         exc.CommandError,
         client_manager.setup_auth,
     )
    def setUp(self):
        super(TestImage, self).setUp()

        api_version = {"image": "2"}

        image_client.API_VERSIONS = {"2": "tests.image.test_image.FakeClient"}

        self.cm = clientmanager.ClientManager(token=AUTH_TOKEN,
                                              url=AUTH_URL,
                                              auth_url=AUTH_URL,
                                              api_version=api_version)
示例#8
0
 def _select_auth_plugin(self, auth_params, api_version, auth_plugin_name):
     auth_params['os_auth_type'] = auth_plugin_name
     auth_params['os_identity_api_version'] = api_version
     client_manager = clientmanager.ClientManager(
         auth_options=FakeOptions(**auth_params),
         api_version=API_VERSION,
         verify=True)
     self.assertEqual(
         auth_plugin_name,
         client_manager.auth_plugin_name,
     )
    def setUp(self):
        super(TestClientManager, self).setUp()

        api_version = {"identity": "2.0"}

        self.client_manager = clientmanager.ClientManager(
            token=AUTH_TOKEN,
            url=AUTH_URL,
            auth_url=AUTH_URL,
            api_version=api_version,
        )
    def get_client_manager(cloud):

        api_version = {
            "identity": "3",
            "compute": "2",
            "volume": "2",
            "network": "2"
        }
        return clientmanager.ClientManager(
            cli_options=cloud,
            api_version=api_version,
        )
示例#11
0
    def setUp(self):
        super(TestIdentity, self).setUp()

        api_version = {"identity": "2.0"}

        identity_client.API_VERSIONS = {
            "2.0": "openstackclient.tests.identity.test_identity.FakeClient"
        }

        self.cm = clientmanager.ClientManager(token=AUTH_TOKEN,
                                              url=AUTH_URL,
                                              auth_url=AUTH_URL,
                                              api_version=api_version)
    def test_client_manager_password_verify_ca(self, mock):

        client_manager = clientmanager.ClientManager(
            auth_url=AUTH_URL,
            username=USERNAME,
            password=PASSWORD,
            verify='cafile',
            api_version=API_VERSION,
        )

        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
        self.assertEqual('cafile', client_manager._cacert)
    def setUp(self):
        super(TestCompute, self).setUp()

        api_version = {"compute": "2"}

        compute_client.API_VERSIONS = {
            "2": "openstackclient.tests.compute.test_compute.FakeClient"
        }

        self.cm = clientmanager.ClientManager(token=AUTH_TOKEN,
                                              url=AUTH_URL,
                                              auth_url=AUTH_URL,
                                              api_version=api_version)
示例#14
0
    def setUp(self):
        super(TestVolume, self).setUp()

        api_version = {"volume": "1"}

        volume_client.API_VERSIONS = {
            "1": "openstackclient.tests.volume.test_volume.FakeClient"
        }

        self.cm = clientmanager.ClientManager(token=AUTH_TOKEN,
                                              url=AUTH_URL,
                                              auth_url=AUTH_URL,
                                              api_version=api_version)
示例#15
0
    def test_client_manager_password_verify_ca(self):

        client_manager = clientmanager.ClientManager(
            auth_options=FakeOptions(os_auth_url=fakes.AUTH_URL,
                                     os_username=fakes.USERNAME,
                                     os_password=fakes.PASSWORD,
                                     os_auth_type='v2password'),
            api_version=API_VERSION,
            verify='cafile',
        )

        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
        self.assertEqual('cafile', client_manager._cacert)
    def test_client_manager_password(self):

        client_manager = clientmanager.ClientManager(
            cli_options=FakeOptions(auth=dict(
                auth_url=fakes.AUTH_URL,
                username=fakes.USERNAME,
                password=fakes.PASSWORD,
                project_name=fakes.PROJECT_NAME,
            ), ),
            api_version=API_VERSION,
            verify=False,
        )
        client_manager.setup_auth()
        client_manager.auth_ref

        self.assertEqual(
            fakes.AUTH_URL,
            client_manager._auth_url,
        )
        self.assertEqual(
            fakes.USERNAME,
            client_manager._username,
        )
        self.assertEqual(
            fakes.PASSWORD,
            client_manager._password,
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_v2.Password,
        )
        self.assertTrue(client_manager._insecure)
        self.assertFalse(client_manager._verify)

        # These need to stick around until the old-style clients are gone
        self.assertEqual(
            AUTH_REF,
            client_manager.auth_ref,
        )
        self.assertEqual(
            dir(SERVICE_CATALOG),
            dir(client_manager.auth_ref.service_catalog),
        )
        self.assertTrue(client_manager.is_network_endpoint_enabled())
示例#17
0
    def test_client_manager_token(self):

        client_manager = clientmanager.ClientManager(auth_options=FakeOptions(
            os_token=fakes.AUTH_TOKEN,
            os_auth_url=fakes.AUTH_URL,
            os_auth_type='v2token'),
                                                     api_version=API_VERSION,
                                                     verify=True)

        self.assertEqual(
            fakes.AUTH_URL,
            client_manager._auth_url,
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_v2.Token,
        )
        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
    def test_client_manager_network_endpoint_disabled(self):

        client_manager = clientmanager.ClientManager(
            cli_options=FakeOptions(
                auth=dict(
                    auth_url=fakes.AUTH_URL,
                    username=fakes.USERNAME,
                    password=fakes.PASSWORD,
                    project_name=fakes.PROJECT_NAME,
                ),
                auth_type='v3password',
            ),
            api_version={"identity": "3"},
            verify=False,
        )
        client_manager.setup_auth()
        client_manager.auth_ref

        # v3 fake doesn't have network endpoint.
        self.assertFalse(client_manager.is_network_endpoint_enabled())
示例#19
0
    def test_client_manager_password_verify_ca(self):

        client_manager = clientmanager.ClientManager(
            cli_options=FakeOptions(
                auth=dict(
                    auth_url=fakes.AUTH_URL,
                    username=fakes.USERNAME,
                    password=fakes.PASSWORD,
                    project_name=fakes.PROJECT_NAME,
                ),
                auth_type='v2password',
            ),
            api_version=API_VERSION,
            verify='cafile',
        )
        client_manager.setup_auth()

        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
        self.assertEqual('cafile', client_manager._cacert)
    def test_client_manager_auth_setup_once(self, check_auth_options_func):
        client_manager = clientmanager.ClientManager(
            cli_options=FakeOptions(auth=dict(
                auth_url=fakes.AUTH_URL,
                username=fakes.USERNAME,
                password=fakes.PASSWORD,
                project_name=fakes.PROJECT_NAME,
            ), ),
            api_version=API_VERSION,
            verify=False,
        )
        self.assertFalse(client_manager._auth_setup_completed)
        client_manager.setup_auth()
        self.assertTrue(check_auth_options_func.called)
        self.assertTrue(client_manager._auth_setup_completed)

        # now make sure we don't do auth setup the second time around
        # by checking whether check_valid_auth_options() gets called again
        check_auth_options_func.reset_mock()
        client_manager.auth_ref
        check_auth_options_func.assert_not_called()
示例#21
0
    def test_client_manager_password(self):

        client_manager = clientmanager.ClientManager(
            auth_options=FakeOptions(os_auth_url=fakes.AUTH_URL,
                                     os_username=fakes.USERNAME,
                                     os_password=fakes.PASSWORD),
            api_version=API_VERSION,
            verify=False,
        )

        self.assertEqual(
            fakes.AUTH_URL,
            client_manager._auth_url,
        )
        self.assertEqual(
            fakes.USERNAME,
            client_manager._username,
        )
        self.assertEqual(
            fakes.PASSWORD,
            client_manager._password,
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_v2.Password,
        )
        self.assertTrue(client_manager._insecure)
        self.assertFalse(client_manager._verify)

        # These need to stick around until the old-style clients are gone
        self.assertEqual(
            AUTH_REF,
            client_manager.auth_ref,
        )
        self.assertEqual(
            dir(SERVICE_CATALOG),
            dir(client_manager.auth_ref.service_catalog),
        )
    def test_client_manager_token(self, mock):

        client_manager = clientmanager.ClientManager(
            token=AUTH_TOKEN,
            url=AUTH_URL,
            verify=True,
            api_version=API_VERSION,
        )

        self.assertEqual(
            AUTH_TOKEN,
            client_manager._token,
        )
        self.assertEqual(
            AUTH_URL,
            client_manager._url,
        )
        self.assertIsInstance(
            client_manager.auth,
            auth_v2.Token,
        )
        self.assertFalse(client_manager._insecure)
        self.assertTrue(client_manager._verify)
def run(opts):
    """Run the examples"""

    # Do configuration file handling
    cc = cloud_config.OpenStackConfig()
    LOG.debug("defaults: %s", cc.defaults)

    cloud = cc.get_one_cloud(
        cloud=opts.cloud,
        argparse=opts,
    )
    LOG.debug("cloud cfg: %s", cloud.config)

    # Loop through extensions to get API versions
    # Currently API versions are statically selected.  Once discovery
    # is working this can go away...
    api_version = {}
    for mod in clientmanager.PLUGIN_MODULES:
        version_opt = getattr(opts, mod.API_VERSION_OPTION, None)
        if version_opt:
            api = mod.API_NAME
            api_version[api] = version_opt

    # Set up certificate verification and CA bundle
    # NOTE(dtroyer): This converts from the usual OpenStack way to the single
    #                requests argument and is an app-specific thing because
    #                we want to be like OpenStackClient.
    if opts.cacert:
        verify = opts.cacert
    else:
        verify = not opts.insecure

    # Get a ClientManager
    # Collect the auth and config options together and give them to
    # ClientManager and it will wrangle all of the goons into place.
    client_manager = clientmanager.ClientManager(
        cli_options=cloud,
        verify=verify,
        api_version=api_version,
    )

    # At this point we have a working client manager with a configured
    # session and authentication plugin.  From here on it is the app
    # making the decisions.  Need to talk to two clouds?  Make another
    # client manager with different opts.  Or use a config file and load it
    # directly into the plugin.  This example doesn't show that (yet).

    # Do useful things with it

    # Look in the object store
    c_list = client_manager.object_store.container_list()
    print("Name\tCount\tBytes")
    for c in c_list:
        print("%s\t%d\t%d" % (c['name'], c['count'], c['bytes']))

    if len(c_list) > 0:
        # See what is in the first container
        o_list = client_manager.object_store.object_list(c_list[0]['name'])
        print("\nObject")
        for o in o_list:
            print("%s" % o)

    # Look at the compute flavors
    flavor_list = client_manager.compute.flavors.list()
    print("\nFlavors:")
    for f in flavor_list:
        print("%s" % f)
示例#24
0
 def test_client_manager_password_client_cert_and_key(self):
     client_manager = clientmanager.ClientManager(
         cli_options=FakeOptions(cert='cert', key='key'))
     self.assertEqual(('cert', 'key'), client_manager._cert)
示例#25
0
    def authenticate_user(self):
        """Verify the required authentication credentials are present"""

        self.log.debug('validating authentication options')
        if self.options.os_token or self.options.os_url:
            # Token flow auth takes priority
            if not self.options.os_token:
                raise exc.CommandError("You must provide a token via"
                                       " either --os-token or env[OS_TOKEN]")

            if not self.options.os_url:
                raise exc.CommandError("You must provide a service URL via"
                                       " either --os-url or env[OS_URL]")

        else:
            # Validate password flow auth
            if not self.options.os_username:
                raise exc.CommandError(
                    "You must provide a username via"
                    " either --os-username or env[OS_USERNAME]")

            if not self.options.os_password:
                # No password, if we've got a tty, try prompting for it
                if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
                    # Check for Ctl-D
                    try:
                        self.options.os_password = getpass.getpass()
                    except EOFError:
                        pass
                # No password because we did't have a tty or the
                # user Ctl-D when prompted?
                if not self.options.os_password:
                    raise exc.CommandError(
                        "You must provide a password via"
                        " either --os-password, or env[OS_PASSWORD], "
                        " or prompted response")

            if not (
                (self.options.os_project_id or self.options.os_project_name) or
                (self.options.os_domain_id or self.options.os_domain_name)
                    or self.options.os_trust_id):
                raise exc.CommandError(
                    "You must provide authentication scope as a project "
                    "or a domain via --os-project-id or env[OS_PROJECT_ID], "
                    "--os-project-name or env[OS_PROJECT_NAME], "
                    "--os-domain-id or env[OS_DOMAIN_ID], or"
                    "--os-domain-name or env[OS_DOMAIN_NAME], or "
                    "--os-trust-id or env[OS_TRUST_ID].")

            if not self.options.os_auth_url:
                raise exc.CommandError(
                    "You must provide an auth url via"
                    " either --os-auth-url or via env[OS_AUTH_URL]")

            if (self.options.os_trust_id
                    and self.options.os_identity_api_version != '3'):
                raise exc.CommandError(
                    "Trusts can only be used with Identity API v3")

            if (self.options.os_trust_id and (
                (self.options.os_project_id or self.options.os_project_name) or
                (self.options.os_domain_id or self.options.os_domain_name))):
                raise exc.CommandError(
                    "Authentication cannot be scoped to multiple targets. "
                    "Pick one of project, domain or trust.")

        self.client_manager = clientmanager.ClientManager(
            token=self.options.os_token,
            url=self.options.os_url,
            auth_url=self.options.os_auth_url,
            domain_id=self.options.os_domain_id,
            domain_name=self.options.os_domain_name,
            project_name=self.options.os_project_name,
            project_id=self.options.os_project_id,
            user_domain_id=self.options.os_user_domain_id,
            user_domain_name=self.options.os_user_domain_name,
            project_domain_id=self.options.os_project_domain_id,
            project_domain_name=self.options.os_project_domain_name,
            username=self.options.os_username,
            password=self.options.os_password,
            region_name=self.options.os_region_name,
            verify=self.verify,
            timing=self.options.timing,
            api_version=self.api_version,
            trust_id=self.options.os_trust_id,
        )
        return
示例#26
0
    def initialize_app(self, argv):
        """Global app init bits:

        * set up API versions
        * validate authentication info
        * authenticate against Identity if requested
        """

        super(OpenStackShell, self).initialize_app(argv)

        # Save default domain
        self.default_domain = self.options.os_default_domain

        # Loop through extensions to get API versions
        for mod in clientmanager.PLUGIN_MODULES:
            version_opt = getattr(self.options, mod.API_VERSION_OPTION, None)
            if version_opt:
                api = mod.API_NAME
                self.api_version[api] = version_opt
                version = '.v' + version_opt.replace('.', '_')
                cmd_group = 'openstack.' + api.replace('-', '_') + version
                self.command_manager.add_command_group(cmd_group)
                self.log.debug(
                    '%(name)s API version %(version)s, cmd group %(group)s', {
                        'name': api,
                        'version': version_opt,
                        'group': cmd_group
                    })

        # Commands that span multiple APIs
        self.command_manager.add_command_group('openstack.common')

        # This is the naive extension implementation referred to in
        # blueprint 'client-extensions'
        # Extension modules can register their commands in an
        # 'openstack.extension' entry point group:
        # entry_points={
        #     'openstack.extension': [
        #         'list_repo=qaz.github.repo:ListRepo',
        #         'show_repo=qaz.github.repo:ShowRepo',
        #     ],
        # }
        self.command_manager.add_command_group('openstack.extension')
        # call InitializeXxx() here
        # set up additional clients to stuff in to client_manager??

        # Handle deferred help and exit
        if self.options.deferred_help:
            self.DeferredHelpAction(self.parser, self.parser, None, None)

        # Set up common client session
        if self.options.os_cacert:
            self.verify = self.options.os_cacert
        else:
            self.verify = not self.options.insecure

        self.client_manager = clientmanager.ClientManager(
            auth_options=self.options,
            verify=self.verify,
            api_version=self.api_version,
            pw_func=prompt_for_password,
        )
示例#27
0
    def authenticate_user(self):
        """Make sure the user has provided all of the authentication
        info we need.
        """
        self.log.debug('validating authentication options')
        if self.options.os_token or self.options.os_url:
            # Token flow auth takes priority
            if not self.options.os_token:
                raise exc.CommandError(
                    "You must provide a token via"
                    " either --os-token or env[OS_TOKEN]")

            if not self.options.os_url:
                raise exc.CommandError(
                    "You must provide a service URL via"
                    " either --os-url or env[OS_URL]")

        else:
            # Validate password flow auth
            if not self.options.os_username:
                raise exc.CommandError(
                    "You must provide a username via"
                    " either --os-username or env[OS_USERNAME]")

            self.get_password_from_keyring()
            if not self.options.os_password:
                # No password, if we've got a tty, try prompting for it
                if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
                    # Check for Ctl-D
                    try:
                        self.options.os_password = getpass.getpass()
                        self.set_password_in_keyring()
                    except EOFError:
                        pass
                # No password because we did't have a tty or the
                # user Ctl-D when prompted?
                if not self.options.os_password:
                    raise exc.CommandError(
                        "You must provide a password via"
                        " either --os-password, or env[OS_PASSWORD], "
                        " or prompted response")

            if not (self.options.os_tenant_id or self.options.os_tenant_name):
                raise exc.CommandError(
                    "You must provide a tenant_id via"
                    " either --os-tenant-id or via env[OS_TENANT_ID]")

            if not self.options.os_auth_url:
                raise exc.CommandError(
                    "You must provide an auth url via"
                    " either --os-auth-url or via env[OS_AUTH_URL]")

        self.client_manager = clientmanager.ClientManager(
            token=self.options.os_token,
            url=self.options.os_url,
            auth_url=self.options.os_auth_url,
            tenant_name=self.options.os_tenant_name,
            tenant_id=self.options.os_tenant_id,
            username=self.options.os_username,
            password=self.options.os_password,
            region_name=self.options.os_region_name,
            api_version=self.api_version,
            )
        return
示例#28
0
from argparse import Namespace

opts=Namespace(access_token_endpoint='', auth_type='', auth_url='http://192.168.122.218:5000/v3', cacert='', client_id='', client_secret='', cloud='', debug=False, domain_id='', domain_name='', endpoint='', identity_provider='', insecure=False, os_compute_api_version='2', os_default_domain='default', os_identity_api_version='3', os_image_api_version='2', os_network_api_version='2', os_object_api_version='', os_project_id=None, os_project_name=None, os_volume_api_version='2', password='******', project_domain_id='default', project_domain_name='', project_id='', project_name='admin', protocol='', region_name='', rest=[], scope='', timing=False, token='', trust_id='', url='', user_domain_id='default', user_domain_name='', user_id='', username='******', verbose_level=1, verify=False)

cc = cloud_config.OpenStackConfig()

cloud = cc.get_one_cloud(cloud=opts.cloud,argparse=opts,)

api_version={}
for mod in clientmanager.PLUGIN_MODULES:
  version_opt = getattr(opts, mod.API_VERSION_OPTION, None)
  if version_opt:
    api = mod.API_NAME
    api_version[api] = version_opt

client_manager = clientmanager.ClientManager(cli_options=cloud,api_version=api_version,)
client_manager.setup_auth()
client_manager.auth_ref


'''
client_manager.identity.users.get(self, user)
client_manager.identity.users.list(self, project=None, domain=None, group=None, default_project=None, **kwargs)
client_manager.identity.users.create(self, name, domain=None, project=None, password=None, email=None, description=None, enabled=True, default_project=None, **kwargs)
client_manager.identity.users.update(self, user, name=None, domain=None, project=None, password=None, email=None, description=None, enabled=None, default_project=None, **kwargs)
client_manager.identity.users.delete(self, user)

client_manager.identity.projects.get(self, project, subtree_as_list=False, parents_as_list=False, subtree_as_ids=False, parents_as_ids=False)
client_manager.identity.projects.list(self, domain=None, user=None, **kwargs)
client_manager.identity.projects.create(self, name, domain, description=None, enabled=True, parent=None, **kwargs)
client_manager.identity.projects.update(self, project, name=None, domain=None, description=None, enabled=None, **kwargs)
    def initialize_app(self, argv):
        """Global app init bits:

        * set up API versions
        * validate authentication info
        * authenticate against Identity if requested
        """

        # Parent __init__ parses argv into self.options
        super(OpenStackShell, self).initialize_app(argv)
        self.log.info("START with options: %s",
                      strutils.mask_password(self.command_options))
        self.log.debug("options: %s", strutils.mask_password(self.options))

        # Set the default plugin to token_endpoint if url and token are given
        if (self.options.url and self.options.token):
            # Use service token authentication
            auth_type = 'token_endpoint'
        else:
            auth_type = 'password'

        project_id = getattr(self.options, 'project_id', None)
        project_name = getattr(self.options, 'project_name', None)
        tenant_id = getattr(self.options, 'tenant_id', None)
        tenant_name = getattr(self.options, 'tenant_name', None)

        # handle some v2/v3 authentication inconsistencies by just acting like
        # both the project and tenant information are both present. This can
        # go away if we stop registering all the argparse options together.
        if project_id and not tenant_id:
            self.options.tenant_id = project_id
        if project_name and not tenant_name:
            self.options.tenant_name = project_name
        if tenant_id and not project_id:
            self.options.project_id = tenant_id
        if tenant_name and not project_name:
            self.options.project_name = tenant_name

        # Do configuration file handling
        # Ignore the default value of interface. Only if it is set later
        # will it be used.
        cc = cloud_config.OpenStackConfig(override_defaults={
            'interface': None,
            'auth_type': auth_type,
        }, )

        # TODO(thowe): Change cliff so the default value for debug
        # can be set to None.
        if not self.options.debug:
            self.options.debug = None
        self.cloud = cc.get_one_cloud(
            cloud=self.options.cloud,
            argparse=self.options,
        )

        self.log_configurator.configure(self.cloud)
        self.dump_stack_trace = self.log_configurator.dump_trace
        self.log.debug("defaults: %s", cc.defaults)
        self.log.debug("cloud cfg: %s",
                       strutils.mask_password(self.cloud.config))

        # Set up client TLS
        # NOTE(dtroyer): --insecure is the non-default condition that
        #                overrides any verify setting in clouds.yaml
        #                so check it first, then fall back to any verify
        #                setting provided.
        self.verify = not self.cloud.config.get(
            'insecure',
            not self.cloud.config.get('verify', True),
        )

        # NOTE(dtroyer): Per bug https://bugs.launchpad.net/bugs/1447784
        #                --insecure now overrides any --os-cacert setting,
        #                where before --insecure was ignored if --os-cacert
        #                was set.
        if self.verify and self.cloud.cacert:
            self.verify = self.cloud.cacert

        # Save default domain
        self.default_domain = self.options.default_domain

        # Loop through extensions to get API versions
        for mod in clientmanager.PLUGIN_MODULES:
            default_version = getattr(mod, 'DEFAULT_API_VERSION', None)
            option = mod.API_VERSION_OPTION.replace('os_', '')
            version_opt = str(self.cloud.config.get(option, default_version))
            if version_opt:
                api = mod.API_NAME
                self.api_version[api] = version_opt

                # Add a plugin interface to let the module validate the version
                # requested by the user
                skip_old_check = False
                mod_check_api_version = getattr(mod, 'check_api_version', None)
                if mod_check_api_version:
                    # this throws an exception if invalid
                    skip_old_check = mod_check_api_version(version_opt)

                mod_versions = getattr(mod, 'API_VERSIONS', None)
                if not skip_old_check and mod_versions:
                    if version_opt not in mod_versions:
                        self.log.warning(
                            "%s version %s is not in supported versions %s" %
                            (api, version_opt, ', '.join(
                                mod.API_VERSIONS.keys())))

                # Command groups deal only with major versions
                version = '.v' + version_opt.replace('.', '_').split('_')[0]
                cmd_group = 'openstack.' + api.replace('-', '_') + version
                self.command_manager.add_command_group(cmd_group)
                self.log.debug(
                    '%(name)s API version %(version)s, cmd group %(group)s', {
                        'name': api,
                        'version': version_opt,
                        'group': cmd_group
                    })

        # Commands that span multiple APIs
        self.command_manager.add_command_group('openstack.common')

        # This is the naive extension implementation referred to in
        # blueprint 'client-extensions'
        # Extension modules can register their commands in an
        # 'openstack.extension' entry point group:
        # entry_points={
        #     'openstack.extension': [
        #         'list_repo=qaz.github.repo:ListRepo',
        #         'show_repo=qaz.github.repo:ShowRepo',
        #     ],
        # }
        self.command_manager.add_command_group('openstack.extension')
        # call InitializeXxx() here
        # set up additional clients to stuff in to client_manager??

        # Handle deferred help and exit
        self.print_help_if_requested()

        self.client_manager = clientmanager.ClientManager(
            cli_options=self.cloud,
            verify=self.verify,
            api_version=self.api_version,
            pw_func=prompt_for_password,
        )
示例#30
0
    def authenticate_user(self):
        """Verify the required authentication credentials are present"""

        self.log.debug("validating authentication options")

        # Assuming all auth plugins will be named in the same fashion,
        # ie vXpluginName
        if (not self.options.os_url
                and self.options.os_auth_plugin.startswith('v')
                and self.options.os_auth_plugin[1] !=
                self.options.os_identity_api_version[0]):
            raise exc.CommandError("Auth plugin %s not compatible"
                                   " with requested API version" %
                                   self.options.os_auth_plugin)
        # TODO(mhu) All these checks should be exposed at the plugin level
        # or just dropped altogether, as the client instantiation will fail
        # anyway
        if self.options.os_url and not self.options.os_token:
            # service token needed
            raise exc.CommandError("You must provide a service token via"
                                   " either --os-token or env[OS_TOKEN]")

        if (self.options.os_auth_plugin.endswith('token')
                and (self.options.os_token or self.options.os_auth_url)):
            # Token flow auth takes priority
            if not self.options.os_token:
                raise exc.CommandError("You must provide a token via"
                                       " either --os-token or env[OS_TOKEN]")

            if not self.options.os_auth_url:
                raise exc.CommandError(
                    "You must provide a service URL via"
                    " either --os-auth-url or env[OS_AUTH_URL]")

        if (not self.options.os_url
                and not self.options.os_auth_plugin.endswith('token')):
            # Validate password flow auth
            if not self.options.os_username:
                raise exc.CommandError(
                    "You must provide a username via"
                    " either --os-username or env[OS_USERNAME]")

            if not self.options.os_password:
                # No password, if we've got a tty, try prompting for it
                if hasattr(sys.stdin, 'isatty') and sys.stdin.isatty():
                    # Check for Ctl-D
                    try:
                        self.options.os_password = getpass.getpass()
                    except EOFError:
                        pass
                # No password because we did't have a tty or the
                # user Ctl-D when prompted?
                if not self.options.os_password:
                    raise exc.CommandError(
                        "You must provide a password via"
                        " either --os-password, or env[OS_PASSWORD], "
                        " or prompted response")

            if not (
                (self.options.os_project_id or self.options.os_project_name) or
                (self.options.os_domain_id or self.options.os_domain_name)
                    or self.options.os_trust_id):
                if self.options.os_auth_plugin.endswith('password'):
                    raise exc.CommandError(
                        "You must provide authentication scope as a project "
                        "or a domain via --os-project-id "
                        "or env[OS_PROJECT_ID], "
                        "--os-project-name or env[OS_PROJECT_NAME], "
                        "--os-domain-id or env[OS_DOMAIN_ID], or"
                        "--os-domain-name or env[OS_DOMAIN_NAME], or "
                        "--os-trust-id or env[OS_TRUST_ID].")

            if not self.options.os_auth_url:
                raise exc.CommandError(
                    "You must provide an auth url via"
                    " either --os-auth-url or via env[OS_AUTH_URL]")

            if (self.options.os_trust_id
                    and self.options.os_identity_api_version != '3'):
                raise exc.CommandError(
                    "Trusts can only be used with Identity API v3")

            if (self.options.os_trust_id and (
                (self.options.os_project_id or self.options.os_project_name) or
                (self.options.os_domain_id or self.options.os_domain_name))):
                raise exc.CommandError(
                    "Authentication cannot be scoped to multiple targets. "
                    "Pick one of project, domain or trust.")

        self.client_manager = clientmanager.ClientManager(
            auth_options=self.options,
            verify=self.verify,
            api_version=self.api_version,
        )
        return