Move from UserPreference to Profile

This is just a big name swap to move away from UserPreference to Profile
so it can be properly referenced in the summit talk. See #1435953

Change-Id: Iaa45fce0c8aacc9315070f8525a13f2e43f05a9e
Closes-Bug: 1435953
This commit is contained in:
Brian Curtin 2015-05-17 22:29:00 -07:00 committed by Terry Howe
parent 6c6cc5a030
commit 7fc1888d19
14 changed files with 162 additions and 162 deletions

View File

@ -57,7 +57,7 @@ with OpenStack services.
:maxdepth: 1 :maxdepth: 1
connection connection
user_preference profile
Once you have a *Connection* instance, the following services may be exposed Once you have a *Connection* instance, the following services may be exposed
to you. Your user preferences determine the full set of exposed services, to you. Your user preferences determine the full set of exposed services,

View File

@ -0,0 +1,9 @@
Profile
=======
.. automodule:: openstack.profile
Profile Object
--------------
.. autoclass:: openstack.profile.Profile
:members:

View File

@ -1,9 +0,0 @@
UserPreference
==============
.. automodule:: openstack.user_preference
UserPreference Object
---------------------
.. autoclass:: openstack.user_preference.UserPreference
:members:

View File

@ -8,11 +8,11 @@ Usage
To use python-openstacksdk in a project:: To use python-openstacksdk in a project::
from openstack import connection from openstack import connection
from openstack import user_preference from openstack import profile
# First, specify your preferences # First, specify your preferences
pref = user_preference.UserPreference() prof = profile.Profile()
pref.set_region('network', 'zion') prof.set_region('network', 'zion')
# Second, create your authorization arguments # Second, create your authorization arguments
auth_args = { auth_args = {
@ -23,7 +23,7 @@ To use python-openstacksdk in a project::
} }
# Third, create a connection # Third, create a connection
conn = connection.Connection(preference=pref, **auth_args) conn = connection.Connection(preference=prof, **auth_args)
# Finally, access your desired services # Finally, access your desired services
network = conn.network.find_network("matrix") network = conn.network.find_network("matrix")

View File

@ -40,7 +40,7 @@ import sys
import traceback import traceback
import uuid import uuid
from openstack import user_preference from openstack import profile
from openstack import utils from openstack import utils
_logger = logging.getLogger(__name__) _logger = logging.getLogger(__name__)
@ -100,12 +100,12 @@ def get_open_fds():
return [d.replace('\000', '|') for d in procs_list] return [d.replace('\000', '|') for d in procs_list]
class UserPreferenceAction(argparse.Action): class ProfileAction(argparse.Action):
"""A custom action to parse user preferences as key=value pairs """A custom action to parse user proferences as key=value pairs
Stores results in users preferences object. Stores results in users proferences object.
""" """
pref = user_preference.UserPreference() prof = profile.Profile()
@classmethod @classmethod
def env(cls, *vars): def env(cls, *vars):
@ -114,8 +114,8 @@ class UserPreferenceAction(argparse.Action):
if values is None: if values is None:
continue continue
cls.set_option(v, values) cls.set_option(v, values)
return cls.pref return cls.prof
return cls.pref return cls.prof
@classmethod @classmethod
def set_option(cls, var, values): def set_option(cls, var, values):
@ -128,20 +128,20 @@ class UserPreferenceAction(argparse.Action):
if '=' in kvp: if '=' in kvp:
service, value = kvp.split('=') service, value = kvp.split('=')
else: else:
service = cls.pref.ALL service = cls.prof.ALL
value = kvp value = kvp
if var == 'name': if var == 'name':
cls.pref.set_name(service, value) cls.prof.set_name(service, value)
elif var == 'region': elif var == 'region':
cls.pref.set_region(service, value) cls.prof.set_region(service, value)
elif var == 'version': elif var == 'version':
cls.pref.set_version(service, value) cls.prof.set_version(service, value)
elif var == 'visibility': elif var == 'visibility':
cls.pref.set_visibility(service, value) cls.prof.set_visibility(service, value)
def __call__(self, parser, namespace, values, option_string=None): def __call__(self, parser, namespace, values, option_string=None):
if getattr(namespace, self.dest, None) is None: if getattr(namespace, self.dest, None) is None:
setattr(namespace, self.dest, UserPreferenceAction.pref) setattr(namespace, self.dest, ProfileAction.prof)
self.set_option(option_string, values) self.set_option(option_string, values)
@ -248,34 +248,34 @@ def option_parser():
) )
parser.add_argument( parser.add_argument(
'--os-api-name', '--os-api-name',
dest='user_preferences', dest='preferences',
metavar='<service>=<name>', metavar='<service>=<name>',
action=UserPreferenceAction, action=ProfileAction,
default=UserPreferenceAction.env('OS_API_NAME'), default=ProfileAction.env('OS_API_NAME'),
help='Desired API names defaults to env[OS_API_NAME]', help='Desired API names defaults to env[OS_API_NAME]',
) )
parser.add_argument( parser.add_argument(
'--os-api-region', '--os-api-region',
dest='user_preferences', dest='preferences',
metavar='<service>=<region>', metavar='<service>=<region>',
action=UserPreferenceAction, action=ProfileAction,
default=UserPreferenceAction.env('OS_API_REGION', 'OS_REGION_NAME'), default=ProfileAction.env('OS_API_REGION', 'OS_REGION_NAME'),
help='Desired API region defaults to env[OS_API_REGION]', help='Desired API region defaults to env[OS_API_REGION]',
) )
parser.add_argument( parser.add_argument(
'--os-api-version', '--os-api-version',
dest='user_preferences', dest='preferences',
metavar='<service>=<version>', metavar='<service>=<version>',
action=UserPreferenceAction, action=ProfileAction,
default=UserPreferenceAction.env('OS_API_VERSION'), default=ProfileAction.env('OS_API_VERSION'),
help='Desired API versions defaults to env[OS_API_VERSION]', help='Desired API versions defaults to env[OS_API_VERSION]',
) )
parser.add_argument( parser.add_argument(
'--os-api-visibility', '--os-api-visibility',
dest='user_preferences', dest='preferences',
metavar='<service>=<visibility>', metavar='<service>=<visibility>',
action=UserPreferenceAction, action=ProfileAction,
default=UserPreferenceAction.env('OS_API_VISIBILITY'), default=ProfileAction.env('OS_API_VISIBILITY'),
help='Desired API visibility defaults to env[OS_API_VISIBILITY]', help='Desired API visibility defaults to env[OS_API_VISIBILITY]',
) )
verify_group = parser.add_mutually_exclusive_group() verify_group = parser.add_mutually_exclusive_group()

