Exemplo n.º 1
0
def _get_by_id_or_name(manager, id=None, name=None):
    if not (name or id):
        raise exceptions.CommandError("either NAME or ID is required")
    if id:
        return manager.get(id)
    ls = manager.find(name=name)
    if len(ls) == 0:
        raise exceptions.CommandError(
            "%s '%s' not found" % (manager.resource_class.resource_name, name))
    elif len(ls) > 1:
        raise exceptions.CommandError(
            "%s '%s' not unique, try by ID" %
            (manager.resource_class.resource_name, name))
    return ls[0]
Exemplo n.º 2
0
def find_resource(manager, name_or_id, **find_args):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id
    try:
        return manager.get(int(name_or_id))
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # now try to get entity as uuid
    try:
        tmp_id = strutils.safe_encode(name_or_id)
        if six.PY3:
            tmp_id = tmp_id.decode()
        uuid.UUID(tmp_id)
        return manager.get(tmp_id)
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # for str id which is not uuid (for Flavor search currently)
    if getattr(manager, 'is_alphanum_id_allowed', False):
        try:
            return manager.get(name_or_id)
        except exceptions.NotFound:
            pass

    try:
        try:
            return manager.find(human_id=name_or_id, **find_args)
        except exceptions.NotFound:
            pass

        # finally try to find entity by name
        try:
            resource = getattr(manager, 'resource_class', None)
            name_attr = resource.NAME_ATTR if resource else 'name'
            kwargs = {name_attr: name_or_id}
            kwargs.update(find_args)
            return manager.find(**kwargs)
        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 %s matches found for '%s', use an ID to be more"
               " specific." %
               (manager.resource_class.__name__.lower(), name_or_id))
        raise exceptions.CommandError(msg)
 def do_help(self, args):
     """Display help about this program or one of its subcommands."""
     if args.command:
         if args.command in self.subcommands:
             self.subcommands[args.command].print_help()
         else:
             raise exc.CommandError("'%s' is not a valid subcommand" %
                                    args.command)
     else:
         self.parser.print_help()
Exemplo n.º 4
0
def do_job_type_list(cs, args):
    """Show supported job types."""
    search_opts = {}
    if args.type:
        search_opts["type"] = args.type
    if args.plugin:
        search_opts["plugin"] = args.plugin
        if args.plugin_version:
            search_opts["version"] = args.plugin_version
    elif args.plugin_version:
        raise exceptions.CommandError(
            'The --plugin-version option is only valid when '
            '--plugin is specified')

    job_types = cs.job_types.list(search_opts)
    columns = ('name', 'plugin(versions)')
    utils.print_list(job_types, columns,
                     {'plugin(versions)': _print_plugin_field})
    def main(self, argv):

        # Parse args once to find version and debug settings
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self.setup_debugging(options.debug)
        self.options = options

        # NOTE(dtroyer): Hackery to handle --endpoint_type due to argparse
        #                thinking usage-list --end is ambiguous; but it
        #                works fine with only --endpoint-type present
        #                Go figure.
        if '--endpoint_type' in argv:
            spot = argv.index('--endpoint_type')
            argv[spot] = '--endpoint-type'

        subcommand_parser = (self.get_subcommand_parser(
            options.sahara_api_version))
        self.parser = subcommand_parser

        if options.help or not argv:
            subcommand_parser.print_help()
            return 0

        args = subcommand_parser.parse_args(argv)

        # Short-circuit and deal with help 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

#        (os_username, os_tenant_name, os_tenant_id, os_auth_url,
#                os_region_name, os_auth_system, endpoint_type, insecure,
#                service_type, service_name, volume_service_name,
#                bypass_url, os_cache, cacert) = ( #, timeout) = (
#                        args.os_username,
#                        args.os_tenant_name, args.os_tenant_id,
#                        args.os_auth_url,
#                        args.os_region_name,
#                        args.os_auth_system,
#                        args.endpoint_type, args.insecure,
#                        args.service_type,
#                        args.service_name, args.volume_service_name,
#                        args.bypass_url, args.os_cache,
#                        args.os_cacert, args.timeout)
        (os_username, os_tenant_name, os_tenant_id, os_auth_url,
         os_auth_system, endpoint_type, service_type, bypass_url, os_cacert,
         insecure,
         region_name) = ((args.os_username, args.os_tenant_name,
                          args.os_tenant_id, args.os_auth_url,
                          args.os_auth_system, args.endpoint_type,
                          args.service_type, args.bypass_url, args.os_cacert,
                          args.insecure, args.region_name))

        if os_auth_system and os_auth_system != "keystone":
            auth_plugin = auth.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        # Fetched and set later as needed
        os_password = None

        if not endpoint_type:
            endpoint_type = DEFAULT_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_SERVICE_TYPE
# NA - there is only one service this CLI accesses
#            service_type = utils.get_service_type(args.func) or service_type

# FIXME(usrleon): Here should be restrict for project id same as
# for os_username or os_password but for compatibility it is not.
        if not cliutils.isunauthenticated(args.func):
            if auth_plugin:
                auth_plugin.parse_opts(args)

            if not auth_plugin or not auth_plugin.opts:
                if not os_username:
                    raise exc.CommandError("You must provide a username "
                                           "via either --os-username or "
                                           "env[OS_USERNAME]")

            if not os_auth_url:
                if os_auth_system and os_auth_system != 'keystone':
                    os_auth_url = auth_plugin.get_auth_url()

            if not os_auth_url:
                raise exc.CommandError("You must provide an auth url "
                                       "via either --os-auth-url or "
                                       "env[OS_AUTH_URL] or specify an "
                                       "auth_system which defines a "
                                       "default url with --os-auth-system "
                                       "or env[OS_AUTH_SYSTEM]")

