Example #1
0
def setup_keystoneauth(conf):
    if conf[CFG_GROUP].auth_type == "password-vitrage-legacy":
        LOG.warn("Value 'password-vitrage-legacy' for '[%s]/auth_type' "
                 "is deprecated. And will be removed in Vitrage 2.0. "
                 "Use 'password' instead.",
                 CFG_GROUP)
    ka_loading.load_auth_from_conf_options(conf, CFG_GROUP)
Example #2
0
def prepare_service(argv=None, config_files=None, conf=None):
    if argv is None:
        argv = sys.argv

    # FIXME(sileht): Use ConfigOpts() instead
    if conf is None:
        conf = cfg.CONF

    oslo_i18n.enable_lazy()
    log.register_options(conf)
    log_levels = (conf.default_log_levels +
                  ['futurist=INFO', 'neutronclient=INFO',
                   'keystoneclient=INFO'])
    log.set_defaults(default_log_levels=log_levels)
    defaults.set_cors_middleware_defaults()
    policy_opts.set_defaults(conf)

    conf(argv[1:], project='ceilometer', validate_default_values=True,
         version=version.version_info.version_string(),
         default_config_files=config_files)

    ka_loading.load_auth_from_conf_options(conf, "service_credentials")

    log.setup(conf, 'ceilometer')
    # NOTE(liusheng): guru cannot run with service under apache daemon, so when
    # ceilometer-api running with mod_wsgi, the argv is [], we don't start
    # guru.
    if argv:
        gmr.TextGuruMeditation.setup_autorun(version)
    messaging.setup()
    return conf
Example #3
0
    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)
Example #4
0
def parse_args(args=None, prog=None):
    log.set_defaults()
    log.register_options(CONF)
    CONF(
        args=args,
        project='distil',
        prog=prog,
        version=version.version_info.version_string(),
    )

    ka_loading.load_auth_from_conf_options(CONF, AUTH_GROUP)

    log.setup(CONF, prog)
Example #5
0
    def test_loading_v3(self):
        section = uuid.uuid4().hex
        auth_url = uuid.uuid4().hex,
        token = uuid.uuid4().hex
        trust_id = uuid.uuid4().hex
        project_id = uuid.uuid4().hex
        project_domain_name = uuid.uuid4().hex

        self.conf_fixture.config(auth_section=section, group=self.GROUP)
        loading.register_auth_conf_options(self.conf_fixture.conf,
                                           group=self.GROUP)

        self.conf_fixture.register_opts(to_oslo_opts(v3.Token().get_options()),
                                        group=section)

        self.conf_fixture.config(auth_type=self.V3TOKEN,
                                 auth_url=auth_url,
                                 token=token,
                                 trust_id=trust_id,
                                 project_id=project_id,
                                 project_domain_name=project_domain_name,
                                 group=section)

        a = loading.load_auth_from_conf_options(self.conf_fixture.conf,
                                                self.GROUP)

        self.assertEqual(token, a.auth_methods[0].token)
        self.assertEqual(trust_id, a.trust_id)
        self.assertEqual(project_id, a.project_id)
        self.assertEqual(project_domain_name, a.project_domain_name)
Example #6
0
    def test_loading_v2(self):
        section = uuid.uuid4().hex
        auth_url = uuid.uuid4().hex
        username = uuid.uuid4().hex
        password = uuid.uuid4().hex
        trust_id = uuid.uuid4().hex
        tenant_id = uuid.uuid4().hex

        self.conf_fixture.config(auth_section=section, group=self.GROUP)
        loading.register_auth_conf_options(self.conf_fixture.conf,
                                           group=self.GROUP)

        self.conf_fixture.register_opts(
            to_oslo_opts(v2.Password().get_options()),
            group=section)

        self.conf_fixture.config(auth_type=self.V2PASS,
                                 auth_url=auth_url,
                                 username=username,
                                 password=password,
                                 trust_id=trust_id,
                                 tenant_id=tenant_id,
                                 group=section)

        a = loading.load_auth_from_conf_options(self.conf_fixture.conf,
                                                self.GROUP)

        self.assertEqual(auth_url, a.auth_url)
        self.assertEqual(username, a.username)
        self.assertEqual(password, a.password)
        self.assertEqual(trust_id, a.trust_id)
        self.assertEqual(tenant_id, a.tenant_id)
Example #7
0
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
Example #8
0
 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
Example #9
0
    def _migrate_keys(self, volumes, backups):
        LOG.info("Starting migration of ConfKeyManager keys.")

        # Establish a Barbican client session that will be used for the entire
        # key migration process. Use cinder's own service credentials.
        try:
            ks_loading.register_auth_conf_options(self.conf,
                                                  'keystone_authtoken')
            auth = ks_loading.load_auth_from_conf_options(self.conf,
                                                          'keystone_authtoken')
            sess = ks_session.Session(auth=auth)
            self.barbican = barbican_client.Client(session=sess)
        except Exception as e:
            LOG.error("Aborting encryption key migration due to "
                      "error creating Barbican client: %s", e)
            return

        errors = 0
        for item in itertools.chain(volumes, backups):
            try:
                self._migrate_encryption_key(item)
            except Exception as e:
                LOG.error("Error migrating encryption key: %s", e)
                # NOTE(abishop): There really shouldn't be any soft errors, so
                # if an error occurs migrating one key then chances are they
                # will all fail. This avoids filling the log with the same
                # error in situations where there are many keys to migrate.
                errors += 1
                if errors > MAX_KEY_MIGRATION_ERRORS:
                    LOG.error("Aborting encryption key migration "
                              "(too many errors).")
                    break
