def from_config(opts):
    """Create a connection from a configuration.

    Create a :class:`~openstack.connection.Connection` from a configuration
    similar to a os-client-config CloudConfig.

    :param opts: An options class like the :class:`~argparse.Namespace` class.

    :rtype: :class:`~openstack.connection.Connection`
    """

    # TODO(thowe): I proposed that service name defaults to None in OCC
    defaults = {}
    prof = profile.Profile()
    services = [service.service_type for service in prof.get_services()]
    for service in services:
        defaults[service + '_service_name'] = None
    # TODO(thowe): default is 2 which turns into v2 which doesn't work
    # this stuff needs to be fixed where we keep version and path separated.
    defaults['network_api_version'] = 'v2.0'

    # Get the cloud_config
    occ = os_client_config.OpenStackConfig(override_defaults=defaults)
    cloud_config = occ.get_one_cloud(opts.cloud, argparse=opts)

    if cloud_config.debug:
        utils.enable_logging(True, stream=sys.stdout)

    # TODO(mordred) we need to add service_type setting to openstacksdk.
    # Some clouds have type overridden as well as name.
    prof = profile.Profile()
    services = [service.service_type for service in prof.get_services()]
    for service in cloud_config.get_services():
        if service in services:
            version = cloud_config.get_api_version(service)
            if version:
                version = str(version)
                if not version.startswith("v"):
                    version = "v" + version
            prof.set_version(service, version)
            prof.set_name(service, cloud_config.get_service_name(service))
            prof.set_interface(service, cloud_config.get_interface(service))
            prof.set_region(service, cloud_config.get_region_name(service))

    # Auth
    auth = cloud_config.config['auth']
    # TODO(thowe) We should be using auth_type
    auth['auth_plugin'] = cloud_config.config['auth_type']
    if 'cacert' in cloud_config.config:
        auth['verify'] = cloud_config.config['cacert']
    if 'insecure' in cloud_config.config:
        auth['verify'] = not bool(cloud_config.config['insecure'])

    return Connection(profile=prof, **auth)
 def test_set(self):
     prof = profile.Profile()
     self.assertEqual(None, prof.get_preference('compute'))
     prof.set_version('compute', 'v2')
     self.assertEqual('v2', prof.get_preference('compute').version)
     self.assertEqual(None, prof.get_preference('clustering'))
     prof.set_version('clustering', 'v1')
     self.assertEqual('v1', prof.get_preference('clustering').version)
     self.assertEqual(None, prof.get_preference('database'))
     prof.set_version('database', 'v3')
     self.assertEqual('v3', prof.get_preference('database').version)
     self.assertEqual(None, prof.get_preference('identity'))
     prof.set_version('identity', 'v4')
     self.assertEqual('v4', prof.get_preference('identity').version)
     self.assertEqual(None, prof.get_preference('image'))
     prof.set_version('image', 'v5')
     self.assertEqual('v5', prof.get_preference('image').version)
     self.assertEqual(None, prof.get_preference('metering'))
     prof.set_version('metering', 'v6')
     self.assertEqual('v6', prof.get_preference('metering').version)
     self.assertEqual(None, prof.get_preference('metric'))
     prof.set_version('metric', 'v9')
     self.assertEqual('v9', prof.get_preference('metric').version)
     self.assertEqual(None, prof.get_preference('network'))
     prof.set_version('network', 'v7')
     self.assertEqual('v7', prof.get_preference('network').version)
     self.assertEqual(None, prof.get_preference('object-store'))
     prof.set_version('object-store', 'v8')
     self.assertEqual('v8', prof.get_preference('object-store').version)
     self.assertEqual(None, prof.get_preference('orchestration'))
     prof.set_version('orchestration', 'v9')
     self.assertEqual('v9', prof.get_preference('orchestration').version)
