Esempio n. 1
0
def find_resource(manager, name_or_id, *args, **kwargs):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id), *args, **kwargs)
    except exceptions.NotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(str(name_or_id))
        return manager.get(name_or_id, *args, **kwargs)
    except (ValueError, exceptions.NotFound):
        pass

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exceptions.NotFound:
        msg = "No %s with a name or ID of '%s' exists." % \
              (manager.resource_class.__name__.lower(), name_or_id)
        raise exceptions.CommandError(msg)
    except exceptions.NoUniqueMatch:
        msg = (_("Multiple %(class)s matches found for '%(name)s', use an ID "
                 "to be more specific.") % {
                     'class': manager.resource_class.__name__.lower(),
                     'name': name_or_id
                 })
        raise exceptions.CommandError(msg)
Esempio n. 2
0
    def _discover_auth_versions(self, session, auth_url):
        # discover the API versions the server is supporting base on the
        # given URL
        v2_auth_url = None
        v3_auth_url = None
        try:
            ks_discover = discover.Discover(session=session, auth_url=auth_url)
            v2_auth_url = ks_discover.url_for('2.0')
            v3_auth_url = ks_discover.url_for('3.0')
        except ks_exc.ClientException as e:
            # Identity service may not support discover API version.
            # Lets trying to figure out the API version from the original URL.
            url_parts = urlparse.urlparse(auth_url)
            (scheme, netloc, path, params, query, fragment) = url_parts
            path = path.lower()
            if path.startswith('/v3'):
                v3_auth_url = auth_url
            elif path.startswith('/v2'):
                v2_auth_url = auth_url
            else:
                # not enough information to determine the auth version
                msg = ('Unable to determine the Keystone version '
                       'to authenticate with using the given '
                       'auth_url. Identity service may not support API '
                       'version discovery. Please provide a versioned '
                       'auth_url instead. error=%s') % (e)
                raise exc.CommandError(msg)

        return (v2_auth_url, v3_auth_url)
Esempio n. 3
0
    def do_help(self, args):
        """Display help about this program or one of its subcommands.

        """
        if getattr(args, 'command', None):
            if args.command in self.subcommands:
                self.subcommands[args.command].print_help()
            else:
                msg = "'%s' is not a valid subcommand"
                raise exc.CommandError(msg % args.command)
        else:
            self.parser.print_help()
Esempio n. 4
0
    def _get_keystone_auth(self, session, auth_url, **kwargs):
        auth_token = kwargs.pop('auth_token', None)
        if auth_token:
            return token.Token(
                auth_url,
                auth_token,
                project_id=kwargs.pop('project_id'),
                project_name=kwargs.pop('project_name'),
                project_domain_id=kwargs.pop('project_domain_id'),
                project_domain_name=kwargs.pop('project_domain_name'))

        # NOTE(starodubcevna): this is a workaround for the bug:
        # https://bugs.launchpad.net/python-openstackclient/+bug/1447704
        # Change that fix this error in keystoneclient was abandoned,
        # so we should use workaround until we move to keystoneauth.
        # The idea of the code came from glanceclient.

        (v2_auth_url, v3_auth_url) = self._discover_auth_versions(
            session=session,
            auth_url=auth_url)

        if v3_auth_url:
            # NOTE(starodubcevna): set user_domain_id and project_domain_id
            # to default as it done in other projects.
            return password.Password(auth_url,
                                     username=kwargs.pop('username'),
                                     user_id=kwargs.pop('user_id'),
                                     password=kwargs.pop('password'),
                                     user_domain_id=kwargs.pop(
                                         'user_domain_id') or 'default',
                                     user_domain_name=kwargs.pop(
                                         'user_domain_name'),
                                     project_id=kwargs.pop('project_id'),
                                     project_name=kwargs.pop('project_name'),
                                     project_domain_id=kwargs.pop(
                                         'project_domain_id') or 'default')
        elif v2_auth_url:
            return password.Password(auth_url,
                                     username=kwargs.pop('username'),
                                     user_id=kwargs.pop('user_id'),
                                     password=kwargs.pop('password'),
                                     project_id=kwargs.pop('project_id'),
                                     project_name=kwargs.pop('project_name'))
        else:
            # if we get here it means domain information is provided
            # (caller meant to use Keystone V3) but the auth url is
            # actually Keystone V2. Obviously we can't authenticate a V3
            # user using V2.
            exc.CommandError("Credential and auth_url mismatch. The given "
                             "auth_url is using Keystone V2 endpoint, which "
                             "may not able to handle Keystone V3 credentials. "
                             "Please provide a correct Keystone V3 auth_url.")
Esempio n. 5
0
def find_resource(manager, name_or_id, *args, **kwargs):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        if isinstance(name_or_id, int) or name_or_id.isdigit():
            return manager.get(int(name_or_id), *args, **kwargs)
    except exceptions.NotFound:
        pass

    # now try to get entity as uuid
    try:
        uuid.UUID(str(name_or_id))
        return manager.get(name_or_id, *args, **kwargs)
    except (ValueError, exceptions.NotFound):
        pass

    # finally try to find entity by name
    try:
        return manager.find(name=name_or_id)
    except exceptions.NotFound:
        msg = "No %s with a name or ID of '%s' exists." % \
              (manager.resource_class.__name__.lower(), name_or_id)
        raise exceptions.CommandError(msg)