Example #10
0
 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)
Example #11
0
    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)
Example #12
0
    def __init__(self, transformers, **kwargs):
        super(GnocchiCollector, self).__init__(transformers, **kwargs)

        adapter_options = {'connect_retries': 3}
        if CONF.collector_gnocchi.gnocchi_auth_type == 'keystone':
            auth_plugin = ks_loading.load_auth_from_conf_options(
                CONF,
                COLLECTOR_GNOCCHI_OPTS,
            )
            adapter_options['interface'] = CONF.collector_gnocchi.interface
        else:
            auth_plugin = gauth.GnocchiBasicPlugin(
                user=CONF.collector_gnocchi.gnocchi_user,
                endpoint=CONF.collector_gnocchi.gnocchi_endpoint,
            )
        adapter_options['region_name'] = CONF.collector_gnocchi.region_name

        verify = True
        if CONF.collector_gnocchi.cafile:
            verify = CONF.collector_gnocchi.cafile
        elif CONF.collector_gnocchi.insecure:
            verify = False

        self._conn = gclient.Client(
            '1',
            session_options={'auth': auth_plugin, 'verify': verify},
            adapter_options=adapter_options,
        )
Example #13
0
    def _get_auth_plugin(self):
        """Load an auth plugin from CONF options."""
        # If an auth plugin name is defined in `auth_type` option of [ironic]
        # group, register its options and load it.
        auth_plugin = ks_loading.load_auth_from_conf_options(CONF, IRONIC_GROUP.name)

        # If no plugin name is defined, load a v2Password plugin from the
        # deprecated, legacy auth options in [ironic] group.
        if auth_plugin is None:
            LOG.warning(
                _LW(
                    "Couldn't find adequate authentication options "
                    "under the [ironic] group of nova.conf. Falling "
                    "to legacy auth options: admin_username, "
                    "admin_password, admin_tenant_name and admin_url. "
                    "Please note that these options are deprecated "
                    "and won't be supported anymore in a future "
                    "release."
                )
            )
            legacy_auth = {
                "username": CONF.ironic.admin_username,
                "password": CONF.ironic.admin_password,
                "tenant_name": CONF.ironic.admin_tenant_name,
                "auth_url": CONF.ironic.admin_url,
            }
            auth_plugin = identity.V2Password(**legacy_auth)

        return auth_plugin
Example #14
0
 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()
Example #15
0
    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)
Example #16
0
    def _get_auth(self):
        if self.context.auth_token_info:
            access_info = ka_access.create(body=self.context.auth_token_info,
                                           auth_token=self.context.auth_token)
            auth = ka_access_plugin.AccessInfoPlugin(access_info)
        elif self.context.auth_token:
            auth = ka_v3.Token(auth_url=self.auth_url,
                               token=self.context.auth_token)
        elif self.context.trust_id:
            auth_info = {
                'auth_url': self.auth_url,
                'username': self.context.user_name,
                'password': self.context.password,
                'user_domain_id': self.context.user_domain_id,
                'user_domain_name': self.context.user_domain_name,
                'trust_id': self.context.trust_id
            }

            auth = ka_v3.Password(**auth_info)
        elif self.context.is_admin:
            try:
                auth = ka_loading.load_auth_from_conf_options(
                    CONF, ksconf.CFG_GROUP)
            except ka_exception.MissingRequiredOptions:
                auth = self._get_legacy_auth()
        else:
            msg = ('Keystone API connection failed: no password, '
                   'trust_id or token found.')
            LOG.error(msg)
            raise exception.AuthorizationFailure(client='keystone',
                                                 message='reason %s' % msg)

        return auth
Example #17
0
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
Example #18
0
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
Example #19
0
def get_trusted_token(trust_id):
    """Return a Keystone token using the given trust_id."""
    auth_plugin = loading.load_auth_from_conf_options(
        cfg.CONF, TRUSTEE_CONF_GROUP, trust_id=trust_id)

    trust_session = session.Session(auth=auth_plugin)
    return trust_session.auth.get_access(trust_session).auth_token