View File

@ -34,7 +34,7 @@ def make_connection(opts):
auth = cloud.config['auth'] auth = cloud.config['auth']
if 'insecure' in cloud.config: if 'insecure' in cloud.config:
auth['verify'] = cloud.config['insecure'] auth['verify'] = cloud.config['insecure']
conn = connection.Connection(preference=opts.user_preferences, **auth) conn = connection.Connection(profile=opts.preferences, **auth)
return conn return conn

View File

@ -17,7 +17,7 @@ for service identifiers and user service preferences. Each
associate the resource with a service. An example of a service identifier associate the resource with a service. An example of a service identifier
would be ``openstack.compute.compute_service.ComputeService``. would be ``openstack.compute.compute_service.ComputeService``.
The preferences are stored in the The preferences are stored in the
:class:`~openstack.user_preference.UserPreference` object. :class:`~openstack.profile.Profile` object.
The service preference and the service identifier are joined to create a The service preference and the service identifier are joined to create a
filter to match a service. filter to match a service.

View File

@ -14,7 +14,7 @@
The :class:`~openstack.connection.Connection` class is the primary interface The :class:`~openstack.connection.Connection` class is the primary interface
to the Python SDK it maintains a context for a connection to a cloud provider. to the Python SDK it maintains a context for a connection to a cloud provider.
The connection has an attribute to access each supported service. The service The connection has an attribute to access each supported service. The service
attributes are created dynamically based on user preferences and the service attributes are created dynamically based on user profiles and the service
catalog. catalog.
Examples Examples
@ -70,7 +70,7 @@ _logger = logging.getLogger(__name__)
class Connection(object): class Connection(object):
def __init__(self, transport=None, authenticator=None, preference=None, def __init__(self, transport=None, authenticator=None, profile=None,
verify=True, user_agent=None, verify=True, user_agent=None,
auth_plugin=None, **auth_args): auth_plugin=None, **auth_args):
"""Create a context for a connection to a cloud provider. """Create a context for a connection to a cloud provider.
@ -94,11 +94,11 @@ class Connection(object):
If this parameter is not passed in, the connection will create an If this parameter is not passed in, the connection will create an
authenticator. authenticator.
:type authenticator: :class:`~openstack.auth.base.BaseAuthPlugin` :type authenticator: :class:`~openstack.auth.base.BaseAuthPlugin`
:param preference: If the user has any special preferences such as the :param profile: If the user has any special profiles such as the
service name, region, version or visibility, they may be provided service name, region, version or visibility, they may be provided
in the preference object. If no preferences are provided, the in the profile object. If no profiles are provided, the
services that appear first in the service catalog will be used. services that appear first in the service catalog will be used.
:type preference: :class:`~openstack.user_preference.UserPreference` :type profile: :class:`~openstack.profile.Profile`
:param bool verify: If a transport is not provided to the connection, :param bool verify: If a transport is not provided to the connection,
this parameter will be used to create a transport. If ``verify`` this parameter will be used to create a transport. If ``verify``
is set to true, which is the default, the SSL cert will be is set to true, which is the default, the SSL cert will be
@ -123,7 +123,7 @@ class Connection(object):
auth_plugin, auth_plugin,
**auth_args) **auth_args)
self.session = session.Session(self.transport, self.authenticator, self.session = session.Session(self.transport, self.authenticator,
preference) profile)
self._open() self._open()
def _create_transport(self, transport, verify, user_agent): def _create_transport(self, transport, verify, user_agent):

