Example #1
0
 def __init__(self, endpoint, *args, **kwargs):
     """Initialize a new client for the Images v1 API."""
     endpoint, version = utils.strip_version(endpoint)
     self.version = version or 1.0
     self.http_client = http.HTTPClient(endpoint, *args, **kwargs)
     self.images = ImageManager(self.http_client)
     self.image_members = ImageMemberManager(self.http_client)
    def __init__(self, endpoint, **kwargs):
        endpoint, version = utils.strip_version(endpoint)
        self.version = version or 2.0
        self.http_client = http.HTTPClient(endpoint, **kwargs)

        self.schemas = schemas.Controller(self.http_client)

        self.images = images.Controller(self.http_client, self.schemas)
        self.image_tags = image_tags.Controller(self.http_client, self.schemas)
        self.image_members = image_members.Controller(self.http_client,
                                                      self.schemas)

        self.tasks = tasks.Controller(self.http_client, self.schemas)

        self.metadefs_resource_type = (metadefs.ResourceTypeController(
            self.http_client, self.schemas))

        self.metadefs_property = (metadefs.PropertyController(
            self.http_client, self.schemas))

        self.metadefs_object = (metadefs.ObjectController(
            self.http_client, self.schemas))

        self.metadefs_namespace = (metadefs.NamespaceController(
            self.http_client, self.schemas))
Example #3
0
 def __init__(self, endpoint, **kwargs):
     """Initialize a new client for the Images v1 API."""
     endpoint, version = utils.strip_version(endpoint)
     self.version = version or 1.0
     self.http_client = http.HTTPClient(endpoint, **kwargs)
     self.images = ImageManager(self.http_client)
     self.image_members = ImageMemberManager(self.http_client)
Example #4
0
def create_authenticated_client(args, name="glance client"):
    if type(args) == argparse.Namespace:
        args = dict(vars(args).items())

    for general_arg in ['insecure', 'timeout']:
        if general_arg not in args:
            args[general_arg] = None

    args['ssl_compression'] = True
    args['name'] = name
    # XXX: It would be much nicer if a well defined template was populated here, opposed to throwing the arguments into
    # a unstructured namespace
    args = argparse.Namespace(**args)

    endpoint = None
    url_version = None
    try:
        if args.os_image_url:
            endpoint = args.os_image_url
        endpoint, url_version = utils.strip_version(endpoint)
    except ValueError:
        pass

    try:
        api_version = int(args.os_image_api_version or url_version or 2)
        if api_version not in SUPPORTED_VERSIONS:
            raise ValueError
    except ValueError:
        msg = ("Invalid API version parameter. "
               "Supported values are %s" % SUPPORTED_VERSIONS)
        utils.exit(msg=msg)

    client, client_desc = _get_versioned_client(api_version, args)
    return client, client_desc
Example #5
0
    def __init__(self, endpoint, **kwargs):
        endpoint, version = utils.strip_version(endpoint)
        self.version = version or 2.0
        self.http_client = http.HTTPClient(endpoint, **kwargs)

        self.schemas = schemas.Controller(self.http_client)

        self.images = images.Controller(self.http_client, self.schemas)
        self.image_tags = image_tags.Controller(self.http_client,
                                                self.schemas)
        self.image_members = image_members.Controller(self.http_client,
                                                      self.schemas)

        self.tasks = tasks.Controller(self.http_client, self.schemas)

        self.metadefs_resource_type = (
            metadefs.ResourceTypeController(self.http_client, self.schemas))

        self.metadefs_property = (
            metadefs.PropertyController(self.http_client, self.schemas))

        self.metadefs_object = (
            metadefs.ObjectController(self.http_client, self.schemas))

        self.metadefs_namespace = (
            metadefs.NamespaceController(self.http_client, self.schemas))
Example #6
0
def Client(version=None, endpoint=None, session=None, *args, **kwargs):
    if session and endpoint:
        msg = ("You cannot provide an endpoint URL with the session. The "
               "endpoint will be retrieved from the auth plugin's catalog")
        raise RuntimeError(msg)

    elif not session:
        if version is not None:
            warnings.warn(("`version` keyword is being deprecated. Please pass"
                           " the version as part of the URL. "
                           "http://$HOST:$PORT/v$VERSION_NUMBER"),
                          DeprecationWarning)

        endpoint, url_version = utils.strip_version(endpoint)

        if not url_version and not version:
            msg = ("Please provide either the version or an url with the form "
                   "http://$HOST:$PORT/v$VERSION_NUMBER")
            raise RuntimeError(msg)

        version = int(version or url_version)

    module = utils.import_versioned_module(version, 'client')
    client_class = getattr(module, 'Client')
    return client_class(endpoint, *args, session=session, **kwargs)