Example #20
0
def _get_keystone_auth(trust_id=None):
    if not cfg.CONF[CFG_KEYSTONE_GROUP].auth_type:
        # Fallback to legacy v2 options if no auth_type is set.
        # If auth_type is set, it is possible to use the auth loader
        # from keystoneauth1. This is the same fallback as keystonemiddleware
        # uses.
        kwargs = {
            'auth_url':
                cfg.CONF[CFG_KEYSTONE_GROUP].auth_uri.replace('v2.0', 'v3'),
            'username': cfg.CONF[CFG_KEYSTONE_GROUP].admin_user,
            'password': cfg.CONF[CFG_KEYSTONE_GROUP].admin_password,
            'user_domain_name': "Default"
        }
        if not trust_id:
            kwargs['project_name'] = \
                cfg.CONF[CFG_KEYSTONE_GROUP].admin_tenant_name
            kwargs['project_domain_name'] = "Default"
        else:
            kwargs['trust_id'] = trust_id
        auth = identity.Password(**kwargs)
    else:
        kwargs = {}
        if trust_id:
            # Remove project_name and project_id, since we need a trust scoped
            # auth object
            kwargs['project_name'] = None
            kwargs['project_domain_name'] = None
            kwargs['project_id'] = None
            kwargs['trust_id'] = trust_id
        auth = ka_loading.load_auth_from_conf_options(
            cfg.CONF,
            CFG_KEYSTONE_GROUP,
            **kwargs)
    return auth
Example #21
0
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
        )
Example #22
0
    def trusts_auth_plugin(self):
        if self._trusts_auth_plugin:
            return self._trusts_auth_plugin

        self._trusts_auth_plugin = ks_loading.load_auth_from_conf_options(
            cfg.CONF, TRUSTEE_CONF_GROUP, trust_id=self.trust_id)

        if self._trusts_auth_plugin:
            return self._trusts_auth_plugin

        LOG.warning(_LW('Using the keystone_authtoken user as the heat '
                        'trustee user directly is deprecated. Please add the '
                        'trustee credentials you need to the %s section of '
                        'your heat.conf file.') % TRUSTEE_CONF_GROUP)

        cfg.CONF.import_group('keystone_authtoken',
                              'keystonemiddleware.auth_token')

        trustee_user_domain = 'default'
        if 'user_domain_id' in cfg.CONF.keystone_authtoken:
            trustee_user_domain = cfg.CONF.keystone_authtoken.user_domain_id

        self._trusts_auth_plugin = generic.Password(
            username=cfg.CONF.keystone_authtoken.admin_user,
            password=cfg.CONF.keystone_authtoken.admin_password,
            user_domain_id=trustee_user_domain,
            auth_url=self.keystone_v3_endpoint,
            trust_id=self.trust_id)
        return self._trusts_auth_plugin
Example #23
0
    def __init__(self, user_plugin, user_project, user_roles):
        """Prepare all parameters and clients required to refresh token"""
        # step 1: create trust to ensure that we can always update token

        # trustor = user who made the request
        trustor_client = self._load_session(user_plugin)
        trustor_id = trustor_client.get_user_id()

        # get trustee user client that impersonates main user
        trustee_user_auth = ka_loading.load_auth_from_conf_options(
            CONF, 'keystone_authtoken')
        # save service user client because we need new service token
        # to refresh trust-scoped client later
        self.trustee_user_client = self._load_session(trustee_user_auth)

        trustee_id = self.trustee_user_client.get_user_id()

        self.trust_id = trustor_client.trusts.create(trustor_user=trustor_id,
                                                     trustee_user=trustee_id,
                                                     impersonation=True,
                                                     role_names=user_roles,
                                                     project=user_project).id
        LOG.debug("Trust %s has been created.", self.trust_id)

        # step 2: postpone trust-scoped client initialization
        # until we need to refresh the token
        self.trustee_client = None
Example #24
0
    def _get_auth_plugin(self):
        """Load an auth plugin from CONF options."""
        # If an auth plugin name is defined in `auth_type` option of [ironic]
        # group, register its options and load it.
        auth_plugin = ks_loading.load_auth_from_conf_options(CONF,
                                                             IRONIC_GROUP.name)

        return auth_plugin
Example #25
0
def _get_auth(group, legacy_mapping=None, legacy_opts=None):
    try:
        auth = loading.load_auth_from_conf_options(CONF, group)
    except exceptions.MissingRequiredOptions:
        auth = _get_legacy_auth(group, legacy_mapping, legacy_opts)
    else:
        if auth is None:
            auth = _get_legacy_auth(group, legacy_mapping, legacy_opts)
    return auth
Example #26
0
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)
Example #27
0
def prepare_service(argv=None, config_files=None, conf=None):
    oslo_i18n.enable_lazy()

    if argv is None:
        argv = sys.argv
    if conf is None:
        conf = cfg.ConfigOpts()
    conf.register_opts(OPTS)
    log.register_options(conf)
    db_options.set_defaults(conf)
    loading.register_auth_conf_options(conf, 'keystone_authtoken')
    conf(argv[1:], project='nabu', validate_default_values=True,
         version=nabu.__version__,
         default_config_files=config_files)
    loading.load_auth_from_conf_options(conf, 'keystone_authtoken')

    log.setup(conf, 'nabu')

    return conf
Example #28
0
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
Example #29
0
 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 = {}
     auth_plugin = keystone.load_auth_from_conf_options(CONF, "placement")
     self._client = session.Session(auth=auth_plugin)
     # TODO(sdague): use this to disable fully when we don't find
     # the endpoint.
     self._disabled = False
    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)