View File

@ -11,33 +11,33 @@
# under the License. # under the License.
""" """
:class:`~openstack.user_preference.UserPreference` is the class that is used to :class:`~openstack.profile.Profile` is the class that is used to
define the various preferences for different services. The preferences that define the various preferences for different services. The preferences that
are currently supported are service name, region, version and visibility. are currently supported are service name, region, version and visibility.
The :class:`~openstack.user_preference.UserPreference` and the The :class:`~openstack.profile.Profile` and the
:class:`~openstack.connection.Connection` classes are the most important :class:`~openstack.connection.Connection` classes are the most important
user facing classes. user facing classes.
Examples Examples
-------- --------
The :class:`~openstack.user_preference.UserPreference` class is constructed The :class:`~openstack.profile.Profile` class is constructed
with no arguments. with no arguments.
Set Methods Set Methods
~~~~~~~~~~~ ~~~~~~~~~~~
The user preferences are set based on the service type. Service type would A user's preferences are set based on the service type. Service type would
normally be something like 'compute', 'identity', 'object-store', etc.:: normally be something like 'compute', 'identity', 'object-store', etc.::
from openstack import user_preference from openstack import profile
pref = user_preference.UserPreference() prof = profile.Profile()
pref.set_name('compute', 'matrix') prof.set_name('compute', 'matrix')
pref.set_region(pref.ALL, 'zion') prof.set_region(prof.ALL, 'zion')
pref.set_version('identity', 'v3') prof.set_version('identity', 'v3')
pref.set_visibility('object-store', 'internal') prof.set_visibility('object-store', 'internal')
for service in pref.get_services(): for service in prof.get_services():
print str(pref.get_preference(service.service_type)) print str(prof.get_preference(service.service_type))
The resulting preference print out would look something like:: The resulting preference print out would look something like::
@ -67,15 +67,15 @@ from openstack.telemetry import telemetry_service
from openstack.volume import volume_service from openstack.volume import volume_service
class UserPreference(object): class Profile(object):
ALL = "*" ALL = "*"
"""Wildcard service identifier representing all services.""" """Wildcard service identifier representing all services."""
def __init__(self): def __init__(self):
"""User preference for each service. """Preferences for each service.
Create a new :class:`~openstack.user_preference.UserPreference` Create a new :class:`~openstack.profile.Profile`
object with no preferences defined, but knowledge of the services. object with no preferences defined, but knowledge of the services.
Services are identified by their service type, e.g.: 'identity', Services are identified by their service type, e.g.: 'identity',
'compute', etc. 'compute', etc.

View File