Example #7
0
def Client(version=None, endpoint=None, *args, **kwargs):
    """Client for the OpenStack Images API.

    Generic client for the OpenStack Images API. See version classes
    for specific details.

    :param string version: The version of API to use. Note this is
                           deprecated and should be passed as part of the URL
                           (http://$HOST:$PORT/v$VERSION_NUMBER).
    """
    if version is not None:
        warnings.warn(("`version` keyword is being deprecated. Please pass the"
                       " version as part of the URL. "
                       "http://$HOST:$PORT/v$VERSION_NUMBER"),
                      DeprecationWarning)

    endpoint, url_version = utils.strip_version(endpoint)

    if not url_version and not version:
        msg = ("Please provide either the version or an url with the form "
               "http://$HOST:$PORT/v$VERSION_NUMBER")
        raise RuntimeError(msg)

    version = int(version or url_version)

    module = utils.import_versioned_module(version, 'client')
    client_class = getattr(module, 'Client')
    return client_class(endpoint, *args, **kwargs)
    def __init__(self, endpoint, type_name, type_version, **kwargs):
        endpoint, version = utils.strip_version(endpoint)
        self.version = version or 3.0
        self.http_client = http.HTTPClient(endpoint, **kwargs)

        self.type_name = type_name
        self.type_version = type_version

        self.artifacts = artifacts.Controller(self.http_client, self.type_name, self.type_version)
Example #9
0
 def __init__(self, endpoint, *args, **kwargs):
     self.http_client = http.HTTPClient(utils.strip_version(endpoint),
                                        *args, **kwargs)
     self.schemas = schemas.Controller(self.http_client)
     image_model = self._get_image_model()
     self.images = images.Controller(self.http_client, image_model)
     self.image_tags = image_tags.Controller(self.http_client, image_model)
     self.image_members = image_members.Controller(self.http_client,
                                                   self._get_member_model())
 def __init__(self, endpoint, *args, **kwargs):
     self.http_client = http.HTTPClient(utils.strip_version(endpoint),
                                        *args, **kwargs)
     self.schemas = schemas.Controller(self.http_client)
     image_model = self._get_image_model()
     self.images = images.Controller(self.http_client,
                                     image_model)
     self.image_tags = image_tags.Controller(self.http_client, image_model)
     self.image_members = image_members.Controller(self.http_client,
                                                   self._get_member_model())
Example #11
0
    def __init__(self, endpoint, type_name, type_version, **kwargs):
        endpoint, version = utils.strip_version(endpoint)
        self.version = version or '0.1'
        self.http_client = http.HTTPClient(endpoint, **kwargs)

        self.type_name = type_name
        self.type_version = type_version

        self.artifacts = artifacts.Controller(self.http_client, self.type_name,
                                              self.type_version, self.version)
Example #12
0
def Client(version=None, endpoint=None, session=None, *args, **kwargs):
    """Client for the OpenStack Images API.

    Generic client for the OpenStack Images API. See version classes
    for specific details.

    :param string version: The version of API to use.
    :param session: A keystoneauth1 session that should be used for transport.
    :type session: keystoneauth1.session.Session
    """
    # FIXME(jamielennox): Add a deprecation warning if no session is passed.
    # Leaving it as an option until we can ensure nothing break when we switch.
    if session:
        if endpoint:
            kwargs.setdefault('endpoint_override', endpoint)

            if not version:
                __, version = utils.strip_version(endpoint)

        if not version:
            msg = ("You must provide a client version when using session")
            raise RuntimeError(msg)

    else:
        if version is not None:
            warnings.warn(("`version` keyword is being deprecated. Please pass"
                           " the version as part of the URL. "
                           "http://$HOST:$PORT/v$VERSION_NUMBER"),
                          DeprecationWarning)

        endpoint, url_version = utils.strip_version(endpoint)
        version = version or url_version

        if not version:
            msg = ("Please provide either the version or an url with the form "
                   "http://$HOST:$PORT/v$VERSION_NUMBER")
            raise RuntimeError(msg)

    module = importutils.import_versioned_module('glanceclient', int(version),
                                                 'client')
    client_class = getattr(module, 'Client')
    return client_class(endpoint, *args, session=session, **kwargs)
Example #13
0
def Client(version=None, endpoint=None, session=None, *args, **kwargs):
    """Client for the OpenStack Images API.

    Generic client for the OpenStack Images API. See version classes
    for specific details.

    :param string version: The version of API to use.
    :param session: A keystoneclient session that should be used for transport.
    :type session: keystoneclient.session.Session
    """
    # FIXME(jamielennox): Add a deprecation warning if no session is passed.
    # Leaving it as an option until we can ensure nothing break when we switch.
    if session:
        if endpoint:
            kwargs.setdefault('endpoint_override', endpoint)

            if not version:
                __, version = utils.strip_version(endpoint)

        if not version:
            msg = ("You must provide a client version when using session")
            raise RuntimeError(msg)

    else:
        if version is not None:
            warnings.warn(("`version` keyword is being deprecated. Please pass"
                           " the version as part of the URL. "
                           "http://$HOST:$PORT/v$VERSION_NUMBER"),
                          DeprecationWarning)

        endpoint, url_version = utils.strip_version(endpoint)
        version = version or url_version

        if not version:
            msg = ("Please provide either the version or an url with the form "
                   "http://$HOST:$PORT/v$VERSION_NUMBER")
            raise RuntimeError(msg)

    module = utils.import_versioned_module(int(version), 'client')
    client_class = getattr(module, 'Client')
    return client_class(endpoint, *args, session=session, **kwargs)