Example #31
0
    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,
                                                           only_contrib=True)
            if ext.name == "server_external_events"
        ]
        self.nclient = nova_client.Client(
            api_versions.APIVersion(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)
Example #32
0
 def _create_client(self):
     """Create the HTTP session accessing the placement service."""
     # Flush _resource_providers and aggregates so we start from a
     # clean slate.
     self._resource_providers = {}
     self._provider_aggregate_map = {}
     # TODO(lajoskatona): perhaps not the best to override config options,
     # actually the abused keystoneauth1 options are:
     # auth_type (used for deciding for NoAuthClient) and auth_section
     # (used for communicating the url for the NoAuthClient)
     if self._conf.placement.auth_type == 'noauth':
         return NoAuthClient(self._conf.placement.auth_section)
     else:
         auth_plugin = keystone.load_auth_from_conf_options(
             self._conf, 'placement')
         return keystone.load_session_from_conf_options(
             self._conf,
             'placement',
             auth=auth_plugin,
             additional_headers={'accept': 'application/json'})
Example #33
0
    def _get_clients(self):
        p_client = placement_client.PlacementAPIClient(
            cfg.CONF, openstack_api_version='placement 1.1')

        n_auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova')
        n_session = ks_loading.load_session_from_conf_options(cfg.CONF,
                                                              'nova',
                                                              auth=n_auth)
        extensions = [
            ext for ext in nova_client.discover_extensions(NOVA_API_VERSION)
            if ext.name == "server_external_events"
        ]
        n_client = nova_client.Client(
            NOVA_API_VERSION,
            session=n_session,
            region_name=cfg.CONF.nova.region_name,
            endpoint_type=cfg.CONF.nova.endpoint_type,
            extensions=extensions)

        return p_client, n_client
Example #34
0
    def __init__(self, transformers, **kwargs):
        super(MonascaCollector, self).__init__(transformers, **kwargs)

        self.t_cloudkitty = self.transformers['CloudKittyFormatTransformer']

        self.auth = ks_loading.load_auth_from_conf_options(
            CONF,
            COLLECTOR_MONASCA_OPTS)
        self.session = ks_loading.load_session_from_conf_options(
            CONF,
            COLLECTOR_MONASCA_OPTS,
            auth=self.auth)
        self.ks_client = ks_client.Client(session=self.session)
        self.mon_endpoint = self._get_monasca_endpoint()
        if not self.mon_endpoint:
            raise EndpointNotFound()
        self._conn = mclient.Client(
            api_version=MONASCA_API_VERSION,
            session=self.session,
            endpoint=self.mon_endpoint)
Example #35
0
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)
Example #36
0
    def _get_auth(self):
        if self.context.is_admin or self.context.trust_id:
            try:
                auth = ka_loading.load_auth_from_conf_options(CONF, CFG_GROUP)
            except ka_exception.MissingRequiredOptions:
                auth = self._get_legacy_auth()
        elif self.context.auth_token_info:
            access_info = ka_access.create(body=self.context.auth_token_info,
                                           auth_token=self.context.auth_token)
            auth = ka_access_plugin.AccessInfoPlugin(access_info)
        elif self.context.auth_token:
            auth = ka_v3.Token(auth_url=self.auth_url,
                               token=self.context.auth_token)
        else:
            LOG.error(
                _LE('Keystone API connection failed: no password, '
                    'trust_id or token found.'))
            raise exception.AuthorizationFailure()

        return auth
Example #37
0
 def __init__(self, **kwargs):
     super(GnocchiStorage, self).__init__(**kwargs)
     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._measures = {}
     self._archive_policy_name = (CONF.storage_gnocchi.archive_policy_name)
     self._archive_policy_definition = json.loads(
         CONF.storage_gnocchi.archive_policy_definition)
     self._period = METRICS_CONF['period']
     if "period" in kwargs:
         self._period = kwargs["period"]