# NA
#        if (options.os_compute_api_version and
#                options.os_compute_api_version != '1.0'):
#            if not os_tenant_name and not os_tenant_id:
#                raise exc.CommandError("You must provide a tenant name "
#                        "or tenant id via --os-tenant-name, "
#                        "--os-tenant-id, env[OS_TENANT_NAME] "
#                        "or env[OS_TENANT_ID]")
#
#            if not os_auth_url:
#                raise exc.CommandError("You must provide an auth url "
#                        "via either --os-auth-url or env[OS_AUTH_URL]")

# NOTE: The Sahara client authenticates when you create it. So instead of
#       creating here and authenticating later, which is what the novaclient
#       does, we just create the client later.

# Now check for the password/token of which pieces of the
# identifying keyring key can come from the underlying client
        if not cliutils.isunauthenticated(args.func):
            # NA - Client can't be used with SecretsHelper
            # helper = SecretsHelper(args, self.cs.client)
            if (auth_plugin and auth_plugin.opts
                    and "os_password" not in auth_plugin.opts):
                use_pw = False
            else:
                use_pw = True

#            tenant_id, auth_token, management_url = (helper.tenant_id,
#                                                     helper.auth_token,
#                                                     helper.management_url)
#
#            if tenant_id and auth_token and management_url:
#                self.cs.client.tenant_id = tenant_id
#                self.cs.client.auth_token = auth_token
#                self.cs.client.management_url = management_url
#                # authenticate just sets up some values in this case, no REST
#                # calls
#                self.cs.authenticate()
            if use_pw:
                # Auth using token must have failed or not happened
                # at all, so now switch to password mode and save
                # the token when its gotten... using our keyring
                # saver
                # os_password = helper.password
                os_password = args.os_password
                if not os_password:
                    raise exc.CommandError(
                        'Expecting a password provided via either '
                        '--os-password, env[OS_PASSWORD], or '
                        'prompted response')
#                self.cs.client.password = os_password
#                self.cs.client.keyring_saver = helper

# V3 stuff
        project_info_provided = (self.options.os_tenant_name
                                 or self.options.os_tenant_id
                                 or (self.options.os_project_name and
                                     (self.options.os_project_domain_name
                                      or self.options.os_project_domain_id))
                                 or self.options.os_project_id)

        if (not project_info_provided):
            raise exc.CommandError(
                ("You must provide a tenant_name, tenant_id, "
                 "project_id or project_name (with "
                 "project_domain_name or project_domain_id) via "
                 "  --os-tenant-name (env[OS_TENANT_NAME]),"
                 "  --os-tenant-id (env[OS_TENANT_ID]),"
                 "  --os-project-id (env[OS_PROJECT_ID])"
                 "  --os-project-name (env[OS_PROJECT_NAME]),"
                 "  --os-project-domain-id "
                 "(env[OS_PROJECT_DOMAIN_ID])"
                 "  --os-project-domain-name "
                 "(env[OS_PROJECT_DOMAIN_NAME])"))

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

        keystone_session = None
        keystone_auth = None
        if not auth_plugin:
            project_id = args.os_project_id or args.os_tenant_id
            project_name = args.os_project_name or args.os_tenant_name

            keystone_session = (session.Session.load_from_cli_options(args))
            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)

        self.cs = client.Client(username=os_username,
                                api_key=os_password,
                                project_id=os_tenant_id,
                                project_name=os_tenant_name,
                                auth_url=os_auth_url,
                                sahara_url=bypass_url,
                                endpoint_type=endpoint_type,
                                session=keystone_session,
                                auth=keystone_auth,
                                cacert=os_cacert,
                                insecure=insecure,
                                service_type=service_type,
                                region_name=region_name)

        args.func(self.cs, args)
Exemplo n.º 6
0
def find_resource(manager, name_or_id, **find_args):
    """Look for resource in a given manager.

    Used as a helper for the _find_* methods.
    Example:

        def _find_hypervisor(cs, hypervisor):
            #Get a hypervisor by name or ID.
            return cliutils.find_resource(cs.hypervisors, hypervisor)
    """
    # first try to get entity as integer id
    try:
        return manager.get(int(name_or_id))
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # now try to get entity as uuid
    try:
        if six.PY2:
            tmp_id = strutils.safe_encode(name_or_id)
        else:
            tmp_id = strutils.safe_decode(name_or_id)

        if uuidutils.is_uuid_like(tmp_id):
            return manager.get(tmp_id)
    except (TypeError, ValueError, exceptions.NotFound):
        pass

    # for str id which is not uuid
    if getattr(manager, 'is_alphanum_id_allowed', False):
        try:
            return manager.get(name_or_id)
        except exceptions.NotFound:
            pass

    try:
        try:
            return manager.find(human_id=name_or_id, **find_args)
        except exceptions.NotFound:
            pass

        # finally try to find entity by name
        try:
            resource = getattr(manager, 'resource_class', None)
            name_attr = resource.NAME_ATTR if resource else 'name'
            kwargs = {name_attr: name_or_id}
            kwargs.update(find_args)
            return manager.find(**kwargs)
        except exceptions.NotFound:
            msg = _("No %(name)s with a name or "
                    "ID of '%(name_or_id)s' exists.") % \
                {
                    "name": manager.resource_class.__name__.lower(),
                    "name_or_id": name_or_id
                }
            raise exceptions.CommandError(msg)
    except exceptions.NoUniqueMatch:
        msg = _("Multiple %(name)s matches found for "
                "'%(name_or_id)s', use an ID to be more specific.") % \
            {
                "name": manager.resource_class.__name__.lower(),
                "name_or_id": name_or_id
            }
        raise exceptions.CommandError(msg)