示例#3
0
def op_connectionv3(data):
    '''python3 openstack_sdk连接 :已完成'''
    from openstack import profile
    from openstack import connection
    region = data['region']
    auth_url = data['auth_url']
    username = data['username']
    password = data['password']
    tenant_name = data['tenant_name']
    domain_name = data['domain_name']
    prof = profile.Profile()
    prof.set_region(profile.Profile.ALL, region)
    return connection.Connection(
        profile=prof,
        user_agent='examples',
        auth_url=auth_url,
        username=username,
        password=password,
        project_name=tenant_name,
        region_name=region,
        project_domain_name=domain_name,
        user_domain_name=domain_name,
        identity_api_version=3,
        # identity_api_version=identity_api_version,
        # image_api_version=image_api_version)
        image_api_version=2)
示例#4
0
def _connect_to_openstack_sdk(*args, **kwargs):
    """
    Connect to OpenStack SDK client
    """

    # Atmosphere was configured on 'v2' naming.
    # This will update the value to the current naming, 'project_name'
    from openstack import profile
    from openstack import utils
    identity_version = kwargs.get('identity_api_version', 2)
    if identity_version == 2:
        return None
    utils.enable_logging(
        True, stream=sys.stdout)  # TODO: stream this to _not_ stdout
    user_profile = profile.Profile()
    user_profile.set_region(profile.Profile.ALL, kwargs.get('region_name'))
    if 'project_name' not in kwargs and 'tenant_name' in kwargs:
        kwargs['project_name'] = kwargs.pop('tenant_name')

    user_profile.set_version('identity', 'v%s' % identity_version)
    user_profile.set_interface('identity', 'admin')
    user_agent = "rtwo/%s" % (rtwo_version(), )
    stack_sdk = openstack_sdk.Connection(user_agent=user_agent,
                                         profile=user_profile,
                                         **kwargs)
    return stack_sdk
示例#5
0
    def __init__(self, auth_url, project, username, password):
        self.res_serv_map = {}
        for serv in self.serv_reslist_map:
            for res in self.serv_reslist_map[serv]:
                self.res_serv_map[res] = serv

        self.connection_map = {}
        param = {
            'auth_url': auth_url,
            'project_name': project,
            'user_domain_name': 'default',
            'project_domain_name': 'default',
            'username': username,
            'password': password
        }

        for region in ('CentralRegion', 'RegionOne', 'RegionTwo'):
            prof = profile.Profile()
            if region == 'CentralRegion':
                serv = multiregion_network_service.MultiregionNetworkService(
                    version='v1')
                prof._add_service(serv)
            net_serv = network_service.NetworkService(version='v2')
            prof._add_service(net_serv)
            prof.set_region(profile.Profile.ALL, region)
            param['profile'] = prof
            conn = connection.Connection(**param)
            self.connection_map[region] = conn
示例#6
0
 def makeConnection(self):
     """
         This method is defined to make connection with keystone.        
     """
     try:
         log.info(" Setting Profile !!")
         prof = profile.Profile()
         prof.set_region(profile.Profile.ALL, self.regionName)
         log.info(" Profile has been successfully set!")
     except Exception as ex:
         log.error(
             "Error in setting profile with region. reason is {}".format(
                 ex))
         return 400, ex
     else:
         self.configDict['profile'] = prof
         #self.auth_args=self.configDict
         try:
             conn = connection.Connection(**self.configDict)
             conn.authorize()
             log.info("Connection get established !")
         except openstack.exceptions.SDKException as ex:
             log.error(
                 "Error in connection with keystone. Reason is {}".format(
                     ex))
             """
                 Unable to establish connection to http://10.10.1.103:35357/v3: 
                 HTTPConnectionPool(host='10.10.1.103', port=35357): 
                 Max retries exceeded with url: /v3
                 (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7fa7e3068710>: 
                 Failed to establish a new connection: [Errno 111] Connection refused',))
             """
             return 400, ex
         else:
             return 201, conn