Example #38
0
def get_ironic_client(context=None):
    session = ks_loading.load_session_from_conf_options(CONF, 'ironic')
    service_auth = ks_loading.load_auth_from_conf_options(CONF, 'ironic')

    # use user context if provided
    user_auth = None
    if context:
        endpoint = ks_loading.load_adapter_from_conf_options(
            CONF, 'ironic', session=session, auth=service_auth).get_endpoint()
        user_auth = service_token.ServiceTokenAuthWrapper(
            user_auth=token_endpoint.Token(endpoint, context.auth_token),
            service_auth=service_auth)
    sess = ks_loading.load_session_from_conf_options(CONF,
                                                     'ironic',
                                                     auth=user_auth
                                                     or service_auth)

    kwargs = {'os_ironic_api_version': '1.65'}
    cli = ironic_client.get_client(1, session=sess, **kwargs)
    return cli
    def _v3_client_init(self):
        kwargs = {'auth_url': self.endpoint, 'endpoint': self.endpoint}
        # Note try trust_id first, as we can't reuse auth_token in that case
        if self.context.trust_id is not None:
            # We got a trust_id, so we use the admin credentials
            # to authenticate with the trust_id so we can use the
            # trust impersonating the trustor user.
            kwargs.update(self._service_admin_creds())
            kwargs['trust_id'] = self.context.trust_id
            kwargs.pop('project_name')
            auth = ka_loading.load_auth_from_conf_options(
                cfg.CONF, 'keystone_authtoken', **kwargs)
        elif self.context.auth_token is not None:
            kwargs['token'] = self.context.auth_token
            kwargs['project_id'] = self.context.tenant
            auth = identity.Token(auth_url=kwargs['auth_url'],
                                  token=kwargs['token'],
                                  project_id=kwargs['project_id'])
        else:
            LOG.error(
                _("Keystone v3 API connection failed, no password "
                  "trust or auth_token!"))
            raise exception.AuthorizationFailure()
        session = ks_session.Session(auth=auth)
        client = kc_v3.Client(session=session)
        client.auth_ref = client.session.auth.get_access(client.session)
        # If we are authenticating with a trust set the context auth_token
        # with the trust scoped token
        if 'trust_id' in kwargs:
            # Sanity check
            if not client.auth_ref.trust_scoped:
                LOG.error(_("trust token re-scoping failed!"))
                raise exception.AuthorizationFailure()
            # All OK so update the context with the token
            self.context.auth_token = client.auth_ref.auth_token
            self.context.auth_url = self.endpoint
            self.context.user = client.auth_ref.user_id
            self.context.tenant = client.auth_ref.project_id
            self.context.user_name = client.auth_ref.username

        return client
Example #40
0
def _get_conf_client(context):
    """Retrieve a neutron client connection using conf parameters.

    :param context: request context,
                    instance of ironic.common.context.RequestContext
    :returns: A neutron client.
    """

    auth = ks_loading.load_auth_from_conf_options(CONF, 'neutron')
    session = ks_loading.load_session_from_conf_options(
        CONF,
        'neutron',
        auth=auth)
    endpoint = keystone.get_endpoint('neutron', session=session,
                                     auth=auth)
    return clientv20.Client(session=session,
                            auth=auth,
                            endpoint_override=endpoint,
                            retries=CONF.neutron.retries,
                            global_request_id=context.global_id,
                            timeout=CONF.neutron.request_timeout)
Example #41
0
    def __init__(self):
        super(GnocchiFetcher, self).__init__()
        adapter_options = {'connect_retries': 3}
        if CONF.fetcher_gnocchi.gnocchi_auth_type == 'keystone':
            auth_plugin = ks_loading.load_auth_from_conf_options(
                CONF,
                FETCHER_GNOCCHI_OPTS,
            )
            adapter_options['interface'] = CONF.fetcher_gnocchi.interface
        else:
            auth_plugin = gauth.GnocchiBasicPlugin(
                user=CONF.fetcher_gnocchi.gnocchi_user,
                endpoint=CONF.fetcher_gnocchi.gnocchi_endpoint,
            )
        adapter_options['region_name'] = CONF.fetcher_gnocchi.region_name

        self._conn = gclient.Client(
            '1',
            session_options={'auth': auth_plugin},
            adapter_options=adapter_options,
        )
Example #42
0
    def __init__(self, *args, **kwargs):
        super(GnocchiStorage, self).__init__(*args, **kwargs)

        adapter_options = {'connect_retries': 3}
        if CONF.storage_gnocchi.gnocchi_auth_type == 'keystone':
            auth_plugin = ks_loading.load_auth_from_conf_options(
                CONF,
                'storage_gnocchi',
            )
            adapter_options['interface'] = CONF.storage_gnocchi.api_interface
        else:
            auth_plugin = gauth.GnocchiBasicPlugin(
                user=CONF.storage_gnocchi.gnocchi_user,
                endpoint=CONF.storage_gnocchi.gnocchi_endpoint,
            )
        self._conn = gclient.Client(
            '1',
            session_options={'auth': auth_plugin},
            adapter_options=adapter_options,
        )
        self._cacher = GnocchiResourceCacher()
Example #43
0
    def __init__(self, **kwargs):
        super(MonascaCollector, self).__init__(**kwargs)

        self.auth = ks_loading.load_auth_from_conf_options(
            CONF,
            COLLECTOR_MONASCA_OPTS)
        self.session = ks_loading.load_session_from_conf_options(
            CONF,
            COLLECTOR_MONASCA_OPTS,
            auth=self.auth)
        self.ks_client = ks_client.Client(
            session=self.session,
            interface=CONF.collector_monasca.interface,
        )
        self.mon_endpoint = self._get_monasca_endpoint()
        if not self.mon_endpoint:
            raise EndpointNotFound()
        self._conn = mclient.Client(
            api_version=MONASCA_API_VERSION,
            session=self.session,
            endpoint=self.mon_endpoint)
