Example #1
0
def do_group_type_delete(cs, args):
    """Deletes group type or types."""
    failure_count = 0
    for group_type in args.group_type:
        try:
            gtype = shell_utils.find_group_type(cs, group_type)
            cs.group_types.delete(gtype)
            print("Request to delete group type %s has been accepted." %
                  (group_type))
        except Exception as e:
            failure_count += 1
            print("Delete for group type %s failed: %s" % (group_type, e))
    if failure_count == len(args.group_type):
        raise exceptions.CommandError("Unable to delete any of the "
                                      "specified types.")
Example #2
0
def do_reset_state(cs, args):
    """Explicitly updates the volume state."""
    failure_flag = False

    for volume in args.volume:
        try:
            utils.find_volume(cs, volume).reset_state(args.state)
        except Exception as e:
            failure_flag = True
            msg = "Reset state for volume %s failed: %s" % (volume, e)
            print(msg)

    if failure_flag:
        msg = "Unable to reset the state for the specified volume(s)."
        raise exceptions.CommandError(msg)
Example #3
0
    def check_duplicate_filters(self, argv, filter):
        resource = RESOURCE_FILTERS[filter]
        filters = []
        for opt in range(len(argv)):
            if argv[opt].startswith('--'):
                if argv[opt] == '--filters':
                    key, __ = argv[opt + 1].split('=')
                    if key in resource:
                        filters.append(key)
                elif argv[opt][2:] in resource:
                    filters.append(argv[opt][2:])

        if len(set(filters)) != len(filters):
            raise exc.CommandError(
                "Filters are only allowed to be passed once.")
Example #4
0
    def _get_keystone_session(self, **kwargs):
        # first create a Keystone session
        cacert = self.options.os_cacert or None
        cert = self.options.os_cert or None
        if cert and self.options.os_key:
            cert = cert, self.options.os_key

        insecure = self.options.insecure or False

        if insecure:
            verify = False
        else:
            verify = cacert or True

        ks_session = session.Session(verify=verify, cert=cert)
        # discover the supported keystone versions using the given url
        (v2_auth_url, v3_auth_url) = self._discover_auth_versions(
            session=ks_session,
            auth_url=self.options.os_auth_url)

        username = self.options.os_username or None
        user_domain_name = self.options.os_user_domain_name or None
        user_domain_id = self.options.os_user_domain_id or None

        auth = None
        if v3_auth_url and v2_auth_url:
            # support both v2 and v3 auth. Use v3 if possible.
            if username:
                if user_domain_name or user_domain_id:
                    # use v3 auth
                    auth = self.get_v3_auth(v3_auth_url)
                else:
                    # use v2 auth
                    auth = self.get_v2_auth(v2_auth_url)

        elif v3_auth_url:
            # support only v3
            auth = self.get_v3_auth(v3_auth_url)
        elif v2_auth_url:
            # support only v2
            auth = self.get_v2_auth(v2_auth_url)
        else:
            raise exc.CommandError('Unable to determine the Keystone version '
                                   'to authenticate with using the given '
                                   'auth_url.')

        ks_session.auth = auth
        return ks_session
def do_import(cs, args):
    """Import a volume from a file."""

    # Parse the volume ID from the filename which is in this format:
    #   volume-<id>-<timestamp>.tgz
    # For example:
    #   volume-3a2cae29-850d-4445-b9ae-03865080b915-20140821-162819.tgz
    if (args.file_name.find("volume-") != 0
            or args.file_name.rfind(".tgz") == -1 or len(args.file_name) < 28):
        raise exceptions.CommandError(
            "Invalid filename - volume files must have the following format: "
            "volume-<id>-<timestamp>.tgz")

    volume_id = args.file_name[7:-20]
    volume = utils.find_volume(cs, volume_id)
    updated_volume = volume.import_volume(args.file_name)
    utils.print_dict(updated_volume[1]['wrs-volume:os-volume_import'])