Esempio n. 6
0
    def main(self, argv):
        # Parse args once to find version
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self._setup_logging(options.debug)

        # build available subcommands based on version
        api_version = options.sgs_api_version
        subcommand_parser = self.get_subcommand_parser(api_version)
        self.parser = subcommand_parser

        # keystone_session = None
        # keystone_auth = None

        # Handle top-level --help/-h before attempting to parse
        # a command off the command line.
        if (not args and options.help) or not argv:
            self.do_help(options)
            return 0

        # Parse args again and call whatever callback was selected.
        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help command right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not args.os_username and not args.os_auth_token:
            raise exc.CommandError("You must provide a username via"
                                   " either --os-username or env[OS_USERNAME]"
                                   " or a token via --os-auth-token or"
                                   " env[OS_AUTH_TOKEN]")

        if args.os_no_client_auth:
            if not args.sgs_url:
                raise exc.CommandError(
                    "If you specify --os-no-client-auth"
                    " you must also specify a SG-Service API URL"
                    " via either --sgs-url or env[SGS_URL]")

        else:
            # Tenant name or ID is needed to make keystoneclient retrieve a
            # service catalog, it's not required if os_no_client_auth is
            # specified, neither is the auth URL.
            if not any([args.os_tenant_name, args.os_tenant_id,
                        args.os_project_id, args.os_project_name]):
                raise exc.CommandError("You must provide a project name or"
                                       " project id via --os-project-name,"
                                       " --os-project-id, env[OS_PROJECT_ID]"
                                       " or env[OS_PROJECT_NAME]. You may"
                                       " use os-project and os-tenant"
                                       " interchangeably.")
            if not args.os_auth_url:
                raise exc.CommandError("You must provide an auth url via"
                                       " either --os-auth-url or via"
                                       " env[OS_AUTH_URL]")

        # TODO(luobin): use keystone get endpoint and kwargs
        kwargs = {}
        project_id = "468b0b3a8318403eba8e7d4fcf44e611"
        endpoint = "http://162.3.117.200:8975/v1/%s" % project_id

        client = sgs_client.Client(api_version, endpoint, **kwargs)

        args.func(client, args)
Esempio n. 7
0
    def main(self, argv):
        # Parse args once to find version
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self._setup_logging(options.debug)

        # build available subcommands based on version
        api_version = options.sgs_api_version
        subcommand_parser = self.get_subcommand_parser(api_version)
        self.parser = subcommand_parser

        # keystone_session = None
        # keystone_auth = None

        # Handle top-level --help/-h before attempting to parse
        # a command off the command line.
        if (not args and options.help) or not argv:
            self.do_help(options)
            return 0

        # Parse args again and call whatever callback was selected.
        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help command right away.
        if args.func == self.do_help:
            self.do_help(args)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not args.os_username and not args.os_auth_token:
            raise exc.CommandError("You must provide a username via"
                                   " either --os-username or env[OS_USERNAME]"
                                   " or a token via --os-auth-token or"
                                   " env[OS_AUTH_TOKEN]")

        if args.os_no_client_auth:
            if not args.sgs_url:
                raise exc.CommandError(
                    "If you specify --os-no-client-auth"
                    " you must also specify a SG-Service API URL"
                    " via either --sgs-url or env[SGS_URL]")

        else:
            # Tenant name or ID is needed to make keystoneclient retrieve a
            # service catalog, it's not required if os_no_client_auth is
            # specified, neither is the auth URL.
            if not any([
                    args.os_tenant_name, args.os_tenant_id, args.os_project_id,
                    args.os_project_name
            ]):
                raise exc.CommandError("You must provide a project name or"
                                       " project id via --os-project-name,"
                                       " --os-project-id, env[OS_PROJECT_ID]"
                                       " or env[OS_PROJECT_NAME]. You may"
                                       " use os-project and os-tenant"
                                       " interchangeably.")
            if not args.os_auth_url:
                raise exc.CommandError("You must provide an auth url via"
                                       " either --os-auth-url or via"
                                       " env[OS_AUTH_URL]")

        endpoint = args.sgs_url

        if args.os_no_client_auth:
            # Authenticate through sgservice, don't use session
            kwargs = {
                'username': args.os_username,
                'password': args.os_password,
                'auth_token': args.os_auth_token,
                'auth_url': args.os_auth_url,
                'token': args.os_auth_token,
                'insecure': args.insecure,
                'timeout': args.api_timeout
            }

            if args.os_region_name:
                kwargs['region_name'] = args.os_region_name
        else:
            # Create a keystone session and keystone auth
            keystone_session = ksession.Session.load_from_cli_options(args)
            project_id = args.os_project_id or args.os_tenant_id
            project_name = args.os_project_name or args.os_tenant_name

            keystone_auth = self._get_keystone_auth(
                keystone_session,
                args.os_auth_url,
                username=args.os_username,
                user_id=args.os_user_id,
                user_domain_id=args.os_user_domain_id,
                user_domain_name=args.os_user_domain_name,
                password=args.os_password,
                auth_token=args.os_auth_token,
                project_id=project_id,
                project_name=project_name,
                project_domain_id=args.os_project_domain_id,
                project_domain_name=args.os_project_domain_name)

            endpoint_type = args.os_endpoint_type or 'publicURL'
            service_type = args.os_service_type or 'sg-service'

            endpoint = keystone_auth.get_endpoint(
                keystone_session,
                service_type=service_type,
                region_name=args.os_region_name)

            kwargs = {
                'session': keystone_session,
                'auth': keystone_auth,
                'service_type': service_type,
                'endpoint_type': endpoint_type,
                'region_name': args.os_region_name,
            }

        if args.api_timeout:
            kwargs['timeout'] = args.api_timeout

        client = sgs_client.Client(api_version, endpoint, **kwargs)

        args.func(client, args)