示例#7
0
 def test_create_session(self):
     auth = mock.Mock()
     prof = profile.Profile()
     conn = connection.Connection(authenticator=auth, profile=prof)
     self.assertEqual(auth, conn.authenticator)
     self.assertEqual(prof, conn.profile)
     self.assertEqual('openstack.telemetry.alarm.v2._proxy',
                      conn.alarm.__class__.__module__)
     self.assertEqual('openstack.cluster.v1._proxy',
                      conn.cluster.__class__.__module__)
     self.assertEqual('openstack.compute.v2._proxy',
                      conn.compute.__class__.__module__)
     self.assertEqual('openstack.database.v1._proxy',
                      conn.database.__class__.__module__)
     self.assertEqual('openstack.identity.v3._proxy',
                      conn.identity.__class__.__module__)
     self.assertEqual('openstack.image.v2._proxy',
                      conn.image.__class__.__module__)
     self.assertEqual('openstack.network.v2._proxy',
                      conn.network.__class__.__module__)
     self.assertEqual('openstack.object_store.v1._proxy',
                      conn.object_store.__class__.__module__)
     self.assertEqual('openstack.load_balancer.v2._proxy',
                      conn.load_balancer.__class__.__module__)
     self.assertEqual('openstack.orchestration.v1._proxy',
                      conn.orchestration.__class__.__module__)
     self.assertEqual('openstack.telemetry.v2._proxy',
                      conn.telemetry.__class__.__module__)
     self.assertEqual('openstack.workflow.v2._proxy',
                      conn.workflow.__class__.__module__)
示例#8
0
def make_client(instance):
    """Returns a network proxy"""
    if getattr(instance, "sdk_connection", None) is None:
        if profile is None:
            # If the installed OpenStackSDK is new enough to not require a
            # Profile obejct and osc-lib is not new enough to have created
            # it for us, make an SDK Connection.
            # NOTE(dtroyer): This can be removed when this bit is in the
            #                released osc-lib in requirements.txt.
            conn = connection.Connection(
                config=instance._cli_options,
                session=instance.session,
            )
        else:
            # Fall back to the original Connection creation
            prof = profile.Profile()
            prof.set_region(API_NAME, instance.region_name)
            prof.set_version(API_NAME, instance._api_version[API_NAME])
            prof.set_interface(API_NAME, instance.interface)
            conn = connection.Connection(
                authenticator=instance.session.auth,
                verify=instance.session.verify,
                cert=instance.session.cert,
                profile=prof,
            )

        instance.sdk_connection = conn

    conn = instance.sdk_connection
    LOG.debug('Connection: %s', conn)
    LOG.debug('Network client initialized using OpenStack SDK: %s',
              conn.network)
    return conn.network
def html_endpoint_urls(conn):
    from openstack import profile as _profile
    from openstack import exceptions as _exceptions

    prof = _profile.Profile()
    services = [service.service_type for service in prof.get_services()]
    #print(services)

    #service_list=['compute', 'clustering', 'orchestration', 'database', 'network', 'volume', 'messaging', 'identity',
    #              'metering', 'object-store', 'key-manager', 'image']
    #service_list=['compute', 'orchestration', 'network', 'volume', 'identity', 'metering', 'object-store', 'image']
    service_list = ['compute', 'network', 'volume', 'identity', 'image']

    endpoint_urls = {}
    for service in services:
        if service in service_list:
            #print("SERVICE:" + service)
            signal.alarm(10)
            try:
                url = conn.authenticator.get_endpoint(conn.session,
                                                      service_type=service,
                                                      interface='public')
                endpoint_urls[service] = url
            #except _exceptions.EndpointNotFound:
            #    pass
            #except TimeoutException as e:
            except Exception as e:
                #raise
                print("Failed to determine '{}' service endpoint url".format(
                    service))
            finally:
                signal.alarm(0)

    return html_ping_endpoint_urls(endpoint_urls)
示例#10
0
def create_connection(params=None):
    if params is None:
        params = {}

    if params.get('token', None):
        auth_plugin = 'token'
    else:
        auth_plugin = 'password'

    prof = profile.Profile()
    prof.set_version('identity', 'v3')
    prof.set_version('messaging', 'v2')
    if 'region_name' in params:
        prof.set_region(prof.ALL, params['region_name'])
        params.pop('region_name')
    elif cfg.CONF.default_region_name:
        prof.set_region(prof.ALL, cfg.CONF.default_region_name)
    try:
        conn = connection.Connection(profile=prof,
                                     user_agent=USER_AGENT,
                                     auth_plugin=auth_plugin,
                                     **params)
    except Exception as ex:
        raise parse_exception(ex)

    return conn