Example #6
0
def do_reset_state(cs, args):
    """Explicitly update the state of a volume."""
    failure_count = 0

    single = (len(args.volume) == 1)

    for volume in args.volume:
        try:
            utils.find_volume(cs, volume).reset_state(args.state)
        except Exception as e:
            failure_count += 1
            msg = "Reset state for volume %s failed: %s" % (volume, e)
            if not single:
                print(msg)

    if failure_count == len(args.volume):
        if not single:
            msg = "Unable to reset the state for any of the specified volumes."
        raise exceptions.CommandError(msg)
Example #7
0
def do_snapshot_reset_state(cs, args):
    """Explicitly update the state of a snapshot."""
    failure_count = 0

    single = (len(args.snapshot) == 1)

    for snapshot in args.snapshot:
        try:
            _find_volume_snapshot(cs, snapshot).reset_state(args.state)
        except Exception as e:
            failure_count += 1
            msg = "Reset state for snapshot %s failed: %s" % (snapshot, e)
            if not single:
                print(msg)

    if failure_count == len(args.snapshot):
        if not single:
            msg = ("Unable to reset the state for any of the the specified "
                   "snapshots.")
        raise exceptions.CommandError(msg)
Example #8
0
    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)
        api_version_input = True
        self.options = options

        if not options.os_volume_api_version:
            # Environment variable OS_VOLUME_API_VERSION was
            # not set and '--os-volume-api-version' option doesn't
            # specify a value.  Fall back to default.
            options.os_volume_api_version = DEFAULT_OS_VOLUME_API_VERSION
            api_version_input = False

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

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

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

        argv = self._delimit_metadata_args(argv)
        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, os_password, os_tenant_name, os_auth_url, os_region_name,
         os_tenant_id, endpoint_type, service_type, service_name,
         volume_service_name, bypass_url, cacert,
         os_auth_system) = (args.os_username, args.os_password,
                            args.os_tenant_name, args.os_auth_url,
                            args.os_region_name, args.os_tenant_id,
                            args.os_endpoint_type, args.service_type,
                            args.service_name, args.volume_service_name,
                            args.bypass_url, args.os_cacert,
                            args.os_auth_system)
        if os_auth_system and os_auth_system != "keystone":
            auth_plugin = cinderclient.auth_plugin.load_plugin(os_auth_system)
        else:
            auth_plugin = None

        if not service_type:
            service_type = DEFAULT_CINDER_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 user name "
                                           "through --os-username or "
                                           "env[OS_USERNAME].")

            if not 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:
                        os_password = getpass.getpass('OS Password: '******'t have a tty or the
                # user Ctl-D when prompted.
                if not os_password:
                    raise exc.CommandError("You must provide a password "
                                           "through --os-password, "
                                           "env[OS_PASSWORD] "
                                           "or, prompted response.")

            if not (os_tenant_name or os_tenant_id):
                raise exc.CommandError("You must provide a tenant ID "
                                       "through --os-tenant-id or "
                                       "env[OS_TENANT_ID].")

            # 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.project_domain_name or
                  self.options.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:
                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 authentication URL "
                    "through --os-auth-url or env[OS_AUTH_URL].")

        if not (os_tenant_name or os_tenant_id):
            raise exc.CommandError(
                "You must provide a tenant ID "
                "through --os-tenant-id or env[OS_TENANT_ID].")

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

        auth_session = None
        if not auth_plugin:
            auth_session = self._get_keystone_session()

        self.cs = client.Client(options.os_volume_api_version,
                                os_username,
                                os_password,
                                os_tenant_name,
                                os_auth_url,
                                region_name=os_region_name,
                                tenant_id=os_tenant_id,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                volume_service_name=volume_service_name,
                                bypass_url=bypass_url,
                                retries=options.retries,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                auth_system=os_auth_system,
                                auth_plugin=auth_plugin,
                                session=auth_session)

        try:
            if not utils.isunauthenticated(args.func):
                self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError("OpenStack credentials are not valid.")
        except exc.AuthorizationFailure:
            raise exc.CommandError("Unable to authorize user.")

        endpoint_api_version = None
        # Try to get the API version from the endpoint URL.  If that fails fall
        # back to trying to use what the user specified via
        # --os-volume-api-version or with the OS_VOLUME_API_VERSION environment
        # variable.  Fail safe is to use the default API setting.
        try:
            endpoint_api_version = \
                self.cs.get_volume_api_version_from_endpoint()
            if endpoint_api_version != options.os_volume_api_version:
                msg = (("OpenStack Block Storage API version is set to %s "
                        "but you are accessing a %s endpoint. "
                        "Change its value through --os-volume-api-version "
                        "or env[OS_VOLUME_API_VERSION].") %
                       (options.os_volume_api_version, endpoint_api_version))
                raise exc.InvalidAPIVersion(msg)
        except exc.UnsupportedVersion:
            endpoint_api_version = options.os_volume_api_version
            if api_version_input:
                logger.warning("Cannot determine the API version from "
                               "the endpoint URL. Falling back to the "
                               "user-specified version: %s" %
                               endpoint_api_version)
            else:
                logger.warning("Cannot determine the API version from the "
                               "endpoint URL or user input. Falling back "
                               "to the default API version: %s" %
                               endpoint_api_version)

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

        args.func(self.cs, args)

        if profile:
            trace_id = osprofiler_profiler.get().get_base_id()
            print("Trace ID: %s" % trace_id)
            print("To display trace use next command:\n"
                  "osprofiler trace show --html %s " % trace_id)
