示例#1
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods.

    This method should be replaced with osc_utils.find_resource()
    """
    # first try to get entity as integer id

    # When the 'name_or_id' is int, covert it to string.
    # Reason is that manager cannot find instance when name_or_id
    # is integer and instance name is digital.
    # Related to bug/1740015.
    if isinstance(name_or_id, int):
        name_or_id = str(name_or_id)
    elif sys.version_info <= (3, 0):
        name_or_id = encodeutils.safe_decode(name_or_id)

    try:
        return manager.get(name_or_id)
    except exceptions.NotFound:
        pass

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

        # finally try to find entity by name
        try:
            return manager.find(name=name_or_id)
        except exceptions.NotFound:
            try:
                return manager.find(display_name=name_or_id)
            except (UnicodeDecodeError, exceptions.NotFound):
                try:
                    # Instances does not have name, but display_name
                    return manager.find(display_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 %s matches found for '%s', use an ID to be more"
               " specific." %
               (manager.resource_class.__name__.lower(), name_or_id))
        raise exceptions.CommandError(msg)
示例#2
0
def get_resource_id(manager, id_or_name):
    if not uuidutils.is_uuid_like(id_or_name):
        try:
            id_or_name = get_resource_id_by_name(manager, id_or_name)
        except Exception as e:
            msg = ("Failed to get resource ID for %s, error: %s" %
                   (id_or_name, str(e)))
            raise exceptions.CommandError(msg)

    return id_or_name
示例#3
0
 def do_help(self, args):
     """Displays 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()
示例#4
0
def get_project_id(manager, id_or_name):
    if not uuidutils.is_uuid_like(id_or_name):
        try:
            project = identity_common.find_project(manager, id_or_name)
            id_or_name = project.id
        except Exception as e:
            msg = ("Failed to get project ID for %s, error: %s" %
                   (id_or_name, str(e)))
            raise exceptions.CommandError(msg)

    return id_or_name
示例#5
0
def find_resource(manager, name_or_id):
    """Helper for the _find_* methods."""
    # first try to get entity as integer id

    # if the 'id' starts with '0' don't treat it as an int
    if isinstance(name_or_id, int) or (name_or_id.isdigit()
                                       and not name_or_id.startswith('0')):
        name_or_id = int(name_or_id)
    elif sys.version_info <= (3, 0):
        name_or_id = encodeutils.safe_decode(name_or_id)

    try:
        return manager.get(name_or_id)
    except exceptions.NotFound:
        pass

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

        # finally try to find entity by name
        try:
            return manager.find(name=name_or_id)
        except exceptions.NotFound:
            try:
                return manager.find(display_name=name_or_id)
            except (UnicodeDecodeError, exceptions.NotFound):
                try:
                    # Instances does not have name, but display_name
                    return manager.find(display_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 %s matches found for '%s', use an ID to be more"
               " specific." %
               (manager.resource_class.__name__.lower(), name_or_id))
        raise exceptions.CommandError(msg)
示例#6
0
def do_action_on_many(action, resources, success_msg, error_msg):
    """Helper to run an action on many resources."""
    failure_flag = False

    for resource in resources:
        try:
            action(resource)
            print(success_msg % resource)
        except Exception as e:
            failure_flag = True
            print(encodeutils.safe_encode(str(e)))

    if failure_flag:
        raise exceptions.CommandError(error_msg)