示例#11
0
    def __init__(self, transport, authenticator, profile=None):
        """Create a new object with a transport and authenticator.

        Session layer which uses the transport for communication.  The
        authenticator also uses the transport to keep authenticated.

        :param transport: A transport that provides an HTTP request method.
            The transport is also to be used by the authenticator, if needed.
        :type transport: :class:`~openstack.transport.Transport`
        :param authenticator: An authenticator that provides get_token and
            get_endpoint methods for the session.
        :type authenticator: :class:`~openstack.auth.base.BaseAuthPlugin`
        :param profile: If the user has any special profiles such as the
            service name, region, version or interface, they may be provided
            in the profile object.  If no profiles are provided, the
            services that appear first in the service catalog will be used.
        :type profile: :class:`~openstack.profile.Profile`

        All the other methods of the session accept the following parameters:

        :param str path: Path relative to service base url.
        :param service: a service filter for the authenticator to determine
            the correct endpoint to use.
        :type service: :class:`~openstack.service_filter.ServiceFilter`
        :param bool authenticate: A flag that indicates if a token should be
            attached to the request.  This parameter defaults to true.
        :param kwargs: The remaining arguments are passed to the transport
            request method.
        """
        self.transport = transport
        self.authenticator = authenticator
        self.profile = profile or _profile.Profile()
 def setUp(self):
     super(TestConnection, self).setUp()
     self.xport = transport.Transport()
     self.auth = v2.Token(auth_url='http://127.0.0.1/v2', token='b')
     self.prof = profile.Profile()
     self.conn = connection.Connection(authenticator=mock.MagicMock(),
                                       transport=mock.MagicMock())
     self.conn.session = mock.MagicMock()
示例#13
0
    def __init__(self,
                 session=None,
                 authenticator=None,
                 profile=None,
                 verify=True,
                 user_agent=None,
                 auth_plugin="password",
                 **auth_args):
        """Create a context for a connection to a cloud provider.

        A connection needs a transport and an authenticator.  The user may pass
        in a transport and authenticator they want to use or they may pass in
        the parameters to create a transport and authenticator.  The connection
        creates a
        :class:`~openstack.session.Session` which uses the profile
        and authenticator to perform HTTP requests.

        :param session: A session object compatible with
            :class:`~openstack.session.Session`.
        :type session: :class:`~openstack.session.Session`
        :param authenticator: An authenticator derived from the base
            authenticator plugin that was previously created.  Two common
            authentication identity plugins are
            :class:`identity_v2 <openstack.auth.identity.v2.Auth>` and
            :class:`identity_v3 <openstack.auth.identity.v3.Auth>`.
            If this parameter is not passed in, the connection will create an
            authenticator.
        :type authenticator: :class:`~openstack.auth.base.BaseAuthPlugin`
        :param profile: If the user has any special profiles such as the
            service name, region, version or interface, they may be provided
            in the profile object.  If no profiles are provided, the
            services that appear first in the service catalog will be used.
        :type profile: :class:`~openstack.profile.Profile`
        :param bool verify: If a transport is not provided to the connection,
            this parameter will be used to create a transport.  If ``verify``
            is set to true, which is the default, the SSL cert will be
            verified.  It can also be set to a CA_BUNDLE path.
        :param str user_agent: If a transport is not provided to the
            connection, this parameter will be used when creating a transport.
            The value given here will be prepended to the default, which is
            specified in :attr:`~openstack.transport.USER_AGENT`.
            The resulting ``user_agent`` value is used for the ``User-Agent``
            HTTP header.
        :param str auth_plugin: The name of authentication plugin to use.
            The default value is ``password``.
        :param auth_args: The rest of the parameters provided are assumed to be
            authentication arguments that are used by the authentication
            plugin.
        """
        self.authenticator = self._create_authenticator(
            authenticator, auth_plugin, **auth_args)
        self.profile = profile if profile else _profile.Profile()
        self.session = session if session else _session.Session(
            self.profile,
            auth=self.authenticator,
            verify=verify,
            user_agent=user_agent)
        self._open()