Example #14
0
    def __init__(self, endpoint, type_name, type_version, **kwargs):
        endpoint, version = utils.strip_version(endpoint)
        # TODO(kzaitsev): start using this variable
        self.version = version or 0.1
        self.http_client = http.HTTPClient(endpoint, **kwargs)

        self.type_name = type_name
        self.type_version = type_version

        self.artifacts = artifacts.Controller(self.http_client,
                                              self.type_name,
                                              self.type_version)
Example #15
0
    def __init__(self, client_info):
        endpoint = utils.strip_version(client_info['endpoint'])
        kwargs = {'cacert': client_info['cacert'],
                  'insecure': client_info['insecure'],
                  'token': client_info['token']}

        if isinstance(endpoint, tuple):
            endpoint = endpoint[0]
        self.http_client = http.HTTPClient(endpoint, **kwargs)
        self.schemas = schemas.Controller(self.http_client)
        self.images = images.Controller(self.http_client, self.schemas)
        self.image_tags = image_tags.Controller(self.http_client, self.schemas)
        self.image_members = image_members.Controller(self.http_client,
                                                      self.schemas)
Example #16
0
def Client(version=None, endpoint=None, *args, **kwargs):
    if version is not None:
        warnings.warn(("`version` keyword is being deprecated. Please pass the"
                       " version as part of the URL. "
                       "http://$HOST:$PORT/v$VERSION_NUMBER"),
                      DeprecationWarning)

    endpoint, url_version = utils.strip_version(endpoint)

    if not url_version and not version:
        msg = ("Please provide either the version or an url with the form "
               "http://$HOST:$PORT/v$VERSION_NUMBER")
        raise RuntimeError(msg)

    version = int(version or url_version)

    module = utils.import_versioned_module(version, 'client')
    client_class = getattr(module, 'Client')
    return client_class(endpoint, *args, **kwargs)
Example #17
0
    def get_legacy_client(self,
                          service_key,
                          client_class=None,
                          interface_key=None,
                          pass_version_arg=True,
                          version=None,
                          **kwargs):
        """Return a legacy OpenStack client object for the given config.

        Most of the OpenStack python-*client libraries have the same
        interface for their client constructors, but there are several
        parameters one wants to pass given a :class:`CloudConfig` object.

        In the future, OpenStack API consumption should be done through
        the OpenStack SDK, but that's not ready yet. This is for getting
        Client objects from python-*client only.

        :param service_key: Generic key for service, such as 'compute' or
                            'network'
        :param client_class: Class of the client to be instantiated. This
                             should be the unversioned version if there
                             is one, such as novaclient.client.Client, or
                             the versioned one, such as
                             neutronclient.v2_0.client.Client if there isn't
        :param interface_key: (optional) Some clients, such as glanceclient
                              only accept the parameter 'interface' instead
                              of 'endpoint_type' - this is a get-out-of-jail
                              parameter for those until they can be aligned.
                              os-client-config understands this to be the
                              case if service_key is image, so this is really
                              only for use with other unknown broken clients.
        :param pass_version_arg: (optional) If a versioned Client constructor
                                 was passed to client_class, set this to
                                 False, which will tell get_client to not
                                 pass a version parameter. os-client-config
                                 already understand that this is the
                                 case for network, so it can be omitted in
                                 that case.
        :param version: (optional) Version string to override the configured
                                   version string.
        :param kwargs: (optional) keyword args are passed through to the
                       Client constructor, so this is in case anything
                       additional needs to be passed in.
        """
        if not client_class:
            client_class = _get_client(service_key)

        interface = self.get_interface(service_key)
        # trigger exception on lack of service
        endpoint = self.get_session_endpoint(service_key)
        endpoint_override = self.get_endpoint(service_key)

        if not interface_key:
            if service_key in ('image', 'key-manager'):
                interface_key = 'interface'
            else:
                interface_key = 'endpoint_type'

        if service_key == 'object-store':
            constructor_kwargs = dict(
                session=self.get_session(),
                os_options=dict(
                    service_type=self.get_service_type(service_key),
                    object_storage_url=endpoint_override,
                    region_name=self.region))
        else:
            constructor_kwargs = dict(
                session=self.get_session(),
                service_name=self.get_service_name(service_key),
                service_type=self.get_service_type(service_key),
                endpoint_override=endpoint_override,
                region_name=self.region)

        if service_key == 'image':
            # os-client-config does not depend on glanceclient, but if
            # the user passed in glanceclient.client.Client, which they
            # would need to do if they were requesting 'image' - then
            # they necessarily have glanceclient installed
            from glanceclient.common import utils as glance_utils
            endpoint, detected_version = glance_utils.strip_version(endpoint)
            # If the user has passed in a version, that's explicit, use it
            if not version:
                version = detected_version
            # If the user has passed in or configured an override, use it.
            # Otherwise, ALWAYS pass in an endpoint_override becuase
            # we've already done version stripping, so we don't want version
            # reconstruction to happen twice
            if not endpoint_override:
                constructor_kwargs['endpoint_override'] = endpoint
        constructor_kwargs.update(kwargs)
        if service_key == 'object-store':
            constructor_kwargs['os_options'][interface_key] = interface
        else:
            constructor_kwargs[interface_key] = interface
        if pass_version_arg and service_key != 'object-store':
            if not version:
                version = self.get_api_version(service_key)
            # Temporary workaround while we wait for python-openstackclient
            # to be able to handle 2.0 which is what neutronclient expects
            if service_key == 'network' and version == '2':
                version = '2.0'
            if service_key == 'identity':
                # Workaround for bug#1513839
                if 'endpoint' not in constructor_kwargs:
                    endpoint = self.get_session_endpoint('identity')
                    constructor_kwargs['endpoint'] = endpoint
            if service_key == 'network':
                constructor_kwargs['api_version'] = version
            else:
                constructor_kwargs['version'] = version
        if service_key == 'database':
            # TODO(mordred) Remove when https://review.openstack.org/314032
            # has landed and released. We're passing in a Session, but the
            # trove Client object has username and password as required
            # args
            constructor_kwargs['username'] = None
            constructor_kwargs['password'] = None

        return client_class(**constructor_kwargs)