Example #44
0
    def __call__(self, req):
        # NOTE(ralonsoh): this method uses Nova Keystone user to retrieve the
        # project because (1) it is allowed to retrieve the projects and (2)
        # Neutron avoids adding another user section in the configuration
        # (Nova user will be always used).
        global _NOVA_CONNECTION
        project = req.params.get('project_id') or req.params.get('tenant_id')
        if project:
            if not _NOVA_CONNECTION:
                auth = ks_loading.load_auth_from_conf_options(cfg.CONF, 'nova')
                keystone_session = ks_loading.load_session_from_conf_options(
                    cfg.CONF, 'nova', auth=auth)
                _NOVA_CONNECTION = connection.Connection(
                    session=keystone_session,
                    oslo_conf=cfg.CONF,
                    connect_retries=cfg.CONF.http_retries)
            if not _NOVA_CONNECTION.get_project(project):
                return webob.exc.HTTPNotFound(
                    comment='Project %s does not exist' % project)

        return req.get_response(self.application)
Example #45
0
def get_clients(context):
    global _SESSION

    if not _SESSION:
        _SESSION = loading.load_session_from_conf_options(
            CONF, 'designate')

    auth = token_endpoint.Token(CONF.designate.url, context.auth_token)
    client = d_client.Client(session=_SESSION, auth=auth)
    if CONF.designate.auth_type:
        admin_auth = loading.load_auth_from_conf_options(
            CONF, 'designate')
    else:
        admin_auth = password.Password(
            auth_url=CONF.designate.admin_auth_url,
            username=CONF.designate.admin_username,
            password=CONF.designate.admin_password,
            tenant_name=CONF.designate.admin_tenant_name,
            tenant_id=CONF.designate.admin_tenant_id)
    admin_client = d_client.Client(session=_SESSION, auth=admin_auth)
    return client, admin_client
 def _get_auth(self):
     #LOG.debug('KeystoneClient _get_auth xxx is_admin=%s,auth_token=%s,auth_token_info=%s', self.context.is_admin, self.context.auth_token,self.context.auth_token_info)
     if self.context.is_admin:
         auth = ka_loading.load_auth_from_conf_options(CONF, CFG_GROUP)
         #LOG.debug('KeystoneClient _get_auth xxx auth=%s', auth.__dict__);
     elif self.context.auth_token_info:
         #LOG.debug('KeystoneClient _get_auth xxx auth_token_info inside');
         access_info = ka_access.create(body=self.context.auth_token_info,
                                        auth_token=self.context.auth_token)
         auth = ka_access_plugin.AccessInfoPlugin(access_info)
     elif self.context.auth_token:
         #LOG.debug('KeystoneClient _get_auth xxx auth_token inside');
         auth = ka_v3.Token(auth_url=self.auth_url,
                            token=self.context.auth_token)
     else:
         msg = ('Keystone API connection failed: no password, '
                'trust_id or token found.')
         LOG.error(msg)
         raise exception.AuthorizationFailure(client='keystone',
                                              message='reason %s' % msg)
     #LOG.debug('KeystoneClient _get_auth xxx final auth=%s', auth);
     return auth
Example #47
0
def get_clients(context):
    global _SESSION

    if not _SESSION:
        _SESSION = loading.load_session_from_conf_options(CONF, 'designate')

    auth = token_endpoint.Token(CONF.designate.url, context.auth_token)
    client = d_client.Client(session=_SESSION, auth=auth)
    if CONF.designate.auth_type:
        admin_auth = loading.load_auth_from_conf_options(CONF, 'designate')
    else:
        # TODO(tkajinam): Make this fail when admin_* parameters are removed.
        admin_auth = password.Password(
            auth_url=CONF.designate.admin_auth_url,
            username=CONF.designate.admin_username,
            password=CONF.designate.admin_password,
            tenant_name=CONF.designate.admin_tenant_name,
            tenant_id=CONF.designate.admin_tenant_id)
    admin_client = d_client.Client(session=_SESSION,
                                   auth=admin_auth,
                                   endpoint_override=CONF.designate.url)
    return client, admin_client
Example #48
0
def _admin_client(trust_id=None):
    if CONF.keystone_authtoken.auth_type is None:
        auth_url = CONF.keystone_authtoken.www_authenticate_uri
        project_name = CONF.keystone_authtoken.admin_tenant_name

        # You can't use trust and project together

        if trust_id:
            project_name = None

        cl = ks_client.Client(username=CONF.keystone_authtoken.admin_user,
                              password=CONF.keystone_authtoken.admin_password,
                              project_name=project_name,
                              auth_url=auth_url,
                              trusts=trust_id)

        cl.management_url = auth_url

        return cl
    else:
        kwargs = {}

        if trust_id:
            # Remove domain_id, domain_name, project_name and project_id,
            # since we need a trust scoped auth object
            kwargs['domain_id'] = None
            kwargs['domain_name'] = None
            kwargs['project_name'] = None
            kwargs['project_domain_name'] = None
            kwargs['project_id'] = None
            kwargs['trust_id'] = trust_id

        auth = loading.load_auth_from_conf_options(CONF, 'keystone_authtoken',
                                                   **kwargs)
        sess = loading.load_session_from_conf_options(CONF,
                                                      'keystone',
                                                      auth=auth)

        return ks_client.Client(session=sess)