示例#14
0
 def test_set_all(self):
     prof = profile.Profile()
     prof.set_name(prof.ALL, 'fee')
     prof.set_region(prof.ALL, 'fie')
     prof.set_interface(prof.ALL, 'public')
     for service in prof.service_keys:
         self.assertEqual('fee', prof.get_filter(service).service_name)
         self.assertEqual('fie', prof.get_filter(service).region)
         self.assertEqual('public', prof.get_filter(service).interface)
示例#15
0
 def test_set_api_version(self):
     # This tests that api_version is effective after explicit setting, or
     # else it defaults to None.
     prof = profile.Profile()
     prof.set_api_version('clustering', '1.2')
     svc = prof.get_filter('clustering')
     self.assertEqual('1.2', svc.api_version)
     svc = prof.get_filter('compute')
     self.assertIsNone(svc.api_version)
示例#16
0
    def test_init_with_single_api_request(self):
        prof = profile.Profile()
        prof.set_api_version('clustering', '1.2')

        sot = session.Session(prof)

        # The assertion acutally tests the property assigned in parent class
        self.assertEqual({'openstack-api-version': 'clustering 1.2'},
                         sot.additional_headers)
示例#17
0
def create_connection(auth_url, region, project_name, username, password):
    prof = profile.Profile()
    prof.set_region(profile.Profile.ALL, region)

    return connection.Connection(profile=prof,
                                 user_agent='examples',
                                 auth_url=auth_url,
                                 project_name=project_name,
                                 username=username,
                                 password=password)
示例#18
0
 def create(self):
     self.__profile = profile.Profile()
     self.__profile.set_region(profile.Profile.ALL, self.__region)
     self.__connect = connection.Connection(
         profile=self.__profile,
         auth_url=self.__auth_url,
         project_name=self.__project_name,
         username=self.__username,
         password=self.__password,
         user_agent=self.__user_agent)
示例#19
0
 def _create(self):
     interface = self._get_client_option(CLIENT_NAME, 'endpoint_type')
     prof = profile.Profile()
     prof.set_interface(self.CLUSTERING, interface)
     prof.set_region(self.CLUSTERING, self._get_region_name())
     keystone_session = self.context.keystone_session
     s = session.Session(session=keystone_session,
                         auth=keystone_session.auth,
                         profile=prof)
     return client.Client(self.VERSION, session=s)
示例#20
0
def make_client(instance):
    """Returns a network proxy"""
    prof = profile.Profile()
    prof.set_region(API_NAME, instance._region_name)
    prof.set_version(API_NAME, instance._api_version[API_NAME])
    conn = connection.Connection(authenticator=instance.session.auth,
                                 verify=instance.session.verify, profile=prof)
    LOG.debug('Connection: %s', conn)
    LOG.debug('Network client initialized using OpenStack SDK: %s',
              conn.network)
    return conn.network
示例#21
0
def make_client(instance):
    """Returns a clustering proxy"""
    prof = profile.Profile()
    prof.set_api_version(API_NAME, CURRENT_API_VERSION)

    conn = connection.Connection(profile=prof,
                                 authenticator=instance.session.auth)
    LOG.debug('Connection: %s', conn)
    LOG.debug('Clustering client initialized using OpenStackSDK: %s',
              conn.cluster)
    return conn.cluster
示例#22
0
    def test_init_with_multi_api_requests(self):
        prof = profile.Profile()
        prof.set_api_version('clustering', '1.2')
        prof.set_api_version('compute', '2.15')

        sot = session.Session(prof)

        versions = sot.additional_headers['openstack-api-version']
        requests = [req.strip() for req in versions.split(',')]
        self.assertIn('clustering 1.2', requests)
        self.assertIn('compute 2.15', requests)