Example #18
0
    def main(self, argv):

        def _get_subparser(api_version):
            try:
                return self.get_subcommand_parser(api_version, argv)
            except ImportError as e:
                if not str(e):
                    # Add a generic import error message if the raised
                    # ImportError has none.
                    raise ImportError('Unable to import module. Re-run '
                                      'with --debug for more info.')
                raise

        # Parse args once to find version

        # NOTE(flepied) Under Python3, parsed arguments are removed
        # from the list so make a copy for the first parsing
        base_argv = copy.deepcopy(argv)
        parser = self.get_base_parser(argv)
        (options, args) = parser.parse_known_args(base_argv)

        try:
            # NOTE(flaper87): Try to get the version from the
            # image-url first. If no version was specified, fallback
            # to the api-image-version arg. If both of these fail then
            # fallback to the minimum supported one and let keystone
            # do the magic.
            endpoint = self._get_image_url(options)
            endpoint, url_version = utils.strip_version(endpoint)
        except ValueError:
            # NOTE(flaper87): ValueError is raised if no endpoint is provided
            url_version = None

        # build available subcommands based on version
        try:
            api_version = int(options.os_image_api_version or url_version or 2)
            if api_version not in SUPPORTED_VERSIONS:
                raise ValueError
        except ValueError:
            msg = ("Invalid API version parameter. "
                   "Supported values are %s" % SUPPORTED_VERSIONS)
            utils.exit(msg=msg)

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

        # NOTE(sigmavirus24): Above, args is defined as the left over
        # arguments from parser.parse_known_args(). This allows us to
        # skip any parameters to command-line flags that may have been passed
        # to glanceclient, e.g., --os-auth-token.
        self._fixup_subcommand(args, argv)

        # short-circuit and deal with help command right away.
        sub_parser = _get_subparser(api_version)
        args = sub_parser.parse_args(argv)

        if args.func == self.do_help:
            self.do_help(args, parser=sub_parser)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not options.os_image_api_version and api_version == 2:
            switch_version = True
            client = self._get_versioned_client('2', args)

            resp, body = client.http_client.get('/versions')

            for version in body['versions']:
                if version['id'].startswith('v2'):
                    # NOTE(flaper87): We know v2 is enabled in the server,
                    # which means we should be able to get the schemas and
                    # move on.
                    switch_version = self._cache_schemas(options, client)
                    break

            if switch_version:
                print('WARNING: The client is falling back to v1 because'
                      ' the accessing to v2 failed. This behavior will'
                      ' be removed in future versions', file=sys.stderr)
                api_version = 1

        sub_parser = _get_subparser(api_version)

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

        # NOTE(flaper87): Make sure we re-use the password input if we
        # have one. This may happen if the schemas were downloaded in
        # this same command. Password will be asked to download the
        # schemas and then for the operations below.
        if not args.os_password and options.os_password:
            args.os_password = options.os_password

        if args.debug:
            # Set up the root logger to debug so that the submodules can
            # print debug messages
            logging.basicConfig(level=logging.DEBUG)
            # for iso8601 < 0.1.11
            logging.getLogger('iso8601').setLevel(logging.WARNING)
        LOG = logging.getLogger('glanceclient')
        LOG.addHandler(logging.StreamHandler())
        LOG.setLevel(logging.DEBUG if args.debug else logging.INFO)

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

        client = self._get_versioned_client(api_version, args)

        try:
            args.func(client, args)
        except exc.Unauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
        finally:
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print("Profiling trace ID: %s" % trace_id)
                print("To display trace use next command:\n"
                      "osprofiler trace show --html %s " % trace_id)
 def __init__(self, endpoint, *args, **kwargs):
     """Initialize a new client for the Images v1 API."""
     self.http_client = http.HTTPClient(utils.strip_version(endpoint),
                                        *args, **kwargs)
     self.images = images.ImageManager(self.http_client)
     self.image_members = image_members.ImageMemberManager(self.http_client)
    def main(self, argv):

        def _get_subparser(api_version):
            try:
                return self.get_subcommand_parser(api_version)
            except ImportError as e:
                if options.debug:
                    traceback.print_exc()
                if not str(e):
                    # Add a generic import error message if the raised
                    # ImportError has none.
                    raise ImportError('Unable to import module. Re-run '
                                      'with --debug for more info.')
                raise
            except Exception:
                if options.debug:
                    traceback.print_exc()
                raise

        # Parse args once to find version

        # NOTE(flepied) Under Python3, parsed arguments are removed
        # from the list so make a copy for the first parsing
        base_argv = copy.deepcopy(argv)
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(base_argv)

        try:
            # NOTE(flaper87): Try to get the version from the
            # image-url first. If no version was specified, fallback
            # to the api-image-version arg. If both of these fail then
            # fallback to the minimum supported one and let keystone
            # do the magic.
            endpoint = self._get_image_url(options)
            endpoint, url_version = utils.strip_version(endpoint)
        except ValueError:
            # NOTE(flaper87): ValueError is raised if no endpoint is povided
            url_version = None

        # build available subcommands based on version
        try:
            api_version = int(options.os_image_api_version or url_version or 2)
            if api_version not in SUPPORTED_VERSIONS:
                raise ValueError
        except ValueError:
            msg = ("Invalid API version parameter. "
                   "Supported values are %s" % SUPPORTED_VERSIONS)
            utils.exit(msg=msg)

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

        # Short-circuit and deal with help command right away.
        sub_parser = _get_subparser(api_version)
        args = sub_parser.parse_args(argv)

        if args.func == self.do_help:
            self.do_help(args, parser=sub_parser)
            return 0
        elif args.func == self.do_bash_completion:
            self.do_bash_completion(args)
            return 0

        if not options.os_image_api_version and api_version == 2:
            switch_version = True
            client = self._get_versioned_client('2', args)

            resp, body = client.http_client.get('/versions')

            for version in body['versions']:
                if version['id'].startswith('v2'):
                    # NOTE(flaper87): We know v2 is enabled in the server,
                    # which means we should be able to get the schemas and
                    # move on.
                    switch_version = self._cache_schemas(options, client)
                    break

            if switch_version:
                print('WARNING: The client is falling back to v1 because'
                      ' the accessing to v2 failed. This behavior will'
                      ' be removed in future versions', file=sys.stderr)
                api_version = 1

        sub_parser = _get_subparser(api_version)

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

        # NOTE(flaper87): Make sure we re-use the password input if we
        # have one. This may happen if the schemas were downloaded in
        # this same command. Password will be asked to download the
        # schemas and then for the operations below.
        if not args.os_password and options.os_password:
            args.os_password = options.os_password

        LOG = logging.getLogger('glanceclient')
        LOG.addHandler(logging.StreamHandler())
        LOG.setLevel(logging.DEBUG if args.debug else logging.INFO)

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

        client = self._get_versioned_client(api_version, args)

        try:
            args.func(client, args)
        except exc.Unauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
        except Exception:
            # NOTE(kragniz) Print any exceptions raised to stderr if the
            # --debug flag is set
            if args.debug:
                traceback.print_exc()
            raise
        finally:
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print("Profiling trace ID: %s" % trace_id)
                print("To display trace use next command:\n"
                      "osprofiler trace show --html %s " % trace_id)
    def get_legacy_client(
            self, service_key, client_class=None, interface_key=None,
            pass_version_arg=True, version=None, **kwargs):
        """Return a legacy OpenStack client object for the given config.

        Most of the OpenStack python-*client libraries have the same
        interface for their client constructors, but there are several
        parameters one wants to pass given a :class:`CloudConfig` object.

        In the future, OpenStack API consumption should be done through
        the OpenStack SDK, but that's not ready yet. This is for getting
        Client objects from python-*client only.

        :param service_key: Generic key for service, such as 'compute' or
                            'network'
        :param client_class: Class of the client to be instantiated. This
                             should be the unversioned version if there
                             is one, such as novaclient.client.Client, or
                             the versioned one, such as
                             neutronclient.v2_0.client.Client if there isn't
        :param interface_key: (optional) Some clients, such as glanceclient
                              only accept the parameter 'interface' instead
                              of 'endpoint_type' - this is a get-out-of-jail
                              parameter for those until they can be aligned.
                              os-client-config understands this to be the
                              case if service_key is image, so this is really
                              only for use with other unknown broken clients.
        :param pass_version_arg: (optional) If a versioned Client constructor
                                 was passed to client_class, set this to
                                 False, which will tell get_client to not
                                 pass a version parameter. os-client-config
                                 already understand that this is the
                                 case for network, so it can be omitted in
                                 that case.
        :param version: (optional) Version string to override the configured
                                   version string.
        :param kwargs: (optional) keyword args are passed through to the
                       Client constructor, so this is in case anything
                       additional needs to be passed in.
        """
        if not client_class:
            client_class = _get_client(service_key)

        # Because of course swift is different
        if service_key == 'object-store':
            return self._get_swift_client(client_class=client_class, **kwargs)
        interface = self.get_interface(service_key)
        # trigger exception on lack of service
        endpoint = self.get_session_endpoint(service_key)
        endpoint_override = self.get_endpoint(service_key)

        if not interface_key:
            if service_key == 'image':
                interface_key = 'interface'
            else:
                interface_key = 'endpoint_type'

        constructor_kwargs = dict(
            session=self.get_session(),
            service_name=self.get_service_name(service_key),
            service_type=self.get_service_type(service_key),
            endpoint_override=endpoint_override,
            region_name=self.region)

        if service_key == 'image':
            # os-client-config does not depend on glanceclient, but if
            # the user passed in glanceclient.client.Client, which they
            # would need to do if they were requesting 'image' - then
            # they necessarily have glanceclient installed
            from glanceclient.common import utils as glance_utils
            endpoint, detected_version = glance_utils.strip_version(endpoint)
            # If the user has passed in a version, that's explicit, use it
            if not version:
                version = detected_version
            # If the user has passed in or configured an override, use it.
            # Otherwise, ALWAYS pass in an endpoint_override becuase
            # we've already done version stripping, so we don't want version
            # reconstruction to happen twice
            if not endpoint_override:
                constructor_kwargs['endpoint_override'] = endpoint
        constructor_kwargs.update(kwargs)
        constructor_kwargs[interface_key] = interface
        constructor_args = []
        if pass_version_arg:
            if not version:
                version = self.get_api_version(service_key)
            # Temporary workaround while we wait for python-openstackclient
            # to be able to handle 2.0 which is what neutronclient expects
            if service_key == 'network' and version == '2':
                version = '2.0'
            if service_key == 'identity':
                # Workaround for bug#1513839
                if 'endpoint' not in constructor_kwargs:
                    endpoint = self.get_session_endpoint('identity')
                    constructor_kwargs['endpoint'] = endpoint
            constructor_args.append(version)

        return client_class(*constructor_args, **constructor_kwargs)