@ -59,7 +59,7 @@ Creating a new object::
import logging import logging
from openstack import user_preference from openstack import profile as _profile
from openstack import utils from openstack import utils
@ -68,7 +68,7 @@ _logger = logging.getLogger(__name__)
class Session(object): class Session(object):
def __init__(self, transport, authenticator, preference=None): def __init__(self, transport, authenticator, profile=None):
"""Create a new object with a transport and authenticator. """Create a new object with a transport and authenticator.
Session layer which uses the transport for communication. The Session layer which uses the transport for communication. The
@ -80,11 +80,11 @@ class Session(object):
:param authenticator: An authenticator that provides get_token and :param authenticator: An authenticator that provides get_token and
get_endpoint methods for the session. get_endpoint methods for the session.
:type authenticator: :class:`~openstack.auth.base.BaseAuthPlugin` :type authenticator: :class:`~openstack.auth.base.BaseAuthPlugin`
:param preference: If the user has any special preferences such as the :param profile: If the user has any special profiles such as the
service name, region, version or visibility, they may be provided service name, region, version or visibility, they may be provided
in the preference object. If no preferences are provided, the in the profile object. If no profiles are provided, the
services that appear first in the service catalog will be used. services that appear first in the service catalog will be used.
:type preference: :class:`~openstack.user_preference.UserPreference` :type profile: :class:`~openstack.profile.Profile`
All the other methods of the session accept the following parameters: All the other methods of the session accept the following parameters:
@ -99,7 +99,7 @@ class Session(object):
""" """
self.transport = transport self.transport = transport
self.authenticator = authenticator self.authenticator = authenticator
self.preference = preference or user_preference.UserPreference() self.profile = profile or _profile.Profile()
def _request(self, path, method, service=None, authenticate=True, def _request(self, path, method, service=None, authenticate=True,
**kwargs): **kwargs):
@ -124,9 +124,9 @@ class Session(object):
if token: if token:
headers['X-Auth-Token'] = token headers['X-Auth-Token'] = token
if service: if service:
preference = self.preference.get_preference(service.service_type) profile = self.profile.get_preference(service.service_type)
if preference: if profile:
service = preference.join(service) service = profile.join(service)
endpoint = self.authenticator.get_endpoint(self.transport, service) endpoint = self.authenticator.get_endpoint(self.transport, service)
url = utils.urljoin(endpoint, path) url = utils.urljoin(endpoint, path)
@ -158,5 +158,5 @@ class Session(object):
return self._request(path, 'PATCH', **kwargs) return self._request(path, 'PATCH', **kwargs)
def get_services(self): def get_services(self):
"""Get list of services from preferences.""" """Get list of services from profiles."""
return self.preference.get_services() return self.profile.get_services()

View File

@ -16,7 +16,7 @@ import unittest
import os_client_config import os_client_config
from openstack import connection from openstack import connection
from openstack import user_preference from openstack import profile
from openstack import utils from openstack import utils
@ -26,15 +26,15 @@ class BaseFunctionalTest(unittest.TestCase):
name = os.getenv('OS_CLOUD', 'test_cloud') name = os.getenv('OS_CLOUD', 'test_cloud')
test_cloud = os_client_config.OpenStackConfig().get_one_cloud(name) test_cloud = os_client_config.OpenStackConfig().get_one_cloud(name)
pref = user_preference.UserPreference() prof = profile.Profile()
pref.set_region(pref.ALL, test_cloud.region) prof.set_region(prof.ALL, test_cloud.region)
if test_cloud.debug: if test_cloud.debug:
utils.enable_logging(True) utils.enable_logging(True)
auth = test_cloud.config['auth'] auth = test_cloud.config['auth']
if 'insecure' in test_cloud.config: if 'insecure' in test_cloud.config:
auth['verify'] = test_cloud.config['insecure'] auth['verify'] = test_cloud.config['insecure']
cls.conn = connection.Connection(preference=pref, **auth) cls.conn = connection.Connection(profile=prof, **auth)
@classmethod @classmethod
def assertIs(cls, expected, actual): def assertIs(cls, expected, actual):

View File