Example #9
0
    def main(self, argv):
        # Parse args once to find version and debug settings
        for filter in FILTER_CHECK:
            if filter in argv:
                self.check_duplicate_filters(argv, filter)
                break
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(argv)
        self.setup_debugging(options.debug)
        api_version_input = True
        self.options = options

        do_help = ('help' in argv) or ('--help'
                                       in argv) or ('-h' in argv) or not argv

        api_version = self._validate_input_api_version(options)

        # build available subcommands based on version
        major_version_string = "%s" % api_version.ver_major
        self.extensions = client.discover_extensions(major_version_string)
        self._run_extension_hooks('__pre_parse_args__')

        subcommand_parser = self.get_subcommand_parser(api_version, do_help,
                                                       args)
        self.parser = subcommand_parser

        if argv and len(argv) > 1 and '--help' in argv:
            argv = [x for x in argv if x != '--help']
            if argv[0] in self.subcommands:
                self.subcommands[argv[0]].print_help()
                return 0

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

        argv = self._delimit_metadata_args(argv)
        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, os_password, os_project_name, os_auth_url,
         os_region_name, os_project_id, endpoint_type, service_type,
         service_name, volume_service_name, os_endpoint, cacert,
         os_auth_type) = (args.os_username, args.os_password,
                          args.os_project_name, args.os_auth_url,
                          args.os_region_name, args.os_project_id,
                          args.os_endpoint_type, args.service_type,
                          args.service_name, args.volume_service_name,
                          args.os_endpoint, args.os_cacert, args.os_auth_type)
        auth_session = None

        if os_auth_type and os_auth_type != "keystone":
            auth_plugin = loading.load_auth_from_argparse_arguments(
                self.options)
            auth_session = loading.load_session_from_argparse_arguments(
                self.options, auth=auth_plugin)
        else:
            auth_plugin = None

        if not service_type:
            service_type = client.SERVICE_TYPES[major_version_string]

        # FIXME(usrleon): Here should be restrict for project id same as
        # for os_username or os_password but for compatibility it is not.

        # V3 stuff
        project_info_provided = ((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
                                 or self.options.os_project_name)

        # NOTE(e0ne): if auth_session exists it means auth plugin created
        # session and we don't need to check for password and other
        # authentification-related things.
        if not utils.isunauthenticated(args.func) and not auth_session:
            if not 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:
                        os_password = getpass.getpass('OS Password: '******'t have a tty or the
                # user Ctl-D when prompted.
                if not os_password:
                    raise exc.CommandError("You must provide a password "
                                           "through --os-password, "
                                           "env[OS_PASSWORD] "
                                           "or, prompted response.")

            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 authentication URL "
                    "through --os-auth-url or env[OS_AUTH_URL].")

        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 and not auth_plugin:
            raise exc.CommandError(
                "You must provide an authentication URL "
                "through --os-auth-url or env[OS_AUTH_URL].")

        if not auth_session:
            auth_session = self._get_keystone_session()

        insecure = self.options.insecure

        client_args = dict(
            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,
            volume_service_name=volume_service_name,
            os_endpoint=os_endpoint,
            retries=options.retries,
            http_log_debug=args.debug,
            insecure=insecure,
            cacert=cacert,
            auth_system=os_auth_type,
            auth_plugin=auth_plugin,
            session=auth_session,
            logger=self.ks_logger if auth_session else self.client_logger)

        self.cs = client.Client(api_version, os_username, os_password,
                                os_project_name, os_auth_url, **client_args)

        try:
            if not utils.isunauthenticated(args.func):
                self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError("OpenStack credentials are not valid.")
        except exc.AuthorizationFailure:
            raise exc.CommandError("Unable to authorize user.")

        endpoint_api_version = None
        # Try to get the API version from the endpoint URL.  If that fails fall
        # back to trying to use what the user specified via
        # --os-volume-api-version or with the OS_VOLUME_API_VERSION environment
        # variable.  Fail safe is to use the default API setting.
        try:
            endpoint_api_version = \
                self.cs.get_volume_api_version_from_endpoint()
        except exc.UnsupportedVersion:
            endpoint_api_version = options.os_volume_api_version
            if api_version_input:
                logger.warning(
                    "Cannot determine the API version from "
                    "the endpoint URL. Falling back to the "
                    "user-specified version: %s", endpoint_api_version)
            else:
                logger.warning(
                    "Cannot determine the API version from the "
                    "endpoint URL or user input. Falling back "
                    "to the default API version: %s", endpoint_api_version)

        API_MAX_VERSION = api_versions.APIVersion(api_versions.MAX_VERSION)
        if endpoint_api_version[0] == '3':
            disc_client = client.Client(API_MAX_VERSION, os_username,
                                        os_password, os_project_name,
                                        os_auth_url, **client_args)
            self.cs, discovered_version = self._discover_client(
                disc_client, api_version, args.os_endpoint_type,
                args.service_type, os_username, os_password, os_project_name,
                os_auth_url, client_args)

            if discovered_version < api_version:
                self.downgrade_warning(api_version, discovered_version)

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

        try:
            args.func(self.cs, args)
        finally:
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print("Trace ID: %s" % trace_id)
                print("To display trace use next command:\n"
                      "osprofiler trace show --html %s " % trace_id)
Example #10
0
    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)
        api_version_input = True

        if not options.os_volume_api_version:
            # Environment variable OS_VOLUME_API_VERSION was
            # not set and '--os-volume-api-version' option doesn't
            # specify a value.  Fall back to default.
            options.os_volume_api_version = DEFAULT_OS_VOLUME_API_VERSION
            api_version_input = False

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

        subcommand_parser = self.get_subcommand_parser(
            options.os_volume_api_version)
        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, os_password, os_tenant_name, os_auth_url, os_region_name,
         os_tenant_id, endpoint_type, insecure, service_type, service_name,
         volume_service_name, username, apikey, projectid, url, region_name,
         cacert, os_auth_system) = (args.os_username, args.os_password,
                                    args.os_tenant_name, args.os_auth_url,
                                    args.os_region_name, args.os_tenant_id,
                                    args.endpoint_type, args.insecure,
                                    args.service_type, args.service_name,
                                    args.volume_service_name, args.username,
                                    args.apikey, args.projectid, args.url,
                                    args.region_name, args.os_cacert,
                                    args.os_auth_system)

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

        if not endpoint_type:
            endpoint_type = DEFAULT_CINDER_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_CINDER_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:
                    if not username:
                        raise exc.CommandError(
                            "You must provide a user name "
                            "through --os-username or env[OS_USERNAME].")
                    else:
                        os_username = username

            if not os_password:
                if not apikey:
                    raise exc.CommandError("You must provide a password "
                                           "through --os-password or "
                                           "env[OS_PASSWORD].")
                else:
                    os_password = apikey

            if not (os_tenant_name or os_tenant_id):
                if not projectid:
                    raise exc.CommandError("You must provide a tenant ID "
                                           "through --os-tenant-id or "
                                           "env[OS_TENANT_ID].")
                else:
                    os_tenant_name = projectid

            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:
                if not url:
                    raise exc.CommandError(
                        "You must provide an authentication URL "
                        "through --os-auth-url or env[OS_AUTH_URL].")
                else:
                    os_auth_url = url

            if not os_region_name and region_name:
                os_region_name = region_name

        if not (os_tenant_name or os_tenant_id):
            raise exc.CommandError(
                "You must provide a tenant ID "
                "through --os-tenant-id or env[OS_TENANT_ID].")

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

        self.cs = client.Client(options.os_volume_api_version,
                                os_username,
                                os_password,
                                os_tenant_name,
                                os_auth_url,
                                insecure,
                                region_name=os_region_name,
                                tenant_id=os_tenant_id,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                volume_service_name=volume_service_name,
                                retries=options.retries,
                                http_log_debug=args.debug,
                                cacert=cacert,
                                auth_system=os_auth_system,
                                auth_plugin=auth_plugin)

        try:
            if not utils.isunauthenticated(args.func):
                self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError("OpenStack credentials are not valid.")
        except exc.AuthorizationFailure:
            raise exc.CommandError("Unable to authorize user.")

        endpoint_api_version = None
        # Try to get the API version from the endpoint URL.  If that fails fall
        # back to trying to use what the user specified via
        # --os-volume-api-version or with the OS_VOLUME_API_VERSION environment
        # variable.  Fail safe is to use the default API setting.
        try:
            endpoint_api_version = \
                self.cs.get_volume_api_version_from_endpoint()
            if endpoint_api_version != options.os_volume_api_version:
                msg = (("OpenStack Block Storage API version is set to %s "
                        "but you are accessing a %s endpoint. "
                        "Change its value through --os-volume-api-version "
                        "or env[OS_VOLUME_API_VERSION].") %
                       (options.os_volume_api_version, endpoint_api_version))
                raise exc.InvalidAPIVersion(msg)
        except exc.UnsupportedVersion:
            endpoint_api_version = options.os_volume_api_version
            if api_version_input:
                logger.warning("Cannot determine the API version from "
                               "the endpoint URL. Falling back to the "
                               "user-specified version: %s" %
                               endpoint_api_version)
            else:
                logger.warning("Cannot determine the API version from the "
                               "endpoint URL or user input. Falling back "
                               "to the default API version: %s" %
                               endpoint_api_version)

        args.func(self.cs, args)