Example #22
0
    def main(self, argv):
        # Parse args once to find version

        # NOTE(flepied) Under Python3, parsed arguments are removed
        # from the list so make a copy for the first parsing
        base_argv = copy.deepcopy(argv)
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(base_argv)

        try:
            # NOTE(flaper87): Try to get the version from the
            # image-url first. If no version was specified, fallback
            # to the api-image-version arg. If both of these fail then
            # fallback to the minimum supported one and let keystone
            # do the magic.
            endpoint = self._get_image_url(options)
            endpoint, url_version = utils.strip_version(endpoint)
        except ValueError:
            # NOTE(flaper87): ValueError is raised if no endpoint is povided
            url_version = None

        # build available subcommands based on version
        try:
            api_version = int(options.os_image_api_version or url_version or 1)
            if api_version not in SUPPORTED_VERSIONS:
                raise ValueError
        except ValueError:
            msg = ("Invalid API version parameter. "
                   "Supported values are %s" % SUPPORTED_VERSIONS)
            utils.exit(msg=msg)

        if api_version == 2:
            self._cache_schemas(options)

        try:
            subcommand_parser = self.get_subcommand_parser(api_version)
        except ImportError as e:
            if options.debug:
                traceback.print_exc()
            if not str(e):
                # Add a generic import error message if the raised ImportError
                # has none.
                raise ImportError('Unable to import module. Re-run '
                                  'with --debug for more info.')
            raise
        except Exception:
            if options.debug:
                traceback.print_exc()
            raise

        self.parser = subcommand_parser

        # Handle top-level --help/-h before attempting to parse
        # a command off the command line
        if 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

        LOG = logging.getLogger('glanceclient')
        LOG.addHandler(logging.StreamHandler())
        LOG.setLevel(logging.DEBUG if args.debug else logging.INFO)

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

        client = self._get_versioned_client(api_version, args,
                                            force_auth=False)

        try:
            args.func(client, args)
        except exc.Unauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
        except Exception:
            # NOTE(kragniz) Print any exceptions raised to stderr if the
            # --debug flag is set
            if args.debug:
                traceback.print_exc()
            raise
        finally:
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print("Profiling trace ID: %s" % trace_id)
                print("To display trace use next command:\n"
                      "osprofiler trace show --html %s " % trace_id)