示例#23
0
    def test_init(self):
        expected = [
            'alarming', 'auto-scaling', 'baremetal', 'cloud-eye', 'clustering',
            'compute', 'database', 'dns', 'identity', 'image', 'key-manager',
            'load-balancer', 'map-reduce', 'messaging', 'metering', 'network',
            'object-store', 'orchestration', 'volume', 'volume-backup',
            'workflowv2'
        ]
        prof = profile.Profile()

        self.assertEqual(expected, prof.service_keys)
 def test_set_all(self):
     prof = profile.Profile()
     prof.set_name(prof.ALL, 'fee')
     prof.set_region(prof.ALL, 'fie')
     prof.set_version(prof.ALL, 'foe')
     prof.set_visibility(prof.ALL, 'public')
     for service in prof.service_names:
         self.assertEqual('fee', prof.get_preference(service).service_name)
         self.assertEqual('fie', prof.get_preference(service).region)
         self.assertEqual('foe', prof.get_preference(service).version)
         self.assertEqual('public', prof.get_preference(service).visibility)
示例#25
0
    def test_from_profile(self):
        """Copied from openstackclient/network/client.py make_client."""
        API_NAME = "network"
        instance = self.cloud_config

        prof = profile.Profile()
        prof.set_region(API_NAME, instance.region_name)
        prof.set_version(API_NAME, instance.get_api_version(API_NAME))
        prof.set_interface(API_NAME, instance.get_interface(API_NAME))
        connection.Connection(authenticator=instance.get_session().auth,
                              verify=instance.get_session().verify,
                              cert=instance.get_session().cert,
                              profile=prof)
示例#26
0
    def setUpClass(cls):
        name = os.getenv('OS_CLOUD', 'test_cloud')
        test_cloud = os_client_config.OpenStackConfig().get_one_cloud(name)

        prof = profile.Profile()
        prof.set_region(prof.ALL, test_cloud.region)
        if test_cloud.debug:
            utils.enable_logging(True, stream=sys.stdout)

        auth = test_cloud.config['auth']
        if 'insecure' in test_cloud.config:
            auth['verify'] = not bool(test_cloud.config['insecure'])
        cls.conn = connection.Connection(profile=prof, **auth)
示例#27
0
def create_connection(auth_url, region, project_name, username, password):
    """ Connect and authenticate to OpenStack
 
    This function came straight from the Openstack docs:
    http://developer.openstack.org/sdks/python/openstacksdk/users/guides/connect.html
    """
    prof = profile.Profile()
    prof.set_region(profile.Profile.ALL, region)
    return connection.Connection(profile=prof,
                                 user_agent='examples',
                                 auth_url=auth_url,
                                 project_name=project_name,
                                 username=username,
                                 password=password)
示例#28
0
    def _connect_openstack(self):
        prof = profile.Profile()
        prof.set_region(profile.Profile.ALL, self.region_name)

        return connection.Connection(
            profile=prof,
            user_agent='cloudbridge',
            auth_url=self.auth_url,
            project_name=self.project_name,
            username=self.username,
            password=self.password,
            user_domain_name=self.user_domain_name,
            project_domain_name=self.project_domain_name
        )
示例#29
0
    def _create(self, version=None):
        prof = profile.Profile()
        for svc_type in self.service_types:
            interface = self._get_client_option(
                self.service_client_map[svc_type], 'endpoint_type')
            prof.set_interface(svc_type, interface)
            prof.set_region(svc_type, self._get_region_name())
            prof.set_version(svc_type, self.api_version_map[svc_type])

        key_session = self.context.keystone_session
        return connection.Connection(authenticator=key_session.auth,
                                     verify=key_session.verify,
                                     cert=key_session.cert,
                                     profile=prof)
示例#30
0
 def test_default_versions(self):
     prof = profile.Profile()
     self.assertEqual('v1', prof.get_filter('clustering').version)
     self.assertEqual('v2', prof.get_filter('compute').version)
     self.assertEqual('v1', prof.get_filter('database').version)
     self.assertEqual('v3', prof.get_filter('identity').version)
     self.assertEqual('v2', prof.get_filter('image').version)
     self.assertEqual('v2', prof.get_filter('network').version)
     self.assertEqual('v1', prof.get_filter('object-store').version)
     self.assertEqual('v1', prof.get_filter('orchestration').version)
     self.assertEqual('v1', prof.get_filter('key-manager').version)
     self.assertEqual('v1', prof.get_filter('metering').version)
     self.assertEqual('v2', prof.get_filter('volume').version)
     self.assertEqual('v1', prof.get_filter('messaging').version)