Example #11
0
 def wrapper(*args, **kwargs):
     if os.getuid() != 0:
         raise exceptions.CommandError(
             "This command requires root permissions.")
     return f(*args, **kwargs)
Example #12
0
    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)

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

        subcommand_parser = self.get_subcommand_parser(
            options.os_volume_api_version)
        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, os_password, os_tenant_name, os_auth_url, os_region_name,
         os_tenant_id, endpoint_type, insecure, service_type, service_name,
         volume_service_name, username, apikey, projectid, url, region_name,
         cacert) = (args.os_username, args.os_password, args.os_tenant_name,
                    args.os_auth_url, args.os_region_name, args.os_tenant_id,
                    args.endpoint_type, args.insecure, args.service_type,
                    args.service_name, args.volume_service_name, args.username,
                    args.apikey, args.projectid, args.url, args.region_name,
                    args.os_cacert)

        if not endpoint_type:
            endpoint_type = DEFAULT_CINDER_ENDPOINT_TYPE

        if not service_type:
            service_type = DEFAULT_CINDER_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 not os_username:
                if not username:
                    raise exc.CommandError(
                        "You must provide a username "
                        "via either --os-username or env[OS_USERNAME]")
                else:
                    os_username = username

            if not os_password:
                if not apikey:
                    raise exc.CommandError("You must provide a password "
                                           "via either --os-password or via "
                                           "env[OS_PASSWORD]")
                else:
                    os_password = apikey

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

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

            if not os_region_name and region_name:
                os_region_name = region_name

        if not (os_tenant_name or os_tenant_id):
            raise exc.CommandError(
                "You must provide a tenant_id "
                "via either --os-tenant-id 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]")

        self.cs = client.Client(options.os_volume_api_version,
                                os_username,
                                os_password,
                                os_tenant_name,
                                os_auth_url,
                                insecure,
                                region_name=os_region_name,
                                tenant_id=os_tenant_id,
                                endpoint_type=endpoint_type,
                                extensions=self.extensions,
                                service_type=service_type,
                                service_name=service_name,
                                volume_service_name=volume_service_name,
                                retries=options.retries,
                                http_log_debug=args.debug,
                                cacert=cacert)

        try:
            if not utils.isunauthenticated(args.func):
                self.cs.authenticate()
        except exc.Unauthorized:
            raise exc.CommandError("Invalid OpenStack Cinder credentials.")
        except exc.AuthorizationFailure:
            raise exc.CommandError("Unable to authorize user")

        args.func(self.cs, args)