Example #23
0
File: shell.py Project: hbkqh/patch
    def main(self, argv):
        # Parse args once to find version

        # NOTE(flepied) Under Python3, parsed arguments are removed
        # from the list so make a copy for the first parsing
        base_argv = copy.deepcopy(argv)
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(base_argv)

        span_host = tomograph.getHost()
        span_name = ' '.join(sys.argv)
        tomograph.start("glanceclient-shell", span_name, span_host, 0)

        try:
            # NOTE(flaper87): Try to get the version from the
            # image-url first. If no version was specified, fallback
            # to the api-image-version arg. If both of these fail then
            # fallback to the minimum supported one and let keystone
            # do the magic.
            endpoint = self._get_image_url(options)
            endpoint, url_version = utils.strip_version(endpoint)
        except ValueError:
            # NOTE(flaper87): ValueError is raised if no endpoint is povided
            url_version = None

        # build available subcommands based on version
        try:
            api_version = int(options.os_image_api_version or url_version or 2)
            if api_version not in SUPPORTED_VERSIONS:
                raise ValueError
        except ValueError:
            msg = ("Invalid API version parameter. "
                   "Supported values are %s" % SUPPORTED_VERSIONS)
            utils.exit(msg=msg)

        if api_version == 2:
            switch_version = self._cache_schemas(options)
            if switch_version:
                print('WARNING: The client is falling back to v1 because'
                      ' the accessing to v2 failed. This behavior will'
                      ' be removed in future versions')
                api_version = 1

        try:
            subcommand_parser = self.get_subcommand_parser(api_version)
        except ImportError as e:
            if options.debug:
                traceback.print_exc()
            if not str(e):
                # Add a generic import error message if the raised ImportError
                # has none.
                raise ImportError('Unable to import module. Re-run '
                                  'with --debug for more info.')
            raise
        except Exception:
            if options.debug:
                traceback.print_exc()
            raise

        self.parser = subcommand_parser

        # Handle top-level --help/-h before attempting to parse
        # a command off the command line
        if 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

        LOG = logging.getLogger('glanceclient')
        LOG.addHandler(logging.StreamHandler())
        LOG.setLevel(logging.DEBUG if args.debug else logging.INFO)

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

        client = self._get_versioned_client(api_version,
                                            args,
                                            force_auth=False)

        try:
            # pdb.set_trace()
            args.func(client, args)
        except exc.Unauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
        except Exception:
            # NOTE(kragniz) Print any exceptions raised to stderr if the
            # --debug flag is set
            if args.debug:
                traceback.print_exc()
            raise
        finally:
            tomograph.stop(span_name)
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print("Profiling trace ID: %s" % trace_id)
                print("To display trace use next command:\n"
                      "osprofiler trace show --html %s " % trace_id)
