Python keystoneauth1.session.Session() Examples

The following are 30 code examples of keystoneauth1.session.Session(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module keystoneauth1.session , or try the search function .
Example #1
Source File: impl_designate.py    From designate with Apache License 2.0 8 votes vote down vote up
def _get_client(self):
        if self._client is not None:
            return self._client

        auth = v3_auth.Password(
            auth_url=self.auth_url,
            username=self.username,
            password=self.password,
            project_name=self.project_name,
            project_domain_name=self.project_domain_name,
            user_domain_name=self.user_domain_name,
        )

        session = ks_session.Session(auth=auth)
        self._client = client.Client(
            session=session,
            service_type=self.service_type,
            region_name=self.region_name,
        )
        return self._client 
Example #2
Source File: keystone.py    From quay with Apache License 2.0 7 votes vote down vote up
def _get_client(self, username, password, tenant_name=None):
        if tenant_name:
            auth = keystone_v2_auth.Password(
                auth_url=self.auth_url,
                username=username,
                password=password,
                tenant_name=tenant_name,
            )
        else:
            auth = keystone_v2_auth.Password(
                auth_url=self.auth_url, username=username, password=password
            )

        sess = session.Session(auth=auth)
        client = client_v2.Client(session=sess, timeout=self.timeout, debug=self.debug)
        return client, sess 
Example #3
Source File: python_client_base.py    From magnum with Apache License 2.0 7 votes vote down vote up
def _get_auth_session(cls, username, password, project_name,
                          project_domain_id, user_domain_id, auth_url,
                          insecure):
        """Return a `keystoneauth1.session.Session` from auth parameters."""
        # create v3Password auth plugin
        _auth = ksa_v3.Password(username=username,
                                password=password,
                                project_name=project_name,
                                project_domain_id=project_domain_id,
                                user_domain_id=user_domain_id,
                                auth_url=auth_url)

        # `insecure` is being replaced by `verify`. Please note they have
        # opposite meanings.
        verify = False if insecure else True

        # create a `keystoneauth1.session.Session`
        _session = ksa_session.Session(auth=_auth, verify=verify)

        return _session 
Example #4
Source File: create-glance-images.py    From openstack-omni with Apache License 2.0 7 votes vote down vote up
def __init__(self):
        os_auth_url = os.getenv('OS_AUTH_URL')
        os_auth_url = os_auth_url.replace('v2.0', 'v3')
        if not os_auth_url.endswith('v3'):
            os_auth_url += '/v3'

        os_username = os.getenv('OS_USERNAME')
        os_password = os.getenv('OS_PASSWORD')
        os_tenant_name = os.getenv('OS_TENANT_NAME')
        os_region_name = os.getenv('OS_REGION_NAME')

        self.glance_endpoint = os_auth_url.replace('keystone/v3', 'glance')
        sys.stdout.write('Using glance endpoint: ' + self.glance_endpoint)

        v3_auth = v3.Password(auth_url = os_auth_url, username = os_username,
                              password = os_password, project_name = os_tenant_name,
                              project_domain_name = 'default', user_domain_name = 'default')
        self.sess = session.Session(auth=v3_auth, verify=False) # verify=True 
Example #5
Source File: barbican_acl.py    From octavia with Apache License 2.0 7 votes vote down vote up
def get_barbican_client_user_auth(cls, context):
        # get a normal session
        ksession = keystone.KeystoneSession()
        service_auth = ksession.get_auth()

        # make our own auth and swap it in
        user_auth = token.Token(auth_url=service_auth.auth_url,
                                token=context.auth_token,
                                project_id=context.project_id)
        user_session = session.Session(
            auth=user_auth,
            verify=CONF.certificates.ca_certificates_file)

        # create a special barbican client with our user's session
        return barbican_client.Client(
            session=user_session,
            region_name=CONF.certificates.region_name,
            interface=CONF.certificates.endpoint_type) 
Example #6
Source File: utils.py    From zun with Apache License 2.0 6 votes vote down vote up
def get_zun_client_from_env():
    # We should catch KeyError exception with the purpose of
    # source or configure openrc file.
    auth_url = os.environ['OS_AUTH_URL']
    username = os.environ['OS_USERNAME']
    password = os.environ['OS_PASSWORD']
    project_name = os.environ['OS_PROJECT_NAME']

    # Either project(user)_domain_name or project(user)_domain_id
    # would be acceptable.
    project_domain_name = os.environ.get("OS_PROJECT_DOMAIN_NAME")
    project_domain_id = os.environ.get("OS_PROJECT_DOMAIN_ID")
    user_domain_name = os.environ.get("OS_USER_DOMAIN_NAME")
    user_domain_id = os.environ.get("OS_USER_DOMAIN_ID")

    auth = identity.Password(auth_url=auth_url,
                             username=username,
                             password=password,
                             project_name=project_name,
                             project_domain_id=project_domain_id,
                             project_domain_name=project_domain_name,
                             user_domain_id=user_domain_id,
                             user_domain_name=user_domain_name)
    session = ks.Session(auth=auth)
    return client.Client(ZUN_API_VERSION, session=session) 
Example #7
Source File: api.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def __init__(
        self,
        session=None,
        service_type=None,
        endpoint=None,
        **kwargs
    ):
        """Base object that contains some common API objects and methods

        :param Session session:
            The default session to be used for making the HTTP API calls.
        :param string service_type:
            API name, i.e. ``identity`` or ``compute``
        :param string endpoint:
            The URL from the Service Catalog to be used as the base for API
            requests on this API.
        """

        super(BaseAPI, self).__init__(session=session, endpoint=endpoint)

        self.service_type = service_type

    # The basic action methods all take a Session and return dict/lists 
Example #8
Source File: api.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def __init__(
        self,
        session=None,
        endpoint=None,
        **kwargs
    ):
        """Base object that contains some common API objects and methods

        :param Session session:
            The default session to be used for making the HTTP API calls.
        :param string endpoint:
            The URL from the Service Catalog to be used as the base for API
            requests on this API.
        """

        super(KeystoneSession, self).__init__()

        # a requests.Session-style interface
        self.session = session
        self.endpoint = endpoint 
Example #9
Source File: openstack_driver.py    From tacker with Apache License 2.0 6 votes vote down vote up
def _get_client(self, vim_obj, client_type):
        """Initializes and returns an openstack client

        :param vim_obj: VIM Information
        :param client_type: openstack client to initialize
        :return: initialized client
        """
        verify = 'True' == vim_obj.get('cert_verify', 'True') or False
        auth_url = vim_obj['auth_url']
        keystone_version = NfvoPlugin.validate_keystone_auth_url(
            auth_url=auth_url,
            verify=verify)
        auth_cred = self._get_auth_creds(vim_obj, keystone_version)
        auth_plugin = self._get_auth_plugin(**auth_cred)
        sess = session.Session(auth=auth_plugin)
        return client_type(session=sess) 
Example #10
Source File: __init__.py    From cloudkitty with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        super(TestCase, self).setUp()
        self._conf_fixture = self.useFixture(config_fixture.Config())
        self.conf = self._conf_fixture.conf
        self.conf.set_override('connection', self.db_url, 'database')
        self.conn = ck_db_api.get_instance()
        migration = self.conn.get_migration()
        migration.upgrade('head')
        auth = mock.patch(
            'keystoneauth1.loading.load_auth_from_conf_options',
            return_value=dict())
        auth.start()
        self.auth = auth
        session = mock.patch(
            'keystoneauth1.loading.load_session_from_conf_options',
            return_value=ks_sess.Session())
        session.start()
        self.session = session 
Example #11
Source File: test_barbican_key_manager.py    From castellan with Apache License 2.0 6 votes vote down vote up
def get_context(self):
        username = CONF.identity.username
        password = CONF.identity.password
        project_name = CONF.identity.project_name
        auth_url = CONF.identity.auth_url
        user_domain_name = CONF.identity.user_domain_name
        project_domain_name = CONF.identity.project_domain_name

        auth = identity.V3Password(auth_url=auth_url,
                                   username=username,
                                   password=password,
                                   project_name=project_name,
                                   user_domain_name=user_domain_name,
                                   project_domain_name=project_domain_name)
        sess = session.Session(auth=auth)

        return context.RequestContext(auth_token=auth.get_token(sess),
                                      tenant=auth.get_project_id(sess)) 
Example #12
Source File: nfv_parameters.py    From JetPack with Apache License 2.0 6 votes vote down vote up
def get_inspector_client(self):
        os_auth_url, os_tenant_name, os_username, os_password, \
            os_user_domain_name, os_project_domain_name = \
            CredentialHelper.get_undercloud_creds()
        auth_url = os_auth_url + "v3"

        kwargs = {
                'username': os_username,
                'password': os_password,
                'auth_url': os_auth_url,
                'project_id': os_tenant_name,
                'user_domain_name': os_user_domain_name,
                'project_domain_name': os_project_domain_name
                }
        auth = v3.Password(
            auth_url=auth_url,
            username=os_username,
            password=os_password,
            project_name=os_tenant_name,
            user_domain_name=os_user_domain_name,
            project_domain_name=os_project_domain_name
            )
        sess = session.Session(auth=auth)
        self.inspector = ironic_inspector_client.ClientV1(session=sess) 
Example #13
Source File: client.py    From syntribos with Apache License 2.0 6 votes vote down vote up
def _get_client():
    """Returns a v2 cinder client object."""
    auth_url = CONF.user.endpoint
    if auth_url.endswith("/v3/"):
        auth_url = auth_url[-1]
    elif auth_url.endswith("/v3"):
        pass
    else:
        auth_url = "{}/v3".format(auth_url)
    auth = identity.v3.Password(auth_url=auth_url,
                                project_name=CONF.user.project_name,
                                project_domain_name=CONF.user.domain_name,
                                user_domain_name=CONF.user.domain_name,
                                username=CONF.user.username,
                                password=CONF.user.password)
    return Client("2", session=session.Session(auth=auth)) 
Example #14
Source File: basic_and_keystone_auth.py    From vitrage with Apache License 2.0 6 votes vote down vote up
def _basic_authenticate(self, auth_info, req):
        try:
            project_domain_id, project_name, user_domain_id = \
                self._get_auth_params()
            auth = password.Password(auth_url=self.auth_url,
                                     username=auth_info.username,
                                     password=auth_info.password,
                                     user_domain_id=user_domain_id,
                                     project_domain_id=project_domain_id,
                                     project_name=project_name)
            sess = session.Session(auth=auth)
            token = sess.get_token()
            project_id = str(auth.get_project_id(sess))
            roles = str(auth.get_auth_ref(sess).role_names[0])
            self._set_req_headers(req, token, project_id, roles)
        except Exception as e:
            to_unicode = encodeutils.exception_to_unicode(e)
            message = 'Authorization exception: %s' % to_unicode
            self._unauthorized(message) 
Example #15
Source File: provider.py    From cloudbridge with MIT License 6 votes vote down vote up
def _connect_keystone(self):
        """Get an OpenStack Keystone (identity) client object."""
        if self._keystone_version == 3:
            return keystone_client.Client(session=self._keystone_session,
                                          auth_url=self.auth_url)
        else:
            # Wow, the internal keystoneV2 implementation is terribly buggy. It
            # needs both a separate Session object and the username, password
            # again for things to work correctly. Plus, a manual call to
            # authenticate() is also required if the service catalog needs
            # to be queried.
            keystone = keystone_client.Client(
                session=self._keystone_session,
                auth_url=self.auth_url,
                username=self.username,
                password=self.password,
                project_name=self.project_name,
                region_name=self.region_name)
            keystone.authenticate()
            return keystone 
Example #16
Source File: pdk.py    From compute-hyperv with Apache License 2.0 6 votes vote down vote up
def _get_pdk_container(self, context, instance, pdk_reference):
        """Retrieves the barbican container containing the pdk file.
        """

        auth = context.get_auth_plugin()
        sess = session.Session(auth=auth)
        brb_client = barbican_client.Client(session=sess)

        try:
            pdk_container = brb_client.containers.get(pdk_reference)
        except Exception as e:
            err_msg = _("Retrieving barbican container with reference "
                        "%(pdk_reference)s failed with error: %(error)s") % {
                        'pdk_reference': pdk_reference,
                        'error': e}
            raise exception.InvalidMetadata(instance_id=instance.uuid,
                                            reason=err_msg)
        return pdk_container 
Example #17
Source File: test_barbican_key_manager.py    From castellan with Apache License 2.0 6 votes vote down vote up
def get_context(self):
        username = CONF.identity.username
        password = CONF.identity.password
        project_name = CONF.identity.project_name
        auth_url = CONF.identity.auth_url
        user_domain_name = CONF.identity.user_domain_name
        project_domain_name = CONF.identity.project_domain_name

        auth = identity.V3Password(auth_url=auth_url,
                                   username=username,
                                   password=password,
                                   project_name=project_name,
                                   user_domain_name=user_domain_name,
                                   project_domain_name=project_domain_name)
        sess = session.Session()

        return keystone_token.KeystoneToken(
            token=auth.get_token(sess),
            auth_url=auth_url,
            project_id=auth.get_project_id(sess)) 
Example #18
Source File: api.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def create(
        self,
        url,
        session=None,
        method=None,
        **params
    ):
        """Create a new resource

        :param string url:
            The API-specific portion of the URL path
        :param Session session:
            HTTP client session
        :param string method:
            HTTP method (default POST)
        """

        if not method:
            method = 'POST'
        ret = self._request(method, url, session=session, **params)
        # Should this move into _requests()?
        try:
            return ret.json()
        except json.JSONDecodeError:
            return ret 
Example #19
Source File: shell.py    From eclcli with Apache License 2.0 6 votes vote down vote up
def _get_keystone_session(self, **kwargs):
        # first create a Keystone session
        cacert = kwargs.pop('cacert', None)
        cert = kwargs.pop('cert', None)
        key = kwargs.pop('key', None)
        insecure = kwargs.pop('insecure', False)
        timeout = kwargs.pop('timeout', None)
        verify = kwargs.pop('verify', None)

        # FIXME(gyee): this code should come from keystoneclient
        if verify is None:
            if insecure:
                verify = False
            else:
                # TODO(gyee): should we do
                # heatclient.common.http.get_system_ca_fle()?
                verify = cacert or True
        if cert and key:
            # passing cert and key together is deprecated in favour of the
            # requests lib form of having the cert and key as a tuple
            cert = (cert, key)

        return kssession.Session(verify=verify, cert=cert, timeout=timeout) 
Example #20
Source File: test_functional_swift.py    From glance_store with Apache License 2.0 6 votes vote down vote up
def tearDown(self):
        auth = v3.Password(auth_url=self.auth_url,
                           username=self.username,
                           password=self.password,
                           project_name=self.project_name,
                           user_domain_id=self.user_domain_id,
                           project_domain_id=self.project_domain_id)
        sess = session.Session(auth=auth)
        swift = swiftclient.client.Connection(session=sess)

        for x in range(1, 4):
            time.sleep(x)
            try:
                _, objects = swift.get_container(self.container)
                for obj in objects:
                    swift.delete_object(self.container, obj.get('name'))
                swift.delete_container(self.container)
            except Exception:
                if x < 3:
                    pass
                else:
                    raise
            else:
                break
        super(TestSwift, self).tearDown() 
Example #21
Source File: client.py    From python-monascaclient with Apache License 2.0 6 votes vote down vote up
def _session(kwargs):
    """Returns or reuses session.

    Method takes care of providing instance of
    session object for the client.

    :param kwargs: all params (without api_version) client was initialized with
    :type kwargs: dict

    :returns: session object
    :rtype keystoneauth1.session.Session

    """
    if 'session' in kwargs:
        LOG.debug('Reusing session')
        sess = kwargs.get('session')
        if not isinstance(sess, k_session.Session):
            msg = ('session should be an instance of %s' % k_session.Session)
            LOG.error(msg)
            raise RuntimeError(msg)
    else:
        LOG.debug('Initializing new session')
        auth = _get_auth_handler(kwargs)
        sess = _get_session(auth, kwargs)
    return sess 
Example #22
Source File: kuryr_base.py    From kuryr-libnetwork with Apache License 2.0 6 votes vote down vote up
def get_neutron_client_from_env():
    # We should catch KeyError exception with the purpose of
    # source or configure openrc file.
    auth_url = os.environ['OS_AUTH_URL']
    username = os.environ['OS_USERNAME']
    password = os.environ['OS_PASSWORD']
    project_name = os.environ['OS_PROJECT_NAME']

    # Either project(user)_domain_name or project(user)_domain_id
    # would be acceptable.
    project_domain_name = os.environ.get("OS_PROJECT_DOMAIN_NAME")
    project_domain_id = os.environ.get("OS_PROJECT_DOMAIN_ID")
    user_domain_name = os.environ.get("OS_USER_DOMAIN_NAME")
    user_domain_id = os.environ.get("OS_USER_DOMAIN_ID")

    auth = identity.Password(auth_url=auth_url,
                             username=username,
                             password=password,
                             project_name=project_name,
                             project_domain_id=project_domain_id,
                             project_domain_name=project_domain_name,
                             user_domain_id=user_domain_id,
                             user_domain_name=user_domain_name)
    session = ks.Session(auth=auth)
    return client.Client(session=session) 
Example #23
Source File: test_client.py    From python-monascaclient with Apache License 2.0 6 votes vote down vote up
def test_should_reuse_the_session_if_initialized_with_one(self,
                                                              get_session,
                                                              get_auth,
                                                              _):
        from keystoneauth1 import session as k_session

        api_version = mock.Mock()
        session = mock.Mock(spec=k_session.Session)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            client.Client(api_version, session=session)
            self.assertEqual(0, len(w))

        get_auth.assert_not_called()
        get_session.assert_not_called() 
Example #24
Source File: cloud_region.py    From openstacksdk with Apache License 2.0 6 votes vote down vote up
def insert_user_agent(self):
        """Set sdk information into the user agent of the Session.

        .. warning::
            This method is here to be used by os-client-config. It exists
            as a hook point so that os-client-config can provice backwards
            compatibility and still be in the User Agent for people using
            os-client-config directly.

        Normal consumers of SDK should use app_name and app_version. However,
        if someone else writes a subclass of
        :class:`~openstack.config.cloud_region.CloudRegion` it may be
        desirable.
        """
        self._keystone_session.additional_user_agent.append(
            ('openstacksdk', openstack_version.__version__)) 
Example #25
Source File: keystone.py    From quay with Apache License 2.0 6 votes vote down vote up
def _get_client(self, username, password, project_name=None):
        if project_name:
            auth = keystone_v3_auth.Password(
                auth_url=self.auth_url,
                username=username,
                password=password,
                project_name=project_name,
                project_domain_id=self.project_domain_id,
                user_domain_id=self.user_domain_id,
            )
        else:
            auth = keystone_v3_auth.Password(
                auth_url=self.auth_url,
                username=username,
                password=password,
                user_domain_id=self.user_domain_id,
            )

        sess = session.Session(auth=auth)
        client = client_v3.Client(session=sess, timeout=self.timeout, debug=self.debug)
        return client, sess 
Example #26
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def __init__(self, host='127.0.0.1', version='2', port=None, user='root', password=None, debug=False, project=None,
                 domain='Default', auth_url=None, ca_file=None):
        self.debug = debug
        self.host = host
        loader = loading.get_plugin_loader('password')
        auth = loader.load_from_options(auth_url=auth_url, username=user, password=password, project_name=project,
                                        user_domain_name=domain, project_domain_name=domain)
        sess = session.Session(auth=auth, verify=ca_file)
        self.nova = novaclient.Client(version, session=sess)
        self.glance = glanceclient(version, session=sess)
        self.cinder = cinderclient.Client(version, session=sess)
        self.neutron = neutronclient(session=sess)
        self.conn = self.nova
        self.project = project
        return

# should cleanly close your connection, if needed 
Example #27
Source File: utils.py    From tripleo-validations with Apache License 2.0 6 votes vote down vote up
def get_auth_session(auth_variables):
    auth_url = auth_variables.get('auth_url')
    username = auth_variables.get('username')
    project_name = auth_variables.get('project_name')
    auth_token = auth_variables.get('os_auth_token')
    password = auth_variables.get('password')
    cacert = auth_variables.get('cacert')
    timeout = auth_variables.get('timeout')

    if auth_token:
        auth = ks_id.Token(auth_url=auth_url,
                           token=auth_token,
                           project_name=project_name,
                           project_domain_id='default')
    else:
        auth = ks_id.Password(auth_url=auth_url,
                              username=username,
                              password=password,
                              project_name=project_name,
                              user_domain_id='default',
                              project_domain_id='default')
    return ks_session.Session(auth=auth, verify=cacert, timeout=timeout) 
Example #28
Source File: keystone.py    From mistral-extra with Apache License 2.0 6 votes vote down vote up
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 #29
Source File: cloud_region.py    From openstacksdk with Apache License 2.0 5 votes vote down vote up
def set_session_constructor(self, session_constructor):
        """Sets the Session constructor."""
        self._session_constructor = session_constructor 
Example #30
Source File: openstack_driver.py    From tacker with Apache License 2.0 5 votes vote down vote up
def __init__(self, auth_attr):
        auth_cred = auth_attr.copy()
        verify = 'True' == auth_cred.pop('cert_verify', 'True') or False
        auth = identity.Password(**auth_cred)
        sess = session.Session(auth=auth, verify=verify)
        self.client = neutron_client.Client(session=sess)