Example #49
0
    def __init__(self):
        v3_kwargs = {
            "username":
            CONF.read_option('keystone_authtoken', 'username'),
            "password":
            CONF.read_option('keystone_authtoken', 'password'),
            "project_name":
            CONF.read_option('keystone_authtoken', 'project_name'),
            "user_domain_name":
            CONF.read_option('keystone_authtoken', 'user_domain_name'),
            "project_domain_name":
            CONF.read_option('keystone_authtoken', 'project_domain_name'),
            "auth_url":
            CONF.read_option('keystone_authtoken', 'auth_url'),
            "region_name":
            CONF.read_option('keystone_authtoken', 'region_name'),
        }
        auth_plugin = loading.load_auth_from_conf_options(
            conf, "gnocchi_credentials")

        self.gn_client = gn_client.Client(
            session_options={'auth': auth_plugin})
Example #50
0
    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.
        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,
            extensions=extensions)
        self.batch_notifier = batch_notifier.BatchNotifier(
            cfg.CONF.send_events_interval, self.send_events)
def _get_keystone_auth(trust_id=None):
    if not cfg.CONF[CFG_MURANO_AUTH_GROUP].auth_type:
        # Fallback to legacy v2 options in keystone_authtoken
        # if no auth_type is set.
        # If auth_type is set, it is possible to use the auth loader
        # from keystoneauth1. This is the same fallback as keystonemiddleware
        # uses.
        versionutils.report_deprecated_feature(
            LOG, 'Please update configuration in ' + CFG_MURANO_AUTH_GROUP +
            ' group')
        auth_uri = cfg.CONF[CFG_KEYSTONE_GROUP].auth_uri
        username = cfg.CONF[CFG_KEYSTONE_GROUP].admin_user
        password = cfg.CONF[CFG_KEYSTONE_GROUP].admin_password
        project_name = cfg.CONF[CFG_KEYSTONE_GROUP].admin_tenant_name
        kwargs = {
            'auth_url': auth_uri.replace('v2.0', 'v3'),
            'username': username,
            'password': password,
            'user_domain_name': 'Default'
        }
        if not trust_id:
            kwargs['project_name'] = project_name
            kwargs['project_domain_name'] = 'Default'
        else:
            kwargs['trust_id'] = trust_id
        auth = identity.Password(**kwargs)
    else:
        kwargs = {}
        if trust_id:
            # Remove project_name and project_id, since we need a trust scoped
            # auth object
            kwargs['project_name'] = None
            kwargs['project_domain_name'] = None
            kwargs['project_id'] = None
            kwargs['trust_id'] = trust_id
        auth = ka_loading.load_auth_from_conf_options(cfg.CONF,
                                                      CFG_MURANO_AUTH_GROUP,
                                                      **kwargs)
    return auth
Example #52
0
    def __init__(self, transformers, **kwargs):
        super(GnocchiCollector, self).__init__(transformers, **kwargs)

        self.t_gnocchi = self.transformers['GnocchiTransformer']
        self.t_cloudkitty = self.transformers['CloudKittyFormatTransformer']

        adapter_options = {'connect_retries': 3}
        if CONF.gnocchi_collector.gnocchi_auth_type == 'keystone':
            auth_plugin = ks_loading.load_auth_from_conf_options(
                CONF,
                'gnocchi_collector',
            )
            adapter_options['interface'] = CONF.gnocchi_collector.interface
        else:
            auth_plugin = gauth.GnocchiBasicPlugin(
                user=CONF.gnocchi_collector.gnocchi_user,
                endpoint=CONF.gnocchi_collector.gnocchi_endpoint,
            )
        self._conn = gclient.Client(
            '1',
            session_options={'auth': auth_plugin},
            adapter_options=adapter_options,
        )
Example #53
0
 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()
Example #54
0
def _load_ks_session(conf):
    """Load session.

    This is either an authenticated session or a requests session, depending on
    what's configured.
    """
    global _ADMIN_AUTH
    global _SESSION

    if not _ADMIN_AUTH:
        _ADMIN_AUTH = ks_loading.load_auth_from_conf_options(
            conf, nova.conf.vendordata.vendordata_group.name)

    if not _ADMIN_AUTH:
        LOG.warning('Passing insecure dynamic vendordata requests '
                    'because of missing or incorrect service account '
                    'configuration.')

    if not _SESSION:
        _SESSION = ks_loading.load_session_from_conf_options(
            conf, nova.conf.vendordata.vendordata_group.name, auth=_ADMIN_AUTH)

    return _SESSION
Example #55
0
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}
Example #56
0
    def test_conf_loaded(self):
        token = uuid.uuid4().hex
        endpoint_filter = {'service_type': 'compute',
                           'service_name': 'nova',
                           'version': (2, 1)}

        loader = self.useLoadingFixture(token=token)

        url = loader.get_endpoint('/path', **endpoint_filter)

        m = self.requests_mock.get(url)

        auth = loading.load_auth_from_conf_options(self.conf_fixture.conf,
                                                   self.GROUP)
        sess = session.Session(auth=auth)
        self.assertEqual(self.AUTH_TYPE, auth.auth_type)

        sess.get('/path', endpoint_filter=endpoint_filter)

        self.assertTrue(m.called_once)

        self.assertTrue(token, m.last_request.headers['X-Auth-Token'])
        self.assertEqual(loader.project_id, sess.get_project_id())
        self.assertEqual(loader.user_id, sess.get_user_id())