示例#7
0
    def main(self, argv):
        # Parse args once to find version and debug settings
        parser = self.get_base_parser(argv)
        (options, args) = parser.parse_known_args(argv)
        self.setup_debugging(options.debug)
        self.options = options

        # Discover available auth plugins
        troveclient.auth_plugin.discover_auth_systems()

        # build available subcommands based on version
        self.extensions = self._discover_extensions(
            options.os_database_api_version)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(
            options.os_database_api_version, argv)
        self.parser = subcommand_parser

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

        args = subcommand_parser.parse_args(argv)
        self._run_extension_hooks('__post_parse_args__', args)

        # 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 = args.os_username
        os_password = args.os_password
        os_project_name = getattr(args, 'os_project_name',
                                  getattr(args, 'os_tenant_name', None))
        os_auth_url = args.os_auth_url
        os_region_name = args.os_region_name
        os_project_id = getattr(args, 'os_project_id',
                                getattr(args, 'os_tenant_id', None))
        os_auth_system = args.os_auth_system

        if "v2.0" not in os_auth_url:
            if (not args.os_project_domain_id
                    and not args.os_project_domain_name):
                setattr(args, "os_project_domain_id", "default")
            if not args.os_user_domain_id and not args.os_user_domain_name:
                setattr(args, "os_user_domain_id", "default")

        endpoint_type = args.endpoint_type
        insecure = args.insecure
        service_type = args.service_type
        service_name = args.service_name
        database_service_name = args.database_service_name
        cacert = args.os_cacert
        bypass_url = args.bypass_url

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

        if not endpoint_type:
            endpoint_type = DEFAULT_TROVE_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_TROVE_SERVICE_TYPE
            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 utils.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_password:
                os_password = getpass.getpass()

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

        # V3 stuff
        project_info_provided = (self.options.os_project_name
                                 or self.options.os_project_id)

        if (not project_info_provided):
            raise exc.CommandError(
                _("You must provide a "
                  "project_id or project_name (with "
                  "project_domain_name or project_domain_id) via "
                  "  --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] or specify an "
                  "auth_system which defines a default "
                  "url with --os-auth-system or "
                  "env[OS_AUTH_SYSTEM]"))

        use_session = True
        if auth_plugin or bypass_url:
            use_session = False

        ks_session = None
        keystone_auth = None
        if use_session:
            project_id = args.os_project_id or args.os_tenant_id
            project_name = args.os_project_name or args.os_tenant_name

            ks_session = loading.load_session_from_argparse_arguments(args)
            keystone_auth = self._get_keystone_auth(
                ks_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)

        profile = osprofiler_profiler and options.profile
        if profile:
            osprofiler_profiler.init(options.profile)

        self.cs = client.Client(options.os_database_api_version,
                                os_username,
                                os_password,
                                os_project_name,
                                os_auth_url,
                                insecure,
                                region_name=os_region_name,
                                tenant_id=os_project_id,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                database_service_name=database_service_name,
                                retries=options.retries,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                bypass_url=bypass_url,
                                auth_system=os_auth_system,
                                auth_plugin=auth_plugin,
                                session=ks_session,
                                auth=keystone_auth)

        try:
            if not utils.isunauthenticated(args.func):
                # If Keystone is used, authentication is handled as
                # part of session.
                if not use_session:
                    self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError(_("Invalid OpenStack Trove credentials."))
        except exc.AuthorizationFailure:
            raise exc.CommandError(_("Unable to authorize user"))

        endpoint_api_version = self.cs.get_database_api_version_from_endpoint()

        if endpoint_api_version != options.os_database_api_version:
            msg = (_("Database API version is set to %(db_ver)s "
                     "but you are accessing a %(ep_ver)s endpoint. "
                     "Change its value via either --os-database-api-version "
                     "or env[OS_DATABASE_API_VERSION]") % {
                         'db_ver': options.os_database_api_version,
                         'ep_ver': endpoint_api_version
                     })
            # raise exc.InvalidAPIVersion(msg)
            raise exc.UnsupportedVersion(msg)

        # Override printing to json output
        if args.json:
            utils.json_output = True
        else:
            utils.json_output = False

        try:
            args.func(self.cs, args)
        finally:
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print(_("Trace ID: %(trace_id)s") % {'trace_id': trace_id})
                print(
                    _("To display the trace, use the following command:\n"
                      "osprofiler trace show --html %(trace_id)s") %
                    {'trace_id': trace_id})