Example #13
0
def do_list(cs, args):
    """Lists all volumes."""
    # NOTE(thingee): Backwards-compatibility with v1 args
    if args.display_name is not None:
        args.name = args.display_name

    all_tenants = 1 if args.tenant else \
        int(os.environ.get("ALL_TENANTS", args.all_tenants))
    search_opts = {
        'all_tenants':
        all_tenants,
        'project_id':
        args.tenant,
        'name':
        args.name,
        'status':
        args.status,
        'bootable':
        args.bootable,
        'migration_status':
        args.migration_status,
        'metadata':
        shell_utils.extract_metadata(args) if args.metadata else None,
        'glance_metadata':
        shell.utils.extract_metadata(args, type='image_metadata')
        if args.image_metadata else None,
    }

    # If unavailable/non-existent fields are specified, these fields will
    # be removed from key_list at the print_list() during key validation.
    field_titles = []
    if args.fields:
        for field_title in args.fields.split(','):
            field_titles.append(field_title)

    # --sort_key and --sort_dir deprecated in kilo and is not supported
    # with --sort
    if args.sort and (args.sort_key or args.sort_dir):
        raise exceptions.CommandError(
            'The --sort_key and --sort_dir arguments are deprecated and are '
            'not supported with --sort.')

    volumes = cs.volumes.list(search_opts=search_opts,
                              marker=args.marker,
                              limit=args.limit,
                              sort_key=args.sort_key,
                              sort_dir=args.sort_dir,
                              sort=args.sort)
    shell_utils.translate_volume_keys(volumes)

    # Create a list of servers to which the volume is attached
    for vol in volumes:
        servers = [s.get('server_id') for s in vol.attachments]
        setattr(vol, 'attached_to', ','.join(map(str, servers)))

    if field_titles:
        key_list = ['ID'] + field_titles
    else:
        key_list = [
            'ID', 'Status', 'Name', 'Size', 'Volume Type', 'Bootable',
            'Attached to'
        ]
        # If all_tenants is specified, print
        # Tenant ID as well.
        if search_opts['all_tenants']:
            key_list.insert(1, 'Tenant ID')

    if args.sort_key or args.sort_dir or args.sort:
        sortby_index = None
    else:
        sortby_index = 0
    utils.print_list(volumes,
                     key_list,
                     exclude_unavailable=True,
                     sortby_index=sortby_index)