@ -16,10 +16,10 @@ from openstack.auth.identity import v2
from openstack.auth import service_filter from openstack.auth import service_filter
from openstack import connection from openstack import connection
from openstack import exceptions from openstack import exceptions
from openstack import profile
from openstack import resource from openstack import resource
from openstack.tests.unit import base from openstack.tests.unit import base
from openstack import transport from openstack import transport
from openstack import user_preference
class TestConnection(base.TestCase): class TestConnection(base.TestCase):
@ -27,7 +27,7 @@ class TestConnection(base.TestCase):
super(TestConnection, self).setUp() super(TestConnection, self).setUp()
self.xport = transport.Transport() self.xport = transport.Transport()
self.auth = v2.Token(auth_url='http://127.0.0.1/v2', token='b') self.auth = v2.Token(auth_url='http://127.0.0.1/v2', token='b')
self.pref = user_preference.UserPreference() self.prof = profile.Profile()
self.conn = connection.Connection(authenticator=mock.MagicMock(), self.conn = connection.Connection(authenticator=mock.MagicMock(),
transport=mock.MagicMock()) transport=mock.MagicMock())
self.conn.session = mock.MagicMock() self.conn.session = mock.MagicMock()
@ -100,12 +100,12 @@ class TestConnection(base.TestCase):
args = { args = {
'transport': self.xport, 'transport': self.xport,
'authenticator': self.auth, 'authenticator': self.auth,
'preference': self.pref, 'profile': self.prof,
} }
conn = connection.Connection(**args) conn = connection.Connection(**args)
self.assertEqual(self.xport, conn.session.transport) self.assertEqual(self.xport, conn.session.transport)
self.assertEqual(self.auth, conn.session.authenticator) self.assertEqual(self.auth, conn.session.authenticator)
self.assertEqual(self.pref, conn.session.preference) self.assertEqual(self.prof, conn.session.profile)
self.assertEqual('openstack.compute.v2._proxy', self.assertEqual('openstack.compute.v2._proxy',
conn.compute.__class__.__module__) conn.compute.__class__.__module__)
self.assertEqual('openstack.database.v1._proxy', self.assertEqual('openstack.database.v1._proxy',

View File

@ -0,0 +1,81 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack import exceptions
from openstack import profile
from openstack.tests.unit import base
class TestProfile(base.TestCase):
def test_init(self):
prof = profile.Profile()
expected = [
'compute',
'database',
'identity',
'image',
'keystore',
'metering',
'metric',
'network',
'object-store',
'orchestration',
'volume',
]
self.assertEqual(expected, prof.service_names)
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('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)
def test_set_version_bad_service(self):
prof = profile.Profile()
self.assertRaises(exceptions.SDKException, prof.set_version, 'bogus',
'v2')
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)

View File

@ -1,81 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack import exceptions
from openstack.tests.unit import base
from openstack import user_preference
class TestUserPreference(base.TestCase):
def test_init(self):
pref = user_preference.UserPreference()
expected = [
'compute',
'database',
'identity',
'image',
'keystore',
'metering',
'metric',
'network',
'object-store',
'orchestration',
'volume',
]
self.assertEqual(expected, pref.service_names)
def test_set(self):
pref = user_preference.UserPreference()
self.assertEqual(None, pref.get_preference('compute'))
pref.set_version('compute', 'v2')
self.assertEqual('v2', pref.get_preference('compute').version)
self.assertEqual(None, pref.get_preference('database'))
pref.set_version('database', 'v3')
self.assertEqual('v3', pref.get_preference('database').version)
self.assertEqual(None, pref.get_preference('identity'))
pref.set_version('identity', 'v4')
self.assertEqual('v4', pref.get_preference('identity').version)
self.assertEqual(None, pref.get_preference('image'))
pref.set_version('image', 'v5')
self.assertEqual('v5', pref.get_preference('image').version)
self.assertEqual(None, pref.get_preference('metering'))
pref.set_version('metering', 'v6')
self.assertEqual('v6', pref.get_preference('metering').version)
self.assertEqual(None, pref.get_preference('metric'))
pref.set_version('metric', 'v9')
self.assertEqual('v9', pref.get_preference('metric').version)
self.assertEqual(None, pref.get_preference('network'))
pref.set_version('network', 'v7')
self.assertEqual('v7', pref.get_preference('network').version)
self.assertEqual(None, pref.get_preference('object-store'))
pref.set_version('object-store', 'v8')
self.assertEqual('v8', pref.get_preference('object-store').version)
self.assertEqual(None, pref.get_preference('orchestration'))
pref.set_version('orchestration', 'v9')
self.assertEqual('v9', pref.get_preference('orchestration').version)
def test_set_version_bad_service(self):
pref = user_preference.UserPreference()
self.assertRaises(exceptions.SDKException, pref.set_version, 'bogus',
'v2')
def test_set_all(self):
pref = user_preference.UserPreference()
pref.set_name(pref.ALL, 'fee')
pref.set_region(pref.ALL, 'fie')
pref.set_version(pref.ALL, 'foe')
pref.set_visibility(pref.ALL, 'public')
for service in pref.service_names:
self.assertEqual('fee', pref.get_preference(service).service_name)
self.assertEqual('fie', pref.get_preference(service).region)
self.assertEqual('foe', pref.get_preference(service).version)
self.assertEqual('public', pref.get_preference(service).visibility)