Example #57
0
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.

    A raise_exc=False adapter is returned, meaning responses >=400 return the
    Response object rather than raising an exception.  This behavior can be
    overridden on a per-request basis by setting raise_exc=True.

    :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,
                                                     raise_exc=False)
Example #58
0
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 _build_auth_details(self):
        #keystone
        self._authn_token = None
        if cfg.CONF.auth_strategy == 'keystone':
            kcfg = cfg.CONF.keystone_authtoken

            #Keystone SSL Support
            self._ksinsecure=kcfg.insecure
            kscertfile=kcfg.certfile
            kskeyfile=kcfg.keyfile
            kscafile=kcfg.cafile

            self._use_ks_certs = False
            if (cfg.CONF.keystone_authtoken.auth_protocol ==
                    _DEFAULT_SECURE_SERVER_CONNECT and kscafile):
                certs = [kscafile]
                if kscertfile and kskeyfile:
                    certs = [kscertfile, kskeyfile, kscafile]
                self._kscertbundle = cfgmutils.getCertKeyCaBundle(
                        _DEFAULT_KS_CERT_BUNDLE,certs)
                self._use_ks_certs = True

            auth_uri = kcfg.auth_uri or ''
            try:
                auth_type = kcfg.auth_type
            except cfg.NoSuchOptError:
                auth_type = None
            auth_version = kcfg.auth_version
            self.ks_sess = None
            if ('v2.0' in auth_uri.split('/') or
                    auth_version == 'v2.0' or
                    not auth_type):
                body = '{"auth":{"passwordCredentials":{'
                body += ' "username": "******",' % (kcfg.admin_user)
                body += ' "password": "******"},' % (kcfg.admin_password)
                body += ' "tenantName":"%s"}}' % (kcfg.admin_tenant_name)

                self._authn_body = body
                self._authn_token = cfg.CONF.keystone_authtoken.admin_token
                try:
                    auth_token_url = cfg.CONF.APISERVER.auth_token_url
                except cfg.NoSuchOptError:
                    auth_token_url = None

                if auth_token_url:
                    self._keystone_url = auth_token_url
                else:
                    self._keystone_url = "%s://%s:%s%s" % (
                        cfg.CONF.keystone_authtoken.auth_protocol,
                        cfg.CONF.keystone_authtoken.auth_host,
                        cfg.CONF.keystone_authtoken.auth_port,
                        "/v2.0/tokens")
            else:
                from keystoneauth1 import session
                from keystoneauth1 import loading as ks_loading
                self.auth_plugin = ks_loading.load_auth_from_conf_options(
                    cfg.CONF, 'keystone_authtoken')
                if self._ksinsecure:
                    self.ks_sess = session.Session(auth=self.auth_plugin, verify=False)
                elif not self._ksinsecure and self._use_ks_certs:
                    self.ks_sess = session.Session(auth=self.auth_plugin,
                                                   verify=self._kscertbundle)
                else:
                    self.ks_sess = session.Session(auth=self.auth_plugin)

        #API Server SSL support
        self._apiusessl=cfg.CONF.APISERVER.use_ssl
        self._apiinsecure=cfg.CONF.APISERVER.insecure
        apicertfile=cfg.CONF.APISERVER.certfile
        apikeyfile=cfg.CONF.APISERVER.keyfile
        apicafile=cfg.CONF.APISERVER.cafile

        if self._apiusessl:
            self._apiserverconnect=_DEFAULT_SECURE_SERVER_CONNECT
        else:
            self._apiserverconnect=_DEFAULT_SERVER_CONNECT

        self._use_api_certs = False
        if self._apiusessl and apicafile:
            certs = [apicafile]
            if apicertfile and apikeyfile:
                certs = [apicertfile, apikeyfile, apicafile]
            self._apicertbundle = cfgmutils.getCertKeyCaBundle(
                    _DEFAULT_API_CERT_BUNDLE,certs)
            self._use_api_certs = True
Example #60
0
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)
    elif privileged_user and CONF.os_privileged_user_name:
        # Fall back to the deprecated os_privileged_xxx settings.
        # TODO(gyurco): Remove it after Pike.
        if CONF.os_privileged_user_auth_url:
            url = CONF.os_privileged_user_auth_url
        else:
            url = _get_identity_endpoint_from_sc(context)
        LOG.debug(
            'Creating Keystone password plugin from legacy settings '
            'using URL: %s', url)
        n_auth = identity.Password(auth_url=url,
                                   username=CONF.os_privileged_user_name,
                                   password=CONF.os_privileged_user_password,
                                   project_name=CONF.os_privileged_user_tenant,
                                   project_domain_id=context.project_domain,
                                   user_domain_id=context.user_domain)
    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)

    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)

    try:
        c.set_timings_max_len(CONF.nova_client.max_timing_buffer)
    except AttributeError as e:
        LOG.error(
            'fix_cinder_memory_leak was not applied to '
            'nova_client: %s', e)

    return c