Example #24
0
    def main(self, argv):
        # Parse args once to find version

        #NOTE(flepied) Under Python3, parsed arguments are removed
        # from the list so make a copy for the first parsing
        base_argv = copy.deepcopy(argv)
        parser = self.get_base_parser()
        (options, args) = parser.parse_known_args(base_argv)

        try:
            # NOTE(flaper87): Try to get the version from the
            # image-url first. If no version was specified, fallback
            # to the api-image-version arg. If both of these fail then
            # fallback to the minimum supported one and let keystone
            # do the magic.
            endpoint = self._get_image_url(options)
            endpoint, url_version = utils.strip_version(endpoint)
        except ValueError:
            # NOTE(flaper87): ValueError is raised if no endpoint is povided
            url_version = None

        # build available subcommands based on version
        try:
            api_version = int(options.os_image_api_version or url_version or 1)
        except ValueError:
            print("Invalid API version parameter")
            utils.exit()

        if api_version == 2:
            self._cache_schemas(options)

        subcommand_parser = self.get_subcommand_parser(api_version)
        self.parser = subcommand_parser

        # Handle top-level --help/-h before attempting to parse
        # a command off the command line
        if 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

        LOG = logging.getLogger('glanceclient')
        LOG.addHandler(logging.StreamHandler())
        LOG.setLevel(logging.DEBUG if args.debug else logging.INFO)

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

        client = self._get_versioned_client(api_version, args,
                                            force_auth=False)

        try:
            args.func(client, args)
        except exc.Unauthorized:
            raise exc.CommandError("Invalid OpenStack Identity credentials.")
        except Exception:
            #NOTE(kragniz) Print any exceptions raised to stderr if the --debug
            # flag is set
            if args.debug:
                traceback.print_exc()
            raise
        finally:
            if profile:
                trace_id = osprofiler_profiler.get().get_base_id()
                print("Profiling trace ID: %s" % trace_id)
                print("To display trace use next command:\n"
                      "osprofiler trace show --html %s " % trace_id)
    def get_legacy_client(
            self, service_key, client_class=None, interface_key=None,
            pass_version_arg=True, version=None, min_version=None,
            max_version=None, **kwargs):
        """Return a legacy OpenStack client object for the given config.

        Most of the OpenStack python-*client libraries have the same
        interface for their client constructors, but there are several
        parameters one wants to pass given a :class:`CloudConfig` object.

        In the future, OpenStack API consumption should be done through
        the OpenStack SDK, but that's not ready yet. This is for getting
        Client objects from python-*client only.

        :param service_key: Generic key for service, such as 'compute' or
                            'network'
        :param client_class: Class of the client to be instantiated. This
                             should be the unversioned version if there
                             is one, such as novaclient.client.Client, or
                             the versioned one, such as
                             neutronclient.v2_0.client.Client if there isn't
        :param interface_key: (optional) Some clients, such as glanceclient
                              only accept the parameter 'interface' instead
                              of 'endpoint_type' - this is a get-out-of-jail
                              parameter for those until they can be aligned.
                              os-client-config understands this to be the
                              case if service_key is image, so this is really
                              only for use with other unknown broken clients.
        :param pass_version_arg: (optional) If a versioned Client constructor
                                 was passed to client_class, set this to
                                 False, which will tell get_client to not
                                 pass a version parameter. os-client-config
                                 already understand that this is the
                                 case for network, so it can be omitted in
                                 that case.
        :param version: (optional) Version string to override the configured
                                   version string.
        :param min_version: (options) Minimum version acceptable.
        :param max_version: (options) Maximum version acceptable.
        :param kwargs: (optional) keyword args are passed through to the
                       Client constructor, so this is in case anything
                       additional needs to be passed in.
        """
        if not client_class:
            client_class = _get_client(service_key)

        interface = self.get_interface(service_key)
        # trigger exception on lack of service
        endpoint = self.get_session_endpoint(
            service_key, min_version=min_version, max_version=max_version)
        endpoint_override = self.get_endpoint(service_key)

        if service_key == 'object-store':
            constructor_kwargs = dict(
                session=self.get_session(),
                os_options=dict(
                    service_type=self.get_service_type(service_key),
                    object_storage_url=endpoint_override,
                    region_name=self.region))
        else:
            constructor_kwargs = dict(
                session=self.get_session(),
                service_name=self.get_service_name(service_key),
                service_type=self.get_service_type(service_key),
                endpoint_override=endpoint_override,
                region_name=self.region)

        if service_key == 'image':
            # os-client-config does not depend on glanceclient, but if
            # the user passed in glanceclient.client.Client, which they
            # would need to do if they were requesting 'image' - then
            # they necessarily have glanceclient installed
            from glanceclient.common import utils as glance_utils
            endpoint, detected_version = glance_utils.strip_version(endpoint)
            # If the user has passed in a version, that's explicit, use it
            if not version:
                version = detected_version
            # If the user has passed in or configured an override, use it.
            # Otherwise, ALWAYS pass in an endpoint_override becuase
            # we've already done version stripping, so we don't want version
            # reconstruction to happen twice
            if not endpoint_override:
                constructor_kwargs['endpoint_override'] = endpoint
        constructor_kwargs.update(kwargs)
        if pass_version_arg and service_key != 'object-store':
            if not version:
                version = self.get_api_version(service_key)
            if not version and service_key == 'volume':
                from cinderclient import client as cinder_client
                version = cinder_client.get_volume_api_from_url(endpoint)
            # Temporary workaround while we wait for python-openstackclient
            # to be able to handle 2.0 which is what neutronclient expects
            if service_key == 'network' and version == '2':
                version = '2.0'
            if service_key == 'identity':
                # Workaround for bug#1513839
                if 'endpoint' not in constructor_kwargs:
                    endpoint = self.get_session_endpoint('identity')
                    constructor_kwargs['endpoint'] = endpoint
            if service_key == 'network':
                constructor_kwargs['api_version'] = version
            elif service_key == 'baremetal':
                if version != '1':
                    # Set Ironic Microversion
                    constructor_kwargs['os_ironic_api_version'] = version
                # Version arg is the major version, not the full microstring
                constructor_kwargs['version'] = version[0]
            else:
                constructor_kwargs['version'] = version
            if min_version and min_version > float(version):
                raise exceptions.OpenStackConfigVersionException(
                    "Minimum version {min_version} requested but {version}"
                    " found".format(min_version=min_version, version=version),
                    version=version)
            if max_version and max_version < float(version):
                raise exceptions.OpenStackConfigVersionException(
                    "Maximum version {max_version} requested but {version}"
                    " found".format(max_version=max_version, version=version),
                    version=version)
        if service_key == 'database':
            # TODO(mordred) Remove when https://review.openstack.org/314032
            # has landed and released. We're passing in a Session, but the
            # trove Client object has username and password as required
            # args
            constructor_kwargs['username'] = None
            constructor_kwargs['password'] = None

        if not interface_key:
            if service_key in ('image', 'key-manager'):
                interface_key = 'interface'
            elif (service_key == 'identity'
                  and version and version.startswith('3')):
                interface_key = 'interface'
            else:
                interface_key = 'endpoint_type'
        if service_key == 'object-store':
            constructor_kwargs['os_options'][interface_key] = interface
        else:
            constructor_kwargs[interface_key] = interface

        return client_class(**constructor_kwargs)