def _get_session(): global _session if not _session: auth = ka_loading.load_auth_from_conf_options(CONF, GROUP) _session = ka_loading.load_session_from_conf_options( CONF, GROUP, auth=auth) return _session
def __init__(self): auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova') session = ks_loading.load_session_from_conf_options( cfg.CONF, 'nova', auth=auth) extensions = [ ext for ext in nova_client.discover_extensions(NOVA_API_VERSION) if ext.name == "server_external_events"] self.nclient = nova_client.Client( NOVA_API_VERSION, session=session, region_name=cfg.CONF.nova.region_name, endpoint_type=cfg.CONF.nova.endpoint_type, extensions=extensions) self.batch_notifier = batch_notifier.BatchNotifier( cfg.CONF.send_events_interval, self.send_events) # register callbacks for events pertaining resources affecting Nova callback_resources = ( resources.FLOATING_IP, resources.PORT, ) for resource in callback_resources: registry.subscribe(self._send_nova_notification, resource, events.BEFORE_RESPONSE)
def __init__(self): # FIXME(jamielennox): A notifier is being created for each Controller # and each Notifier is handling it's own auth. That means that we are # authenticating the exact same thing len(controllers) times. This # should be an easy thing to optimize. # FIXME(kevinbenton): remove this comment and the one above once the # switch to pecan is complete since only one notifier is constructed # in the pecan notification hook. auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova') session = ks_loading.load_session_from_conf_options( cfg.CONF, 'nova', auth=auth) extensions = [ ext for ext in nova_client.discover_extensions(NOVA_API_VERSION) if ext.name == "server_external_events"] self.nclient = nova_client.Client( NOVA_API_VERSION, session=session, region_name=cfg.CONF.nova.region_name, endpoint_type=cfg.CONF.nova.endpoint_type, extensions=extensions) self.batch_notifier = batch_notifier.BatchNotifier( cfg.CONF.send_events_interval, self.send_events) # register callbacks for events pertaining resources affecting Nova callback_resources = ( resources.FLOATING_IP, resources.PORT, ) for resource in callback_resources: registry.subscribe(self._send_nova_notification, resource, events.BEFORE_RESPONSE)
def __init__(self, **kwargs): super(GnocchiStorage, self).__init__(**kwargs) conf = kwargs.get('conf') or ck_utils.load_conf( CONF.collect.metrics_conf) self.conf = validate_conf(conf) self.auth = ks_loading.load_auth_from_conf_options( CONF, GNOCCHI_STORAGE_OPTS) self.session = ks_loading.load_session_from_conf_options( CONF, GNOCCHI_STORAGE_OPTS, auth=self.auth) self._conn = gclient.Client( '1', session=self.session, adapter_options={'connect_retries': 3, 'interface': CONF.storage_gnocchi.interface}) self._archive_policy_name = ( CONF.storage_gnocchi.archive_policy_name) self._archive_policy_definition = json.loads( CONF.storage_gnocchi.archive_policy_definition) self._period = kwargs.get('period') or CONF.collect.period self._measurements = dict() self._resource_type_data = dict() self._init_resource_types()
def _get_barbican_client(self, ctxt): """Creates a client to connect to the Barbican service. :param ctxt: the user context for authentication :return: a Barbican Client object :raises Forbidden: if the ctxt is None """ # Confirm context is provided, if not raise forbidden if not ctxt: msg = _("User is not authorized to use key manager.") LOG.error(msg) raise exception.Forbidden(msg) if not hasattr(ctxt, 'project_id') or ctxt.project_id is None: msg = _("Unable to create Barbican Client without project_id.") LOG.error(msg) raise exception.KeyManagerError(msg) # If same context, return cached barbican client if self._barbican_client and self._current_context == ctxt: return self._barbican_client try: _SESSION = ks_loading.load_session_from_conf_options( CONF, BARBICAN_OPT_GROUP) auth = ctxt.get_auth_plugin() service_type, service_name, interface = (CONF. barbican. catalog_info. split(':')) region_name = CONF.barbican.os_region_name service_parameters = {'service_type': service_type, 'service_name': service_name, 'interface': interface, 'region_name': region_name} if CONF.barbican.endpoint_template: self._base_url = (CONF.barbican.endpoint_template % ctxt.to_dict()) else: self._base_url = _SESSION.get_endpoint( auth, **service_parameters) # the barbican endpoint can't have the '/v1' on the end self._barbican_endpoint = self._base_url.rpartition('/')[0] sess = session.Session(auth=auth) self._barbican_client = barbican_client.Client( session=sess, endpoint=self._barbican_endpoint) self._current_context = ctxt except Exception as e: with excutils.save_and_reraise_exception(): LOG.error(_LE("Error creating Barbican client: %s"), e) return self._barbican_client
def get_client_on_behalf_user(conf, auth_plugin, trust_id=None, requests_session=None): """Return a client for keystone v3 endpoint, optionally using a trust.""" session = ka_loading.load_session_from_conf_options( conf, CFG_GROUP, auth=auth_plugin, session=requests_session ) return ks_client_v3.Client(session=session, trust_id=trust_id)
def get_session(conf, requests_session=None): """Get an aodh service credentials auth session.""" auth_plugin = ka_loading.load_auth_from_conf_options(conf, CFG_GROUP) session = ka_loading.load_session_from_conf_options( conf, CFG_GROUP, auth=auth_plugin, session=requests_session ) return session
def _barbican_admin_init(self): # Import auth_token to have keystone_authtoken settings setup. auth = loading.load_auth_from_conf_options( cfg.CONF, 'keystone_authtoken') sess = loading.load_session_from_conf_options( cfg.CONF, 'keystone_authtoken', auth=auth) return barbicanclient.Client(session=sess)
def get_session(requests_session=None): """Get a ceilometer service credentials auth session.""" auth_plugin = ka_loading.load_auth_from_conf_options(cfg.CONF, CFG_GROUP) session = ka_loading.load_session_from_conf_options( cfg.CONF, CFG_GROUP, auth=auth_plugin, session=requests_session ) return session
def _get_keystone_session(self): auth = ka_loading.load_auth_from_conf_options(cfg.CONF, _CLIENTS_AUTH_GROUP) sess = ka_loading.load_session_from_conf_options(cfg.CONF, _CLIENTS_AUTH_GROUP, auth=auth) return sess
def get_admin_session(): """Returns a keystone session from Mistral's service credentials.""" if CONF.keystone_authtoken.auth_type is None: auth = auth_plugins.Password( CONF.keystone_authtoken.www_authenticate_uri, username=CONF.keystone_authtoken.admin_user, password=CONF.keystone_authtoken.admin_password, project_name=CONF.keystone_authtoken.admin_tenant_name, # NOTE(jaosorior): Once mistral supports keystone v3 properly, we # can fetch the following values from the configuration. user_domain_name='Default', project_domain_name='Default') return ks_session.Session(auth=auth) else: auth = loading.load_auth_from_conf_options( CONF, 'keystone_authtoken' ) return loading.load_session_from_conf_options( CONF, 'keystone', auth=auth )
def _get_client(self, retry_on_conflict=True): max_retries = CONF.ironic.api_max_retries if retry_on_conflict else 1 retry_interval = (CONF.ironic.api_retry_interval if retry_on_conflict else 0) # If we've already constructed a valid, authed client, just return # that. if retry_on_conflict and self._cached_client is not None: return self._cached_client auth_plugin = self._get_auth_plugin() sess = ks_loading.load_session_from_conf_options(CONF, IRONIC_GROUP.name, auth=auth_plugin) # Retries for Conflict exception kwargs = {} kwargs['max_retries'] = max_retries kwargs['retry_interval'] = retry_interval kwargs['os_ironic_api_version'] = '%d.%d' % IRONIC_API_VERSION # NOTE(clenimar/efried): by default, the endpoint is taken from the # service catalog. Use `endpoint_override` if you want to override it. if CONF.ironic.api_endpoint: # NOTE(efried): `api_endpoint` still overrides service catalog and # `endpoint_override` conf options. This will be removed in a # future release. ironic_url = CONF.ironic.api_endpoint else: try: ksa_adap = utils.get_ksa_adapter( nova.conf.ironic.DEFAULT_SERVICE_TYPE, ksa_auth=auth_plugin, ksa_session=sess, min_version=IRONIC_API_VERSION, max_version=(IRONIC_API_VERSION[0], ks_disc.LATEST)) ironic_url = ksa_adap.get_endpoint() except exception.ServiceNotFound: # NOTE(efried): No reason to believe service catalog lookup # won't also fail in ironic client init, but this way will # yield the expected exception/behavior. ironic_url = None try: cli = ironic.client.get_client(IRONIC_API_VERSION[0], ironic_url=ironic_url, session=sess, **kwargs) # Cache the client so we don't have to reconstruct and # reauthenticate it every time we need it. if retry_on_conflict: self._cached_client = cli except ironic.exc.Unauthorized: msg = _("Unable to authenticate Ironic client.") LOG.error(msg) raise exception.NovaException(msg) return cli
def get_neutron_client(*args, **kwargs): auth_plugin = ks_loading.load_auth_from_conf_options( cfg.CONF, kuryr_config.neutron_group.name) session = ks_loading.load_session_from_conf_options(cfg.CONF, 'neutron', auth=auth_plugin) return client.Client(session=session, auth=auth_plugin, endpoint_type=cfg.CONF.neutron.endpoint_type)
def get_session(conf, requests_session=None, group=None, timeout=None): """Get a ceilometer service credentials auth session.""" group = group or DEFAULT_GROUP auth_plugin = ka_loading.load_auth_from_conf_options(conf, group) kwargs = {'auth': auth_plugin, 'session': requests_session} if timeout is not None: kwargs['timeout'] = timeout session = ka_loading.load_session_from_conf_options(conf, group, **kwargs) return session
def _get_glance_client(self, project_id=None): if project_id: auth_plugin = loading.load_auth_from_conf_options( CONF, CFG_GROUP, project_id=project_id) else: auth_plugin = loading.load_auth_from_conf_options(CONF, CFG_GROUP) session = loading.load_session_from_conf_options(CONF, CFG_GROUP, auth=auth_plugin) return glanceclient.client.Client(2, session=session)
def get_session(group): auth = ironic_auth.load_auth(CONF, group) or _get_legacy_auth() if not auth: msg = _("Failed to load auth from either [%(new)s] or [%(old)s] " "config sections.") raise exception.ConfigInvalid(message=msg, new=group, old=ironic_auth.LEGACY_SECTION) session = kaloading.load_session_from_conf_options( CONF, group, auth=auth) return session
def get_session(self): """Initializes a Keystone session. :return: a Keystone Session object """ if not self._session: self._session = ks_loading.load_session_from_conf_options( cfg.CONF, self.section, auth=self.get_auth()) return self._session
def __init__(self): auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova') session = ks_loading.load_session_from_conf_options( cfg.CONF, 'nova', auth=auth) self.nclient = nclient.Client( n_nova.NOVA_API_VERSION, session=session, region_name=cfg.CONF.nova.region_name, endpoint_type=cfg.CONF.nova.endpoint_type)
def _session_and_auth(context): # Session is cached, but auth needs to be pulled from context each time. global _SESSION if not _SESSION: _SESSION = ks_loading.load_session_from_conf_options( CONF, nova.conf.glance.glance_group.name) auth = service_auth.get_auth_plugin(context) return _SESSION, auth
def __init__(self): auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova') self.session = ks_loading.load_session_from_conf_options( cfg.CONF, 'nova', auth=auth) self.extensions = [ ext for ext in nova_client.discover_extensions(NOVA_API_VERSION) if ext.name == "server_external_events"] self.batch_notifier = batch_notifier.BatchNotifier( cfg.CONF.send_events_interval, self.send_events)
def verify_project_id(context, project_id): """verify that a project_id exists. This attempts to verify that a project id exists. If it does not, an HTTPBadRequest is emitted. """ session = ksa_loading.load_session_from_conf_options( CONF, 'keystone', auth=context.get_auth_plugin()) adap = ksa_loading.load_adapter_from_conf_options( CONF, 'keystone', session=session, min_version=(3, 0), max_version=(3, 'latest')) try: resp = adap.get('/projects/%s' % project_id, raise_exc=False) except kse.EndpointNotFound: LOG.error( "Keystone identity service version 3.0 was not found. This might " "be because your endpoint points to the v2.0 versioned endpoint " "which is not supported. Please fix this.") raise exceptions.KeystoneCommunicationFailure( _("KeystoneV3 endpoint not found")) except kse.ClientException: # something is wrong, like there isn't a keystone v3 endpoint, # or nova isn't configured for the interface to talk to it; # we'll take the pass and default to everything being ok. LOG.info("Unable to contact keystone to verify project_id") return True if resp: # All is good with this 20x status return True elif resp.status_code == 404: # we got access, and we know this project is not there raise exceptions.InvalidProject( _("%s is not a valid project ID.") % project_id) elif resp.status_code == 403: # we don't have enough permission to verify this, so default # to "it's ok". LOG.info( "Insufficient permissions for user %(user)s to verify " "existence of project_id %(pid)s", {"user": context.user_id, "pid": project_id}) return True else: LOG.warning( "Unexpected response from keystone trying to " "verify project_id %(pid)s - resp: %(code)s %(content)s", {"pid": project_id, "code": resp.status_code, "content": resp.content}) # realize we did something wrong, but move on with a warning return True
def get_session(group, **session_kwargs): """Loads session object from options in a configuration file section. The session_kwargs will be passed directly to keystoneauth1 Session and will override the values loaded from config. Consult keystoneauth1 docs for available options. :param group: name of the config section to load session options from """ return kaloading.load_session_from_conf_options( CONF, group, **session_kwargs)
def get_os_admin_session(): """Create a context to interact with OpenStack as an administrator.""" # NOTE(ft): this is a singletone because keystone's session looks thread # safe for both regular and token renewal requests global _admin_session if not _admin_session: auth_plugin = ks_loading.load_auth_from_conf_options( CONF, GROUP_AUTHTOKEN) _admin_session = ks_loading.load_session_from_conf_options( CONF, GROUP_AUTHTOKEN, auth=auth_plugin) return _admin_session
def get_session_and_auth(context, **kwargs): """Get session and auth parameters :param context: action context :return: dict to be used as kwargs for client serviceinitialization """ if not context: raise AssertionError('context is mandatory') if context.trust_id: kwargs['project_name'] = None kwargs['project_domain_name'] = None kwargs['project_id'] = None kwargs['trust_id'] = context.trust_id kwargs.pop('service_name') auth = loading.load_auth_from_conf_options( CONF, 'keystone_authtoken', **kwargs ) session = loading.load_session_from_conf_options( CONF, 'keystone', auth=auth ) else: project_endpoint = get_endpoint_for_project(context, **kwargs) endpoint = format_url( project_endpoint.url, { 'tenant_id': context.project_id, 'project_id': context.project_id } ) auth = SimpleToken(endpoint=endpoint, token=context.auth_token) auth_uri = context.auth_uri or CONF.keystone_authtoken.auth_uri ks_auth = SimpleToken( endpoint=auth_uri, token=context.auth_token ) session = ks_session.Session( auth=ks_auth, verify=_determine_verify(context) ) return { "session": session, "auth": auth }
def _glanceclient_from_endpoint(context, endpoint, version): global _SESSION if not _SESSION: _SESSION = ks_loading.load_session_from_conf_options( CONF, nova.conf.glance.glance_group.name) auth = service_auth.get_auth_plugin(context) # TODO(johngarbutt) eventually we should default to getting the # endpoint URL from the service catalog. return glanceclient.Client(version, session=_SESSION, auth=auth, endpoint_override=endpoint, global_request_id=context.global_id)
def novaclient(context, privileged_user=False, timeout=None, api_version=None): """Returns a Nova client @param privileged_user: If True, use the account from configuration (requires 'auth_type' and the other usual Keystone authentication options to be set in the [nova] section) @param timeout: Number of seconds to wait for an answer before raising a Timeout exception (None to disable) @param api_version: api version of nova """ if privileged_user and CONF[NOVA_GROUP].auth_type: LOG.debug('Creating Keystone auth plugin from conf') n_auth = ks_loading.load_auth_from_conf_options(CONF, NOVA_GROUP) else: if CONF[NOVA_GROUP].token_auth_url: url = CONF[NOVA_GROUP].token_auth_url else: url = _get_identity_endpoint_from_sc(context) LOG.debug('Creating Keystone token plugin using URL: %s', url) n_auth = identity.Token(auth_url=url, token=context.auth_token, project_name=context.project_name, project_domain_id=context.project_domain_id) if CONF.auth_strategy == 'keystone': n_auth = service_auth.get_auth_plugin(context, auth=n_auth) keystone_session = ks_loading.load_session_from_conf_options( CONF, NOVA_GROUP, auth=n_auth) c = nova_client.Client( api_versions.APIVersion(api_version or NOVA_API_VERSION), session=keystone_session, insecure=CONF[NOVA_GROUP].insecure, timeout=timeout, region_name=CONF[NOVA_GROUP].region_name, endpoint_type=CONF[NOVA_GROUP].interface, cacert=CONF[NOVA_GROUP].cafile, global_request_id=context.global_id, extensions=nova_extensions) return c
def cinderclient(context): global _SESSION if not _SESSION: _SESSION = ks_loading.load_session_from_conf_options( CONF, nova.conf.cinder.cinder_group.name) url = None endpoint_override = None auth = service_auth.get_auth_plugin(context) service_type, service_name, interface = CONF.cinder.catalog_info.split(':') service_parameters = {'service_type': service_type, 'service_name': service_name, 'interface': interface, 'region_name': CONF.cinder.os_region_name} if CONF.cinder.endpoint_template: url = CONF.cinder.endpoint_template % context.to_dict() endpoint_override = url else: url = _SESSION.get_endpoint(auth, **service_parameters) # TODO(jamielennox): This should be using proper version discovery from # the cinder service rather than just inspecting the URL for certain string # values. version = cinder_client.get_volume_api_from_url(url) if version == '1': raise exception.UnsupportedCinderAPIVersion(version=version) if version == '2': LOG.warning("The support for the Cinder API v2 is deprecated, please " "upgrade to Cinder API v3.") if version == '3': # TODO(ildikov): Add microversion support for picking up the new # attach/detach API that was added in 3.27. version = '3.0' return cinder_client.Client(version, session=_SESSION, auth=auth, endpoint_override=endpoint_override, connect_retries=CONF.cinder.http_retries, global_request_id=context.global_id, **service_parameters)
def _placement_get(self, path): """Do an HTTP get call against placement engine. This is in a dedicated method to make it easier for unit testing purposes. """ ks_filter = {'service_type': 'placement', 'region_name': CONF.placement.os_region_name, 'interface': CONF.placement.os_interface} auth = keystone.load_auth_from_conf_options( CONF, 'placement') client = keystone.load_session_from_conf_options( CONF, 'placement', auth=auth) return client.get(path, endpoint_filter=ks_filter).json()
def __init__(self, transformers, **kwargs): super(GnocchiCollector, self).__init__(transformers, **kwargs) self.t_gnocchi = self.transformers['GnocchiTransformer'] self.t_cloudkitty = self.transformers['CloudKittyFormatTransformer'] self.auth = ks_loading.load_auth_from_conf_options( CONF, GNOCCHI_COLLECTOR_OPTS) self.session = ks_loading.load_session_from_conf_options( CONF, GNOCCHI_COLLECTOR_OPTS, auth=self.auth) self._conn = gclient.Client( '1', session=self.session)
def __init__(self): # A dict, keyed by the resource provider UUID, of ResourceProvider # objects that will have their inventories and allocations tracked by # the placement API for the compute host self._resource_providers = {} # A dict, keyed by resource provider UUID, of sets of aggregate UUIDs # the provider is associated with self._provider_aggregate_map = {} auth_plugin = keystone.load_auth_from_conf_options( CONF, 'placement') self._client = keystone.load_session_from_conf_options( CONF, 'placement', auth=auth_plugin) # NOTE(danms): Keep track of how naggy we've been self._warn_count = 0 self.ks_filter = {'service_type': 'placement', 'region_name': CONF.placement.os_region_name, 'interface': CONF.placement.os_interface}
def _get_auth_and_session(confgrp): ksa_auth = ks_loading.load_auth_from_conf_options(CONF, confgrp) return ks_loading.load_session_from_conf_options(CONF, confgrp, auth=ksa_auth)
def __init__(self): auth_plugin = ks_loading.load_auth_from_conf_options( cfg.CONF, 'placement') self._client = ks_loading.load_session_from_conf_options( cfg.CONF, 'placement', auth=auth_plugin) self._disabled = False
def get_keystone_session(conf_group, auth_plugin): return ks_loading.load_session_from_conf_options(cfg.CONF, conf_group, auth=auth_plugin)
def _get_session(self, group): auth = ks_loading.load_auth_from_conf_options(cfg.CONF, group) session = ks_loading.load_session_from_conf_options(cfg.CONF, group, auth=auth) return session
def _get_client(self, retry_on_conflict=True): max_retries = CONF.ironic.api_max_retries if retry_on_conflict else 1 retry_interval = (CONF.ironic.api_retry_interval if retry_on_conflict else 0) # If we've already constructed a valid, authed client, just return # that. if retry_on_conflict and self._cached_client is not None: return self._cached_client auth_plugin = self._get_auth_plugin() sess = ks_loading.load_session_from_conf_options(CONF, IRONIC_GROUP.name, auth=auth_plugin) # Retries for Conflict exception kwargs = {} kwargs['max_retries'] = max_retries kwargs['retry_interval'] = retry_interval # NOTE(TheJulia): The ability for a list of available versions to be # accepted was added in python-ironicclient 2.2.0. The highest # available version will be utilized by the client for the lifetime # of the client. kwargs['os_ironic_api_version'] = [ '%d.%d' % IRONIC_API_VERSION, '%d.%d' % PRIOR_IRONIC_API_VERSION] ironic_conf = CONF[IRONIC_GROUP.name] # valid_interfaces is a list. ironicclient passes this kwarg through to # ksa, which is set up to handle 'interface' as either a list or a # single value. kwargs['interface'] = ironic_conf.valid_interfaces # NOTE(clenimar/efried): by default, the endpoint is taken from the # service catalog. Use `endpoint_override` if you want to override it. try: ksa_adap = utils.get_ksa_adapter( nova.conf.ironic.DEFAULT_SERVICE_TYPE, ksa_auth=auth_plugin, ksa_session=sess, min_version=(IRONIC_API_VERSION[0], 0), max_version=(IRONIC_API_VERSION[0], ks_disc.LATEST)) ironic_url = ksa_adap.get_endpoint() ironic_url_none_reason = 'returned None' except exception.ServiceNotFound: # NOTE(efried): No reason to believe service catalog lookup # won't also fail in ironic client init, but this way will # yield the expected exception/behavior. ironic_url = None ironic_url_none_reason = 'raised ServiceNotFound' if ironic_url is None: LOG.warning("Could not discover ironic_url via keystoneauth1: " "Adapter.get_endpoint %s", ironic_url_none_reason) # NOTE(eandersson): We pass in region here to make sure # that the Ironic client can make an educated decision when # we don't have a valid endpoint to pass on. kwargs['region_name'] = ironic_conf.region_name try: cli = ironic.client.get_client(IRONIC_API_VERSION[0], endpoint=ironic_url, session=sess, **kwargs) # Cache the client so we don't have to reconstruct and # reauthenticate it every time we need it. if retry_on_conflict: self._cached_client = cli except ironic.exc.Unauthorized: msg = _("Unable to authenticate Ironic client.") LOG.error(msg) raise exception.NovaException(msg) return cli
def get_session(conf, requests_session=None): """Get a ceilometer service credentials auth session.""" auth_plugin = ka_loading.load_auth_from_conf_options(conf, CFG_GROUP) session = ka_loading.load_session_from_conf_options( conf, CFG_GROUP, auth=auth_plugin, session=requests_session) return session
def get_session(conf): """Get an aodh service credentials auth session.""" auth_plugin = ka_loading.load_auth_from_conf_options(conf, CFG_GROUP) return ka_loading.load_session_from_conf_options(conf, CFG_GROUP, auth=auth_plugin)
def get_session(group): auth = loading.load_auth_from_conf_options(CONF, group) session = loading.load_session_from_conf_options( CONF, group, auth=auth) return session
def get_ksa_adapter(service_type, ksa_auth=None, ksa_session=None, min_version=None, max_version=None): """Construct a keystoneauth1 Adapter for a given service type. We expect to find a conf group whose name corresponds to the service_type's project according to the service-types-authority. That conf group must provide at least ksa adapter options. Depending how the result is to be used, ksa auth and/or session options may also be required, or the relevant parameter supplied. :param service_type: String name of the service type for which the Adapter is to be constructed. :param ksa_auth: A keystoneauth1 auth plugin. If not specified, we attempt to find one in ksa_session. Failing that, we attempt to load one from the conf. :param ksa_session: A keystoneauth1 Session. If not specified, we attempt to load one from the conf. :param min_version: The minimum major version of the adapter's endpoint, intended to be used as the lower bound of a range with max_version. If min_version is given with no max_version it is as if max version is 'latest'. :param max_version: The maximum major version of the adapter's endpoint, intended to be used as the upper bound of a range with min_version. :return: A keystoneauth1 Adapter object for the specified service_type. :raise: ConfGroupForServiceTypeNotFound If no conf group name could be found for the specified service_type. """ # Get the conf group corresponding to the service type. confgrp = _SERVICE_TYPES.get_project_name(service_type) if not confgrp or not hasattr(CONF, confgrp): # Try the service type as the conf group. This is necessary for e.g. # placement, while it's still part of the nova project. # Note that this might become the first thing we try if/as we move to # using service types for conf group names in general. confgrp = service_type if not confgrp or not hasattr(CONF, confgrp): raise exception.ConfGroupForServiceTypeNotFound(stype=service_type) # Ensure we have an auth. # NOTE(efried): This could be None, and that could be okay - e.g. if the # result is being used for get_endpoint() and the conf only contains # endpoint_override. if not ksa_auth: if ksa_session and ksa_session.auth: ksa_auth = ksa_session.auth else: ksa_auth = ks_loading.load_auth_from_conf_options(CONF, confgrp) if not ksa_session: ksa_session = ks_loading.load_session_from_conf_options(CONF, confgrp, auth=ksa_auth) return ks_loading.load_adapter_from_conf_options(CONF, confgrp, session=ksa_session, auth=ksa_auth, min_version=min_version, max_version=max_version)
def get_session(): """Get a vitrage service credentials auth session.""" auth_plugin = ka_loading.load_auth_from_conf_options(CONF, CFG_GROUP) return ka_loading.load_session_from_conf_options(CONF, CFG_GROUP, auth=auth_plugin)
def _get_client(self, retry_on_conflict=True): max_retries = CONF.ironic.api_max_retries if retry_on_conflict else 1 retry_interval = (CONF.ironic.api_retry_interval if retry_on_conflict else 0) # If we've already constructed a valid, authed client, just return # that. if retry_on_conflict and self._cached_client is not None: return self._cached_client auth_plugin = self._get_auth_plugin() sess = ks_loading.load_session_from_conf_options(CONF, IRONIC_GROUP.name, auth=auth_plugin) # Retries for Conflict exception kwargs = {} kwargs['max_retries'] = max_retries kwargs['retry_interval'] = retry_interval # NOTE(TheJulia): The ability for a list of available versions to be # accepted was added in python-ironicclient 2.2.0. The highest # available version will be utilized by the client for the lifetime # of the client. kwargs['os_ironic_api_version'] = [ '%d.%d' % IRONIC_API_VERSION, '%d.%d' % PRIOR_IRONIC_API_VERSION ] # NOTE(clenimar/efried): by default, the endpoint is taken from the # service catalog. Use `endpoint_override` if you want to override it. if CONF.ironic.api_endpoint: # NOTE(efried): `api_endpoint` still overrides service catalog and # `endpoint_override` conf options. This will be removed in a # future release. ironic_url = CONF.ironic.api_endpoint else: try: ksa_adap = utils.get_ksa_adapter( nova.conf.ironic.DEFAULT_SERVICE_TYPE, ksa_auth=auth_plugin, ksa_session=sess, min_version=IRONIC_API_VERSION, max_version=(IRONIC_API_VERSION[0], ks_disc.LATEST)) ironic_url = ksa_adap.get_endpoint() except exception.ServiceNotFound: # NOTE(efried): No reason to believe service catalog lookup # won't also fail in ironic client init, but this way will # yield the expected exception/behavior. ironic_url = None try: cli = ironic.client.get_client(IRONIC_API_VERSION[0], ironic_url=ironic_url, session=sess, **kwargs) # Cache the client so we don't have to reconstruct and # reauthenticate it every time we need it. if retry_on_conflict: self._cached_client = cli except ironic.exc.Unauthorized: msg = _("Unable to authenticate Ironic client.") LOG.error(msg) raise exception.NovaException(msg) return cli
def _get_user_client(auth_plugin): sess = loading.load_session_from_conf_options(cfg.CONF, TRUSTEE_CONF_GROUP, auth=auth_plugin) return client.Client(session=sess)
def cinderclient(context, microversion=None, skip_version_check=False): """Constructs a cinder client object for making API requests. :param context: The nova request context for auth. :param microversion: Optional microversion to check against the client. This implies that Cinder v3 is required for any calls that require a microversion. If the microversion is not available, this method will raise an CinderAPIVersionNotAvailable exception. :param skip_version_check: If True and a specific microversion is requested, the version discovery check is skipped and the microversion is used directly. This should only be used if a previous check for the same microversion was successful. """ global _SESSION if not _SESSION: _SESSION = ks_loading.load_session_from_conf_options( CONF, nova.conf.cinder.cinder_group.name) url = None endpoint_override = None auth = service_auth.get_auth_plugin(context) service_type, service_name, interface = CONF.cinder.catalog_info.split(':') service_parameters = { 'service_type': service_type, 'service_name': service_name, 'interface': interface, 'region_name': CONF.cinder.os_region_name } if CONF.cinder.endpoint_template: url = CONF.cinder.endpoint_template % context.to_dict() endpoint_override = url else: url = _SESSION.get_endpoint(auth, **service_parameters) # TODO(jamielennox): This should be using proper version discovery from # the cinder service rather than just inspecting the URL for certain string # values. version = cinder_client.get_volume_api_from_url(url) if version == '1': raise exception.UnsupportedCinderAPIVersion(version=version) if version == '2': if microversion is not None: # The Cinder v2 API does not support microversions. raise exception.CinderAPIVersionNotAvailable(version=microversion) LOG.warning("The support for the Cinder API v2 is deprecated, please " "upgrade to Cinder API v3.") if version == '3': version = '3.0' # Check to see a specific microversion is requested and if so, can it # be handled by the backing server. if microversion is not None: if skip_version_check: version = microversion else: version = _check_microversion(url, microversion) return cinder_client.Client(version, session=_SESSION, auth=auth, endpoint_override=endpoint_override, connect_retries=CONF.cinder.http_retries, global_request_id=context.global_id, **service_parameters)
def _load_session(): global _SESSION if not _SESSION: _SESSION = ks_loading.load_session_from_conf_options( CONF, nova.conf.cinder.cinder_group.name)
def _get_session(self, auth): session = ka_loading.load_session_from_conf_options(CONF, CFG_GROUP, auth=auth) return session